├── .DS_Store
├── LICENSE
├── README.md
├── black.py
├── details
├── Brochure.pdf
└── README.md
├── display.sh
├── docs
├── .DS_Store
├── Product Images
│ ├── IMG_5541.HEIC
│ ├── IMG_5542.HEIC
│ ├── IMG_5543.HEIC
│ └── IMG_5544.HEIC
├── autoconnect.md
├── desmos.md
├── graduation.png
├── index.html
├── instructions.md
├── p5.js
├── serials.txt
├── setting-up-wifi-connect.md
├── sketch.js
└── ydb.jpeg
├── green.py
├── red.py
├── server.sh
├── site.sh
├── src
├── .DS_Store
├── .gitattributes
├── .gitignore
├── assets
│ ├── .DS_Store
│ ├── clock
│ │ ├── classic-0.png
│ │ ├── classic-1.png
│ │ ├── classic-2.png
│ │ ├── classic-3.png
│ │ ├── classic-4.png
│ │ ├── classic-5.png
│ │ ├── classic-6.png
│ │ ├── classic-7.png
│ │ ├── classic-8.png
│ │ ├── classic-9.png
│ │ ├── modern-0.png
│ │ ├── modern-1.png
│ │ ├── modern-2.png
│ │ ├── modern-3.png
│ │ ├── modern-4.png
│ │ ├── modern-5.png
│ │ ├── modern-6.png
│ │ ├── modern-7.png
│ │ ├── modern-8.png
│ │ └── modern-9.png
│ ├── codes
│ │ ├── ..png
│ │ ├── 0.png
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── 3.png
│ │ ├── 4.png
│ │ ├── 5.png
│ │ ├── 6.png
│ │ ├── 7.png
│ │ ├── 8.png
│ │ └── 9.png
│ ├── error.png
│ ├── gifs
│ │ ├── .DS_Store
│ │ ├── brick.gif
│ │ ├── egypt.gif
│ │ ├── large
│ │ │ ├── brick.gif
│ │ │ ├── egypt.gif
│ │ │ └── rap.gif
│ │ └── rap.gif
│ ├── images
│ │ ├── led.jpg
│ │ └── top.jpg
│ ├── loading.png
│ ├── off.png
│ ├── paused.png
│ └── wifi.png
├── authentication.py
├── autobrightness.py
├── clock.py
├── driver.py
├── exceptions.py
├── fun.py
├── index.py
├── ip.py
├── ipdisplay.py
├── light.py
├── listen.py
├── nightshift.py
├── nonlinearity.py
├── publiship.py
├── requirements.txt
├── run.py
├── secrets.example.py
├── settings.py
├── spotipy
│ ├── .DS_Store
│ ├── README.md
│ ├── __init__.py
│ ├── client.py
│ ├── exceptions.py
│ ├── oauth2.py
│ └── util.py
└── testscripts
│ ├── README.md
│ ├── autoconnect.py
│ ├── cover.py
│ ├── display.py
│ ├── displaybasictest.py
│ ├── fade.py
│ ├── find.py
│ ├── gif.py
│ ├── gorgeous.wav
│ ├── ip.py
│ ├── lightsensor.py
│ ├── listen.py
│ ├── mbdtf.py
│ ├── print1.py
│ ├── print2.py
│ ├── recorded.wav
│ ├── responsetime.py
│ ├── silence.m4a
│ ├── swipe.py
│ ├── talking.m4a
│ └── test.py
├── start.sh
└── supreme.py
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/.DS_Store
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [Frame](https://patrick.app/project/frame)
2 | A Summer of Making Project by Addison and Patrick.
3 | 
4 |
5 |
6 | **Funded by GitHub through Hack Club.**
7 |
8 | ### A Note About the Code
9 | As of right now, the code contains both NodeJS files and Python files. Since I'm better in JS, I started by writing most in JS then switched to Python.
10 |
11 | The `./testscripts/` folder contains most individual components of the application to be tested all at once. It is no longer maintained.
12 |
13 | The `./nodetest/` folder is for the initial testing of the Audd.io API. It is no longer maintained.
14 |
15 | ## Some milestones
16 |
17 | >Due to the data wire from the Raspberry Pi to the led strip acting as an antenna, and producing random, glitchy, flashing patterns, we decided to replace the data line as well as the common ground wire with a shielded wire taken from a scrap usb cable, which completely eliminated the display errors, even with a slightly longer wire from the pi to the led strip.
18 |
19 | >To adjust for bad colors in the display at some point, we used LED non-linearity compensation with a power vs intensity curve. We used the best tool ever for this: Desmos! [Here's](https://www.desmos.com/calculator/maqayzhvgg) the link to the graph.
20 |
21 | ## About
22 | This is a repository dedicated to the smart album cover display.
23 |
24 | Running on a Raspberry Pi, this recognizes the live music playing and displays it on a 16x16 grid made with LED strips.
25 |
26 | ### Usage
27 | Create an Audd.io API Key and place it in `./key`. You can use "test" as the key for up to 10 instances.
28 |
29 | After installing all packages, run the following commmand:
30 | ```bash
31 | $ python3 run.py
32 | ```
33 | If that causes a permissions error, run
34 | ```bash
35 | $ sudo python3 run.py
36 | ```
37 |
38 | To set brightness 10%, run
39 | ```bash
40 | $ python3 run.py 10
41 | ```
42 |
43 | To run in testing mode (no screen), run
44 | ```bash
45 | $ python3 run.py test
46 | ```
47 |
48 | ### The Software
49 |
50 | Python script records live audio, then uses the [audd.io](https://audd.io) service for music recognition.
51 |
52 | Then sets the pixels to whatever the album cover receives.
53 |
54 | Note: `authentication.py` doesn't do anything useful... yet!
55 |
56 | ### The Hardware
57 |
58 |
59 |
60 |
61 | See more at [The Lab](https://thelab.gallery/user/AddisonHenikoff)
62 |
--------------------------------------------------------------------------------
/black.py:
--------------------------------------------------------------------------------
1 |
2 | import board
3 | import neopixel
4 | pixels = neopixel.NeoPixel(board.D12, 30)
5 |
6 | pixels[0] = (0, 0, 0)
7 | pixels[1] = (0, 0, 0)
8 |
--------------------------------------------------------------------------------
/details/Brochure.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/details/Brochure.pdf
--------------------------------------------------------------------------------
/details/README.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/display.sh:
--------------------------------------------------------------------------------
1 | cd src
2 | # python3 run.py test
3 | sudo python3 run.py auto
--------------------------------------------------------------------------------
/docs/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/.DS_Store
--------------------------------------------------------------------------------
/docs/Product Images/IMG_5541.HEIC:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/Product Images/IMG_5541.HEIC
--------------------------------------------------------------------------------
/docs/Product Images/IMG_5542.HEIC:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/Product Images/IMG_5542.HEIC
--------------------------------------------------------------------------------
/docs/Product Images/IMG_5543.HEIC:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/Product Images/IMG_5543.HEIC
--------------------------------------------------------------------------------
/docs/Product Images/IMG_5544.HEIC:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/Product Images/IMG_5544.HEIC
--------------------------------------------------------------------------------
/docs/autoconnect.md:
--------------------------------------------------------------------------------
1 | # Frame Autoconnect
2 |
3 | ## What is it?
4 | To connect to your Frame, that is to sign in with spotify, or to setup listening, or configure settings, you need to know the Frame's ip address on your network.
5 |
6 | Of course, each device on a network has its own local ip address. You use this ip address to connect to Frame. So the goal of autoconnect is to find the Frame's local ip address.
7 |
8 | ## From Frame
9 |
10 | To do this, we could just keep trying ips... but that's like thousands of possibilities. We also could ping around on the local network to try to find a raspberry pi, but there might be other pis on the same network, and this often isn't possible due to device security concerns.
11 |
12 | So, to combat this, Frame sends its local ip to the server. Every 1 minute, or on start, it checks to see if its local ip has changed. If so, it makes the following request which uploads the ip:
13 |
14 | `https://patrick.today/frame/set/?ip=&frameId=`
15 |
16 | It knows its local ip address, and the Frame ID is set in `secrets.py`.
17 |
18 | ## From your Phone
19 |
20 | You make a request to:
21 |
22 | `https://patrick.today/frame/connect`
23 |
24 | On the background, here is what happens:
25 |
26 | - The server grabs the phone's global ip
27 | - The server finds a frame with the same global ip (that means the frame and phone are on the same network!)
28 | - If it can't find one, it throws an error
29 | - Once the frame is found, the local IP is taken from a database
30 | - The phone is redirected to the proper local ip. That's `` above
31 |
--------------------------------------------------------------------------------
/docs/desmos.md:
--------------------------------------------------------------------------------
1 | # Desmos
2 | Auto brightness is important to keep the user's eyes from hurting, and is generally needed.
3 |
4 | With a light sensor we can record the **lux** of the room, which is some unit; but it's kind of arbitrary.
5 |
6 | Really, we need to convert the lux to a brighntess value of the LEDs.
7 |
8 | ## Lux, a runtime variable, needs to be mapped to an optimal brightness between 0 and 1.
9 |
10 | #### Let's say lux has a maximum value of `M`
11 |
12 | Let's call the mapping function f(x), where f is the output brightness [0,1]
13 |
14 | The most basic mapping function would be
15 | ```
16 | f(x) = x/M
17 | ```
18 |
19 | Thus, if the lux is the maximum **M**, the brightness will be 1.
20 |
21 | On the same hand, if the lux is **0** (it's minimum), the brightness will be 0.
22 |
23 | Of course, this won't work. If the brightneess is 0, the screen would be off.
24 |
25 | ## Thus, we need to find this function `f(x)`
26 |
27 |
--------------------------------------------------------------------------------
/docs/graduation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/graduation.png
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/docs/instructions.md:
--------------------------------------------------------------------------------
1 | # Instruction for setup
2 | Run on Raspberry Pi 4
3 |
4 | ## Install Raspbian
5 | Using the Raspberry Pi Imager, simply install Raspbian (32 Bit)
6 |
7 | ## Clone Git Repository
8 | `sudo git clone https://github.com/phultquist/smart-album-cover`
9 |
10 | `cd smart-album-cover`
11 |
12 | `cd src`
13 |
14 | `sudo git clone https://github.com/phultquist/resize`
15 |
16 | `sudo git clone https://github.com/phultquist/mobile`
17 |
18 | ## Install Requirements
19 |
20 | `sudo pip3 install -r requirements.txt`
21 | This will take a while (about 5-10 minutes)
22 |
23 | `sudo pip3 install rpi_ws281x adafruit-circuitpython-neopixel`
24 |
25 | `sudo python3 -m pip install --force-reinstall adafruit-blinka`
26 |
27 | `sudo pip3 install adafruit-circuitpython-tsl2591`
28 |
29 | Finally, install schedule
30 | `sudo pip3 install schedule`
31 |
32 | ## Install Microphone Drivers
33 | `git clone https://github.com/respeaker/seeed-voicecard`
34 |
35 | `cd seeed-voicecard`
36 |
37 | `sudo ./install.sh --compat-kernel`
38 |
39 | `sudo reboot`
40 |
41 | ## Configure Pi
42 | > Run `sudo raspi-config` on the command line, then use the arrow keys to select 'Interfacing Options' and 'I2C' to tell the RasPi to enable the I2C interface. Then select 'Finish' and reboot the RasPi.
43 |
44 | ## Run the Program
45 | `sudo python3 run.py auto`
46 | See more in ../README.md. You'll be asked to sign in first
47 |
48 | ## Sign into spotify
49 | Run `sudo python3 authentication.py`
50 |
--------------------------------------------------------------------------------
/docs/serials.txt:
--------------------------------------------------------------------------------
1 | alpaca
2 | onion
3 | horseshoe
4 | daisy
5 | mist
6 | strawberry
7 | pythagoras
8 | pollen
9 | bee
10 | mountain
11 | bamboo
12 | volcano
13 | cantaloupe
14 | bounce
15 | quinoa
16 | beagle
17 | squeeze
18 | cereal
19 | cheddhar
20 | gelato
21 |
--------------------------------------------------------------------------------
/docs/setting-up-wifi-connect.md:
--------------------------------------------------------------------------------
1 | # Setting up Wifi-Connect
2 | This should only be done once
3 |
4 | `bash <(curl -L https://github.com/balena-io/wifi-connect/raw/master/scripts/raspbian-install.sh)`
5 |
6 | When the y/N prompt appears, type `Y`. Note it must be uppercase.
7 |
8 | `sudo wifi-connect --portal-ssid Frame`
9 |
10 | Go on your phone, or any device with internet connectivity. Connect to the `Frame` WiFi network. Then, input your local network ssid and password.
--------------------------------------------------------------------------------
/docs/sketch.js:
--------------------------------------------------------------------------------
1 | const queryString = window.location.search;
2 | const urlParams = new URLSearchParams(queryString);
3 | let l = parseInt(urlParams.get('n')) || 16;
4 | console.log(l);
5 | let input, button
6 |
7 | let img, cimg;
8 |
9 | //xxx
10 | // let imgname = 'https://i.scdn.co/image/ab67616d00004851806c160566580d6335d1f16c'
11 |
12 | //graduation
13 | let imgname = 'https://i.scdn.co/image/ab67616d000048519bbd79106e510d13a9a5ec33'
14 |
15 | //young dumb and broke
16 | // let imgname = 'https://i.scdn.co/image/ab67616d00004851988ede5e1276e758b5f9e577'
17 |
18 | //runaway
19 | // let imgname = 'https://i.scdn.co/image/ab67616d00004851d9194aa18fa4c9362b47464f'
20 |
21 | function preload() {
22 | img = loadImage(imgname);
23 | cimg = loadImage(imgname)
24 | }
25 |
26 | function setup() {
27 | createCanvas(830, 400);
28 |
29 | img.resize(l, l);
30 | img.loadPixels();
31 |
32 | let pix = img.pixels;
33 | let pixels = [];
34 | let correctRed = false;
35 | for (i = 0; i < pix.length; i += 4) {
36 | if (pix[i] < 255 && pix[i] > 230 && correctRed) {
37 | pixels.push([255, 0, 0]);
38 | } else {
39 | pixels.push([pix[i], pix[i + 1], pix[i + 2]]);
40 | }
41 | }
42 |
43 |
44 | let grouped = groupPixels(pixels)
45 | // console.log(grouped);
46 | let structured = structure(grouped)
47 |
48 | drawGrid(structured, 0, false)
49 | // return
50 |
51 |
52 |
53 |
54 |
55 |
56 | cimg.loadPixels()
57 |
58 | let raw = cimg.pixels;
59 | let org = []
60 | let cpix = [];
61 |
62 | for (i = 0; i < raw.length; i += 4) {
63 | org.push([raw[i], raw[i + 1], raw[i + 2]]);
64 | }
65 |
66 | org = groupPixels(org);
67 | // console.log(org);
68 | let stepsize = cimg.width / l;
69 | console.log(stepsize);
70 | for (x = 0; x < org.length; x += stepsize) {
71 | let row = org[x]
72 | let smallrow = []
73 | for (y = 0; y < row.length; y += stepsize) {
74 | let toAvg = []
75 | for (a = 0; a < stepsize; a++) {
76 | for (b = 0; b < stepsize; b++) {
77 | toAvg.push(org[x + a][y + b])
78 | }
79 | }
80 | for (o = 0; o < 50; o++) {
81 | // toAvg.push(org[x+2][y+2])
82 | }
83 | // let avg = averagePixels([org[x][y], org[x][y +1], org[x+1][y], org[x+1][y+1]])
84 | let avg = generalize(toAvg)
85 | smallrow.push(avg);
86 | }
87 | cpix.push(smallrow);
88 | }
89 |
90 | let rawStructured = structure(cpix)
91 | drawGrid(rawStructured, width / 2 + 10, false)
92 | }
93 |
94 | function drawGrid(pixels, offset, snake) {
95 | noStroke();
96 | let len = height
97 | for (i in pixels) {
98 | let x = i % l,
99 | y = Math.floor(i / l);
100 | if (y % 2 == 1 && snake) {
101 | x = l - 1 - x;
102 | }
103 | fill(pixels[i][0], pixels[i][1], pixels[i][2])
104 |
105 | let pwidth = Math.sqrt(len) * Math.sqrt(len) / l
106 | rect(offset + x * pwidth, y * pwidth, pwidth, pwidth);
107 | }
108 | }
109 |
110 | function structure(grouped) {
111 | let structured = [];
112 | grouped.forEach((group, i) => {
113 | if (i % 2 == 1) {
114 | // group = group.reverse();
115 | }
116 | group.forEach(pixel => {
117 | structured.push(pixel);
118 | })
119 | })
120 |
121 | return structured;
122 | }
123 |
124 | function groupPixels(pixels) {
125 | let sq = Math.sqrt(pixels.length)
126 | console.log(sq);
127 | let grouped = [];
128 | for (j = 0; j < pixels.length; j += sq) {
129 | let group = []
130 | for (k = 0; k < sq; k++) {
131 | group.push(pixels[j + k])
132 | }
133 | grouped.push(group);
134 | }
135 | return grouped
136 | }
137 |
138 |
139 | function generalize(pi) {
140 | let s = 0
141 | let totals = [0, 0, 0]
142 | let transposed = transpose(pi);
143 | // console.log(transposed);
144 | let component;
145 | transposed.forEach((v, i) => {
146 | totals[i] = compensate(average(v))
147 | // totals[i] = compensate(median(v))
148 | })
149 | return totals;
150 | // return totals.map(t => t / pi.length)
151 | }
152 |
153 | let average = (array) => array.reduce((a, b) => a + b) / array.length;
154 |
155 | function transpose(a) {
156 |
157 | // Calculate the width and height of the Array
158 | var w = a.length || 0;
159 | var h = a[0] instanceof Array ? a[0].length : 0;
160 |
161 | // In case it is a zero matrix, no transpose routine needed.
162 | if (h === 0 || w === 0) { return []; }
163 |
164 | /**
165 | * @var {Number} i Counter
166 | * @var {Number} j Counter
167 | * @var {Array} t Transposed data is stored in this array.
168 | */
169 | var i, j, t = [];
170 |
171 | // Loop through every item in the outer array (height)
172 | for (i = 0; i < h; i++) {
173 |
174 | // Insert a new row (array)
175 | t[i] = [];
176 |
177 | // Loop through every item per item in outer array (width)
178 | for (j = 0; j < w; j++) {
179 |
180 | // Save transposed data.
181 | t[i][j] = a[j][i];
182 | }
183 | }
184 |
185 | return t;
186 | }
187 |
188 | function median(values) {
189 | if (values.length === 0) return 0;
190 |
191 | values.sort(function (a, b) {
192 | return a - b;
193 | });
194 |
195 | var half = Math.floor(values.length / 2);
196 |
197 | if (values.length % 2)
198 | return values[half];
199 |
200 | return (values[half - 1] + values[half]) / 2.0;
201 | }
202 |
203 | function compensate(original) {
204 | let max = 255
205 | let gamma = 1
206 | return parseInt(pow(original, gamma) * pow(max, 1-gamma))
207 | }
--------------------------------------------------------------------------------
/docs/ydb.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/docs/ydb.jpeg
--------------------------------------------------------------------------------
/green.py:
--------------------------------------------------------------------------------
1 |
2 | import board
3 | import neopixel
4 | pixels = neopixel.NeoPixel(board.D12, 30)
5 |
6 | pixels[0] = (0, 255, 0)
7 |
--------------------------------------------------------------------------------
/red.py:
--------------------------------------------------------------------------------
1 | import board
2 | import neopixel
3 | pixels = neopixel.NeoPixel(board.D12, 30)
4 |
5 | pixels[0] = (255, 0, 0)
6 |
--------------------------------------------------------------------------------
/server.sh:
--------------------------------------------------------------------------------
1 | cd src/mobile
2 | sudo git stash
3 | sudo git pull
4 | cd server
5 | sudo node index.js
--------------------------------------------------------------------------------
/site.sh:
--------------------------------------------------------------------------------
1 | cd src/mobile
2 | # sudo git pull
3 | cd site
4 | sudo npm start
--------------------------------------------------------------------------------
/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/.DS_Store
--------------------------------------------------------------------------------
/src/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/src/.gitignore:
--------------------------------------------------------------------------------
1 | output.mp3
2 | key
3 |
4 | # Byte-compiled / optimized / DLL files
5 | __pycache__/
6 | *.py[cod]
7 | *$py.class
8 |
9 | # C extensions
10 | *.so
11 |
12 | # Distribution / packaging
13 | .Python
14 | build/
15 | develop-eggs/
16 | dist/
17 | downloads/
18 | eggs/
19 | .eggs/
20 | lib/
21 | lib64/
22 | parts/
23 | sdist/
24 | var/
25 | wheels/
26 | pip-wheel-metadata/
27 | share/python-wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .nox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | *.py,cover
54 | .hypothesis/
55 | .pytest_cache/
56 |
57 | # Translations
58 | *.mo
59 | *.pot
60 |
61 | # Django stuff:
62 | *.log
63 | local_settings.py
64 | db.sqlite3
65 | db.sqlite3-journal
66 |
67 | # Flask stuff:
68 | instance/
69 | .webassets-cache
70 |
71 | # Scrapy stuff:
72 | .scrapy
73 |
74 | # Sphinx documentation
75 | docs/_build/
76 |
77 | # PyBuilder
78 | target/
79 |
80 | # Jupyter Notebook
81 | .ipynb_checkpoints
82 |
83 | # IPython
84 | profile_default/
85 | ipython_config.py
86 |
87 | # pyenv
88 | .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # celery beat schedule file
98 | celerybeat-schedule
99 |
100 | # SageMath parsed files
101 | *.sage.py
102 |
103 | # Environments
104 | .env
105 | .venv
106 | env/
107 | venv/
108 | ENV/
109 | env.bak/
110 | venv.bak/
111 |
112 | # Spyder project settings
113 | .spyderproject
114 | .spyproject
115 |
116 | # Rope project settings
117 | .ropeproject
118 |
119 | # mkdocs documentation
120 | /site
121 |
122 | # mypy
123 | .mypy_cache/
124 | .dmypy.json
125 | dmypy.json
126 |
127 | # Pyre type checker
128 | .pyre/
129 |
130 | # Logs
131 | logs
132 | *.log
133 | npm-debug.log*
134 | yarn-debug.log*
135 | yarn-error.log*
136 | lerna-debug.log*
137 |
138 | # Diagnostic reports (https://nodejs.org/api/report.html)
139 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
140 |
141 | # Runtime data
142 | pids
143 | *.pid
144 | *.seed
145 | *.pid.lock
146 |
147 | # Directory for instrumented libs generated by jscoverage/JSCover
148 | lib-cov
149 |
150 | # Coverage directory used by tools like istanbul
151 | coverage
152 | *.lcov
153 |
154 | # nyc test coverage
155 | .nyc_output
156 |
157 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
158 | .grunt
159 |
160 | # Bower dependency directory (https://bower.io/)
161 | bower_components
162 |
163 | # node-waf configuration
164 | .lock-wscript
165 |
166 | # Compiled binary addons (https://nodejs.org/api/addons.html)
167 | build/Release
168 |
169 | # Dependency directories
170 | node_modules/
171 | jspm_packages/
172 |
173 | # Snowpack dependency directory (https://snowpack.dev/)
174 | web_modules/
175 |
176 | # TypeScript cache
177 | *.tsbuildinfo
178 |
179 | # Optional npm cache directory
180 | .npm
181 |
182 | # Optional eslint cache
183 | .eslintcache
184 |
185 | # Microbundle cache
186 | .rpt2_cache/
187 | .rts2_cache_cjs/
188 | .rts2_cache_es/
189 | .rts2_cache_umd/
190 |
191 | # Optional REPL history
192 | .node_repl_history
193 |
194 | # Output of 'npm pack'
195 | *.tgz
196 |
197 | # Yarn Integrity file
198 | .yarn-integrity
199 |
200 | # dotenv environment variables file
201 | .env
202 | .env.test
203 |
204 | # parcel-bundler cache (https://parceljs.org/)
205 | .cache
206 | .parcel-cache
207 |
208 | # Next.js build output
209 | .next
210 | out
211 |
212 | # Nuxt.js build / generate output
213 | .nuxt
214 | dist
215 |
216 | # Gatsby files
217 | .cache/
218 | # Comment in the public line in if your project uses Gatsby and not Next.js
219 | # https://nextjs.org/blog/next-9-1#public-directory-support
220 | # public
221 |
222 | # vuepress build output
223 | .vuepress/dist
224 |
225 | # Serverless directories
226 | .serverless/
227 |
228 | # FuseBox cache
229 | .fusebox/
230 |
231 | # DynamoDB Local files
232 | .dynamodb/
233 |
234 | # TernJS port file
235 | .tern-port
236 |
237 | # Stores VSCode versions used for testing VSCode extensions
238 | .vscode-test
239 |
240 | # yarn v2
241 | .yarn/cache
242 | .yarn/unplugged
243 | .yarn/build-state.yml
244 | .yarn/install-state.gz
245 | .pnp.*
246 | secrets.py
247 | .cache-jdiaalhsw8zdhpcdv391bj5we
248 |
249 | assets/time.png
250 | testscripts/acrcloud.js
--------------------------------------------------------------------------------
/src/assets/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/.DS_Store
--------------------------------------------------------------------------------
/src/assets/clock/classic-0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-0.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-1.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-2.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-3.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-4.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-5.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-6.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-7.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-8.png
--------------------------------------------------------------------------------
/src/assets/clock/classic-9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/classic-9.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-0.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-1.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-2.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-3.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-4.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-5.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-6.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-7.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-8.png
--------------------------------------------------------------------------------
/src/assets/clock/modern-9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/clock/modern-9.png
--------------------------------------------------------------------------------
/src/assets/codes/..png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/..png
--------------------------------------------------------------------------------
/src/assets/codes/0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/0.png
--------------------------------------------------------------------------------
/src/assets/codes/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/1.png
--------------------------------------------------------------------------------
/src/assets/codes/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/2.png
--------------------------------------------------------------------------------
/src/assets/codes/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/3.png
--------------------------------------------------------------------------------
/src/assets/codes/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/4.png
--------------------------------------------------------------------------------
/src/assets/codes/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/5.png
--------------------------------------------------------------------------------
/src/assets/codes/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/6.png
--------------------------------------------------------------------------------
/src/assets/codes/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/7.png
--------------------------------------------------------------------------------
/src/assets/codes/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/8.png
--------------------------------------------------------------------------------
/src/assets/codes/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/codes/9.png
--------------------------------------------------------------------------------
/src/assets/error.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/error.png
--------------------------------------------------------------------------------
/src/assets/gifs/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/.DS_Store
--------------------------------------------------------------------------------
/src/assets/gifs/brick.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/brick.gif
--------------------------------------------------------------------------------
/src/assets/gifs/egypt.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/egypt.gif
--------------------------------------------------------------------------------
/src/assets/gifs/large/brick.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/large/brick.gif
--------------------------------------------------------------------------------
/src/assets/gifs/large/egypt.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/large/egypt.gif
--------------------------------------------------------------------------------
/src/assets/gifs/large/rap.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/large/rap.gif
--------------------------------------------------------------------------------
/src/assets/gifs/rap.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/gifs/rap.gif
--------------------------------------------------------------------------------
/src/assets/images/led.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/images/led.jpg
--------------------------------------------------------------------------------
/src/assets/images/top.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/images/top.jpg
--------------------------------------------------------------------------------
/src/assets/loading.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/loading.png
--------------------------------------------------------------------------------
/src/assets/off.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/off.png
--------------------------------------------------------------------------------
/src/assets/paused.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/paused.png
--------------------------------------------------------------------------------
/src/assets/wifi.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/assets/wifi.png
--------------------------------------------------------------------------------
/src/authentication.py:
--------------------------------------------------------------------------------
1 | # import spotify
2 | # print(spotify.song())
3 |
4 | import spotipy
5 | import os
6 | from spotipy.oauth2 import SpotifyOAuth
7 | from secrets import SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, username
8 | import ip
9 |
10 | print(ip.ip)
11 |
12 | scope = 'user-read-private user-read-playback-state user-modify-playback-state'
13 |
14 | os.environ["SPOTIPY_CLIENT_ID"] = SPOTIPY_CLIENT_ID
15 | os.environ["SPOTIPY_CLIENT_SECRET"] = SPOTIPY_CLIENT_SECRET
16 |
17 | sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIPY_CLIENT_ID,
18 | client_secret=SPOTIPY_CLIENT_SECRET,
19 | redirect_uri="http://"+str(ip.ip)+":3000/",
20 | scope=scope,
21 | username=username,
22 | show_dialog=True,
23 | cache_path=None))
24 |
25 | results = sp.currently_playing()
26 | print(results)
--------------------------------------------------------------------------------
/src/autobrightness.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def get_output_brightness(user_brightness, sensor_value, max_brightness, min_brightness):
4 | if sensor_value < 0:
5 | sensor_value = 0
6 |
7 | interpreted = sensor_value * 3
8 |
9 |
10 |
11 | # multiply interpreted by linear user_brightness value from 0 to 2
12 | output_brightness = ((user_brightness / 50) * interpreted)
13 |
14 |
15 | # this is some version of point slope form
16 | #output_brightness = output_brightness * (max_brightness - min_brightness) + min_brightness
17 |
18 | return output_brightness
19 |
--------------------------------------------------------------------------------
/src/clock.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | import PIL.Image
3 | import numpy as np
4 | import settings
5 |
6 | to_display = '0000'
7 |
8 | black_replacement = [0,0,0,255]
9 | gray_replacement = [0,0,0,255]
10 |
11 |
12 | def get_image_ref(style, digit):
13 | return 'assets/clock/'+style+'-'+str(digit)+'.png'
14 |
15 | def get_image(src):
16 | img = PIL.Image.open(src)
17 | # img.show()
18 | return img
19 |
20 | all_images = []
21 |
22 | def set_digit_images():
23 | global all_images
24 | all_images = []
25 | for i in range(10):
26 | clock_style = settings.get()["clock"]
27 | if not (clock_style == "modern"):
28 | clock_style = "classic"
29 | ref = get_image_ref(clock_style, i)
30 | all_images.append(get_image(ref))
31 |
32 | def combine_horizontally(n1, n2):
33 | n1 = int(n1)
34 | n2 = int(n2)
35 | first_num_pixels = np.array(all_images[n1]).tolist()
36 | second_num_pixels = np.array(all_images[n2]).tolist()
37 |
38 | new_image_pixels = []
39 |
40 | for y in range(len(first_num_pixels)):
41 | row = first_num_pixels[y]
42 | while len(row) < 8:
43 | row.append([1,0,0,255])
44 |
45 | for x in range(8):
46 | row2 = second_num_pixels[y]
47 | while len(row2) < 8:
48 | row2.insert(0, [1,0,0,255])
49 | row.append(row2[x])
50 |
51 | new_image_pixels.append(np.uint8(row))
52 |
53 | return new_image_pixels
54 |
55 | def combine_vertically(top, bottom):
56 | all_px = top
57 | colors_to_replace = [
58 | ([0, 0, 0, 255], black_replacement), # replace black with...
59 | ([136, 136, 136, 255], gray_replacement) # replace gray with...
60 | ]
61 | # print(colors_to_replace)
62 | while len(top) < 8:
63 | newrow = [[1,0,0,255]] * 16
64 | newrow = np.uint8(newrow)
65 | top.append(newrow)
66 |
67 | while len(bottom) < 8:
68 | newrow = [[1,0,0,255]] * 16
69 | newrow = np.uint8(newrow)
70 | bottom.insert(0, newrow)
71 |
72 | for y in range(len(bottom)):
73 | all_px.append(bottom[y])
74 | # print(all_px)
75 | for pair in colors_to_replace:
76 | for y in range(len(all_px)):
77 | for x in range(len(all_px[y])):
78 | if (all_px[y][x] == pair[0]).all():
79 | all_px[y][x] = pair[1]
80 |
81 | return all_px
82 |
83 | def now():
84 | set_digit_images()
85 | global to_display
86 | global black_replacement
87 | black_replacement = settings.check("clockColor").split(",")
88 | black_replacement.append(255)
89 | # print(settings.check("clockColor").split(','))
90 |
91 | use_24_hour_clock = settings.check("clockTiming") == "24"
92 | to_display = datetime.now().strftime("%I%M")
93 |
94 | if use_24_hour_clock:
95 | to_display = datetime.now().strftime("%H%M")
96 |
97 | to_display = str(to_display)
98 | if len(to_display) != 4:
99 | to_display = '0000'
100 |
101 | top = combine_horizontally(to_display[0], to_display[1])
102 | bottom = combine_horizontally(to_display[2], to_display[3])
103 |
104 | combined = combine_vertically(top, bottom)
105 | im = PIL.Image.fromarray(np.array(combined))
106 |
107 | return im
108 |
109 | now()
110 |
--------------------------------------------------------------------------------
/src/driver.py:
--------------------------------------------------------------------------------
1 | # drives the program, finds what to put on the screen
2 |
3 | import spotipy
4 | import spotipy.util as util
5 | from secrets import SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, username
6 | import exceptions
7 | import os
8 | import json
9 | import time
10 | import settings
11 | import listen
12 | from datetime import datetime
13 | import random
14 |
15 | os.environ["SPOTIPY_CLIENT_ID"] = SPOTIPY_CLIENT_ID
16 | os.environ["SPOTIPY_CLIENT_SECRET"] = SPOTIPY_CLIENT_SECRET
17 |
18 | loginUsername = username
19 | # what the program is allowed to modify
20 | scope = 'user-read-private user-read-playback-state user-modify-playback-state'
21 |
22 | token = util.prompt_for_user_token(loginUsername, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri="http://localhost:3000/")
23 |
24 | sp = spotipy.Spotify(auth=token)
25 |
26 | pause_time = 0
27 | screen_off = False
28 | shutoff_time = 60 # seconds
29 |
30 | show_clock = True
31 |
32 | def song():
33 | # print("song called")
34 | global pause_time
35 | global screen_off
36 | global sp
37 |
38 | current_settings = settings.get()
39 | if current_settings["asleep"] == "true" or current_settings["asleep"] == True:
40 | settings.put("albumName", "Frame is Asleep")
41 | settings.put("imageUrl", "https://i.ibb.co/2d9xQNk/Group-31.png")
42 | return exceptions.exc_object('off', 'screen off')
43 |
44 | if current_settings["mode"] == "listen":
45 | if current_settings["listenTrigger"] == True or current_settings["listenTrigger"] == "true":
46 | settings.setTrigger("listenTrigger")
47 | return listen.recognize()
48 | else:
49 | return listen.last()
50 | # return exceptions.exc_object('off', 'screen off')
51 | listen.reset_last_successful_song()
52 |
53 | try:
54 | playing = sp.currently_playing()
55 | except spotipy.client.SpotifyException:
56 | # re-authenticate when token expires
57 | token = util.prompt_for_user_token(loginUsername, scope, client_id=SPOTIPY_CLIENT_ID, client_secret=SPOTIPY_CLIENT_SECRET, redirect_uri="http://localhost:3000/")
58 | print("New Spotify Token")
59 | sp = spotipy.Spotify(auth=token)
60 | try:
61 | playing = sp.currently_playing()
62 | except:
63 | return exceptions.exc_object('error', 'spotify api error')
64 |
65 | idle_setting = settings.check("idleMode") # can be clock, gif:[gif_id], off, false (off means the same thing as false)
66 |
67 | if idle_setting == "off":
68 | idle_setting = "false"
69 |
70 | if (playing == None) or (not (playing.get('is_playing'))):
71 | if idle_setting == "false":
72 | # no clock, no gif
73 | if pause_time == 0:
74 | pause_time = time.time()
75 | if (time.time() - pause_time) > shutoff_time:
76 | if not screen_off:
77 | print('Shutting off...')
78 | screen_off = True
79 | return exceptions.exc_object('off', 'screen off')
80 | elif idle_setting == "clock":
81 | # a composite index, that way if anything changes the clock updates :)
82 | return exceptions.exc_object('time', datetime.now().strftime("%H%M")+settings.check("clock")+settings.check("clockColor")+settings.check("clockTiming"))
83 | elif idle_setting.startswith("gif"):
84 | try:
85 | gif_id = idle_setting.split(':')[1] # format is gif:[gif_id]
86 | return exceptions.exc_object('gif', gif_id)
87 | except Exception as e:
88 | print(e)
89 | return exceptions.exc_object('error', "error with gif: "+idle_setting)
90 |
91 | return exceptions.exc_object('paused', json.dumps(playing))
92 | else:
93 | screen_off = False
94 | pause_time = 0
95 |
96 | try:
97 | images_returned = playing.get("item").get("album").get("images")
98 | image_url = (images_returned[len(images_returned) - 1].get('url'))
99 | except:
100 | return exceptions.exc_object('error', json.dumps(playing))
101 |
102 | artists = playing.get("item").get("album").get('artists')
103 | name = playing.get("item").get('name')
104 | artist_names = ""
105 |
106 | for i in range(len(artists)):
107 | artist_names += artists[i].get('name')
108 | if not (i == len(artists) - 1):
109 | artist_names += ', '
110 |
111 | return {
112 | "image_url": image_url,
113 | "name": name,
114 | "artist_names": artist_names,
115 | "fullsize_image_url": images_returned[0].get('url'),
116 | "raw": "spotify",
117 | "ready": True,
118 | "playing": True,
119 | "force": False,
120 | "exception": False,
121 | "type": "song"
122 | }
123 |
--------------------------------------------------------------------------------
/src/exceptions.py:
--------------------------------------------------------------------------------
1 | PAUSED_IMAGE = 'assets/paused.png'
2 | ERROR_IMAGE = 'assets/error.png'
3 | OFF_IMAGE = 'assets/off.png'
4 | # TIME_IMAGE = 'assets/time.png'
5 |
6 | def exc_object(type, raw="reload for updates"):
7 | imgurl = PAUSED_IMAGE
8 | force_reload = False
9 |
10 | if type=='error':
11 | imgurl = ERROR_IMAGE
12 | elif type=='off':
13 | imgurl = OFF_IMAGE
14 | elif type=='paused':
15 | imgurl = PAUSED_IMAGE
16 | elif type.startswith('time'):
17 | # imgurl = TIME_IMAGE
18 | imgurl = "time//"+raw
19 | elif type.startswith('errorcode'):
20 | imgurl = 'assets/codes/'+type.split('_')[1] + '.png'
21 |
22 | return {
23 | "image_url": imgurl,
24 | "name": 'Not Playing',
25 | "fullsize_image_url": imgurl,
26 | "artist_names": '--',
27 | "raw": raw,
28 | "ready": False,
29 | "playing": False,
30 | "force": force_reload,
31 | "exception": True,
32 | "type": type
33 | }
34 |
--------------------------------------------------------------------------------
/src/fun.py:
--------------------------------------------------------------------------------
1 | # for when the Frame is idle
2 | import time
3 | from PIL import Image, ImageSequence
4 | import numpy as np
5 |
6 | frame_duration = 0
7 |
8 | # Display individual frames from the loaded animated GIF file
9 | def get_frames(gif_id):
10 | img = Image.open("./assets/gifs/"+gif_id+".gif")
11 | frames = np.array([np.array(frame.copy().convert('RGB').getdata(),dtype=np.uint8).reshape(frame.size[1],frame.size[0],3) for frame in ImageSequence.Iterator(img)])
12 |
13 | return frames
--------------------------------------------------------------------------------
/src/index.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import PIL.Image
3 | from io import BytesIO
4 | import numpy as np
5 | import time
6 | import driver
7 | import sys
8 | import exceptions
9 | import numbers
10 | import nonlinearity
11 | import settings
12 | import autobrightness
13 | import clock
14 | import nightshift
15 | import fun
16 |
17 | sys.path.append('/resize')
18 | from resize import resize
19 |
20 | def get_argument(index):
21 | try:
22 | a = sys.argv[index]
23 | return a
24 | except:
25 | return None
26 |
27 | max_brightness = 0.50
28 | min_brightness = 0.06
29 | brt = 0.05
30 | night_shift_value = 0
31 |
32 | def get_brightness():
33 | brightness_setting = int(settings.get()['brightness']) / 100
34 | l = 45
35 |
36 | if settings.check("autobrightness") == False or settings.check("autobrightness") == "false":
37 | return brightness_setting
38 |
39 | try:
40 | l = light.lux()
41 | if (l) > 30:
42 | l = 30
43 | elif l < 0:
44 | l = 0
45 | l = (l * 10/3) / 100
46 | except:
47 | # there can be an overload of brightness, in which an error is thrown
48 | if setLeds:
49 | print('Error getting sensor value. Used 45')
50 | output = (l+(brightness_setting))/2
51 |
52 | # print("sensor: "+str(l), "setting: "+str(brightness_setting), "output: "+str(output))
53 |
54 | # output = autobrightness.get_output_brightness(brightness_setting, l, max_brightness=max_brightness, min_brightness=min_brightness)
55 | return output
56 |
57 |
58 | def set_brightness(val):
59 | global brt
60 |
61 | brt = val
62 | if brt > max_brightness:
63 | brt = max_brightness
64 | elif brt < min_brightness:
65 | brt = min_brightness
66 | #print('Set brightness automatically to '+str(brt))
67 |
68 | if get_argument(1) != None and get_argument(1) != "test" and get_argument(1) != 'auto':
69 | brt = int(get_argument(1)) / (max_brightness * 100)
70 |
71 | if get_argument(1) == 'auto':
72 | import light
73 | import math
74 | set_brightness(get_brightness())
75 |
76 | run_server = False
77 |
78 | img = None
79 |
80 | # if the LED strip is not on you, that is okay, make sure this is set to false; or, use the runtime variable "test"
81 | setLeds = True
82 |
83 | if get_argument(1) == 'test':
84 | setLeds = False
85 |
86 | if setLeds:
87 | import board
88 | import neopixel
89 | pixels = neopixel.NeoPixel(board.D12, 256, auto_write=False)
90 |
91 | def get_image(song):
92 | # print(song)
93 | try:
94 | imgurl = song.get('image_url')
95 | except:
96 | print('### error 1 ###')
97 | imgurl = exceptions.ERROR_IMAGE # error 1
98 |
99 | return imgurl
100 |
101 | # Finds the image based off of url/path
102 | def find_image(locator):
103 | global img
104 | imgsource = locator
105 | if locator.startswith('http'):
106 | # try:
107 | imgresp = requests.get(locator)
108 | imgsource = BytesIO(imgresp.content)
109 | # except:
110 | # imgresp = requests.get(locator)
111 | # imgsource = BytesIO(imgresp.content)
112 |
113 | img = PIL.Image.open(imgsource)
114 |
115 | return img
116 |
117 | # Gets the pixels given either the url or the exact image
118 | def get_pixels(imgurl=None, image=None):
119 | global img
120 |
121 | if (imgurl== None) and not (image==None): # if actual image object passed in
122 | img = image
123 | else:
124 | find_image(imgurl)
125 |
126 | return manipulate()
127 |
128 | # Reverses every second row, compensates for non-linearity, etc.
129 | def manipulate():
130 | global img
131 |
132 | contrast_setting = int(settings.get()['contrast']) / 100 + 0.5
133 | imgpx = resize.resize(img, contrast_setting)
134 |
135 | # only doing this for testing mode.
136 | img = PIL.Image.fromarray(imgpx)
137 |
138 | finalpx = []
139 |
140 | for ri in range(len(imgpx)):
141 | if ri % 2 == 1:
142 | imgpx[ri] = imgpx[ri][::-1] # flips every 2 rows
143 | for ci in range(len(imgpx[0])):
144 | try:
145 | # colored pixels
146 | r = imgpx[ri][ci][0]
147 | g = imgpx[ri][ci][1]
148 | b = imgpx[ri][ci][2]
149 | except:
150 | # only black and white pixels
151 | r = imgpx[ri][ci]
152 | g = imgpx[ri][ci]
153 | b = imgpx[ri][ci]
154 |
155 | # manipulation of all pixels
156 | r = int(brt * r)
157 | g = int(brt * g)
158 | b = int(brt * b)
159 |
160 | night_shift_setting = settings.check("nightshift")
161 | if (night_shift_setting == None):
162 | night_shift_setting = 0
163 |
164 | (r,g,b) = nightshift.adjust(r,g,b, 100-int(night_shift_setting))
165 |
166 | # adjust for bad colors on display
167 | if brt > 0.15:
168 | r = nonlinearity.compensate(r)
169 | g = nonlinearity.compensate(g)
170 | b = nonlinearity.compensate(b)
171 |
172 | finalpx.append((r, g, b))
173 |
174 | return finalpx
175 |
176 | # Update the pixels on the screen
177 | def update_pixels(finalpx, transition=True):
178 | if setLeds:
179 | if transition:
180 | animate(pixels[0:256], finalpx)
181 | else:
182 | pixels[0:256] = finalpx[0:256]
183 | pixels.show()
184 | else:
185 | img.show()
186 | return
187 | def configure_brightness():
188 | lastbrt = brt
189 |
190 | current = get_brightness()
191 | if abs(current - lastbrt) > 0.01:
192 | set_brightness(current)
193 |
194 | # Main function to be repeatedly run. Gets song, and brings everything together
195 | def main(last_image_url):
196 | global night_shift_value, img
197 | song = driver.song()
198 | imgurl = get_image(song)
199 |
200 | # set brightness automatically
201 | lastbrt = brt
202 | last_night_shift_value = night_shift_value
203 | night_shift_value = settings.check("nightshift")
204 |
205 | current = get_brightness()
206 |
207 | if abs(current - lastbrt) > 0.01:
208 | set_brightness(current)
209 |
210 | if song.get('type') == "time":
211 | time_image = clock.now()
212 | px = get_pixels(image=time_image)
213 | elif song.get('type') == "gif":
214 | current_item = song
215 | frame_number = 0
216 | while settings.check("idleMode").startswith("gif") and current_item.get('type') == 'gif':
217 | configure_brightness()
218 | gif_id = current_item.get('raw')
219 | frames = fun.get_frames(gif_id)
220 | for frame in frames:
221 | frame_image = PIL.Image.fromarray(frame)
222 | px = get_pixels(image=frame_image)
223 | update_pixels(px, transition=False if frame_number != 0 else True)
224 |
225 | time.sleep(fun.frame_duration)
226 | frame_number += 1
227 | current_item = driver.song()
228 | else:
229 | px = get_pixels(imgurl)
230 |
231 | if lastbrt != brt or last_night_shift_value != night_shift_value:
232 | print('brt updated to ' +str(brt))
233 | update_pixels(px)
234 | elif ((imgurl == last_image_url) or (imgurl == None)) and (song.get("force") == False):
235 | # note: this specifies if the image url is the same or not. Meaning, that if two songs are from the same album it won't do anything
236 | pass
237 | else:
238 | print(song.get('name'))
239 | display_image_url = song.get('fullsize_image_url')
240 | if not display_image_url.startswith("http"):
241 | display_image_url = "https://i.ibb.co/KNq0069/Group-30.png"
242 |
243 | settings.put("albumName", song.get('name'))
244 | settings.put("imageUrl", display_image_url)
245 | settings.put("artistName", song.get('artist_names'))
246 | # img.show()
247 | update_pixels(px)
248 |
249 | return song
250 |
251 | steps = 12
252 |
253 | # Animates a set of pixels
254 | def animate(oldpixels, newpixels):
255 | set_step_count()
256 |
257 | stepcount = 0
258 | while stepcount < steps:
259 | pix = []
260 | for l in range(len(oldpixels)):
261 | temppixel = [0,0,0]
262 | for j in range(3):
263 | temppixel[j] = int(calc_pixel(oldpixels[l][j], newpixels[l][j], stepcount, steps))
264 | pix.append(temppixel)
265 |
266 | for i in range(len(oldpixels)):
267 | pixels[i] = (pix[i][0], pix[i][1], pix[i][2])
268 | pixels.show()
269 | stepcount += 1
270 |
271 | pixels[0:256] = newpixels[0:256]
272 | pixels.show()
273 |
274 | # Sets number of frames on the animatoin
275 | def set_step_count():
276 | global steps
277 | steps = int(settings.get()['animation'])
278 |
279 | # Used for animation. Calculates the pixel color based on a linear function x1 + x((y2-y1) / dx)
280 | def calc_pixel(old, new, stepno, totalsteps):
281 | p = ((new - old)/totalsteps) * stepno + old
282 | if p > 255:
283 | p = 255
284 | if p < 0:
285 | p = 0
286 | return p
--------------------------------------------------------------------------------
/src/ip.py:
--------------------------------------------------------------------------------
1 | import socket
2 |
3 | def get_ip_address():
4 | ip_address = ''
5 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
6 | s.connect(("8.8.8.8",80))
7 | ip_address = s.getsockname()[0]
8 | s.close()
9 | return ip_address
10 |
11 | ip = get_ip_address()
--------------------------------------------------------------------------------
/src/ipdisplay.py:
--------------------------------------------------------------------------------
1 | import exceptions
2 | import ip
3 | import index
4 | import time
5 |
6 | lasturl = exceptions.exc_object('off')
7 |
8 | def job():
9 | iplist = list(ip.ip)
10 | for i in range(len(iplist)):
11 | show('errorcode_'+str(iplist[i]))
12 | time.sleep(1)
13 | show('off')
14 | time.sleep(0.5)
15 | show('error')
16 | time.sleep(2)
17 | show('off')
18 |
19 | def show(code):
20 | ref = exceptions.exc_object(str(code))
21 | px = index.manipulate(ref.get('image_url'))
22 | index.update_pixels(px)
23 |
24 | job()
--------------------------------------------------------------------------------
/src/light.py:
--------------------------------------------------------------------------------
1 | # Simple demo of the TSL2591 sensor. Will print the detected light value
2 | # every second.
3 | import time
4 |
5 | import board
6 | import busio
7 | import adafruit_tsl2591
8 |
9 | # Initialize the I2C bus.
10 | i2c = busio.I2C(board.SCL, board.SDA)
11 |
12 | # Initialize the sensor.
13 | sensor = adafruit_tsl2591.TSL2591(i2c)
14 |
15 | def lux():
16 | return sensor.lux
--------------------------------------------------------------------------------
/src/listen.py:
--------------------------------------------------------------------------------
1 | import json
2 | import requests
3 | import base64
4 | import sounddevice as sd
5 | from scipy.io.wavfile import write
6 | from io import BytesIO
7 | from secrets import AUDD_API_KEY
8 | import exceptions
9 |
10 | duration = 6 # seconds
11 | fs = 44100
12 |
13 | # NOTE: This is a misnomer; I originally named it this, and will change soon.
14 | last_successful_song = exceptions.exc_object("off", "screen off")
15 | recorded_file_name = "output.mp3"
16 |
17 | def reset_last_successful_song():
18 | last_successful_song = exceptions.exc_object("off", "screen off")
19 |
20 | # records song and saves to file. easier to save then open, and it overall doesn't take too long.
21 | def record():
22 | print('Recording...')
23 | recorded = sd.rec(int(duration * fs), samplerate=fs, channels=1)
24 | sd.wait()
25 |
26 | write(recorded_file_name, fs, recorded)
27 |
28 | print('Done Recording')
29 |
30 | # recognize the current song playing. also records
31 | def recognize():
32 | global last_successful_song
33 | record()
34 | sound_file = open('./'+recorded_file_name,"rb")
35 | sound_data_binary = sound_file.read()
36 | sound_data = (base64.b64encode(sound_data_binary))
37 |
38 | data = {
39 | 'return': 'spotify',
40 | 'api_token': AUDD_API_KEY,
41 | 'audio': sound_data
42 | }
43 |
44 | result = requests.post('https://api.audd.io/', data=data)
45 |
46 | response = json.loads(result.text)
47 | # print(response)
48 | name = 'null'
49 | artist = 'null'
50 | try:
51 | name = response['result']['title']
52 | artist = response['result']['artist']
53 | imgurl = response['result']['spotify']['album']['images'][0]['url']
54 | except:
55 | # print(response)
56 | last_successful_song = exceptions.exc_object('off', 'screen off')
57 | return exceptions.exc_object('off', 'screen off')
58 |
59 | full_object = {
60 | "image_url": imgurl,
61 | "name": name,
62 | "artist_names": artist,
63 | "fullsize_image_url": imgurl,
64 | "raw": "listening",
65 | # "raw": json.dumps(response),
66 | "ready": True,
67 | "playing": True,
68 | "force": False,
69 | "exception": False,
70 | "type": "song"
71 | }
72 | last_successful_song = full_object
73 | return full_object
74 |
75 | def last():
76 | return last_successful_song
--------------------------------------------------------------------------------
/src/nightshift.py:
--------------------------------------------------------------------------------
1 | def adjust(old_r, old_g, old_b, shift_k):
2 | shifted_r = old_r
3 | shifted_g = old_g
4 | shifted_b = old_b * shift_k / 100
5 |
6 | return (shifted_r, shifted_g, shifted_b)
--------------------------------------------------------------------------------
/src/nonlinearity.py:
--------------------------------------------------------------------------------
1 | max_pixel_brightness = 255
2 | brightness_gamma = 1.5
3 |
4 | def compensate(original):
5 | # print(original)
6 | original = int(original)
7 | if original == 0:
8 | return 0
9 | return int((original ** brightness_gamma) * (max_pixel_brightness ** (1 - brightness_gamma)))
10 |
--------------------------------------------------------------------------------
/src/publiship.py:
--------------------------------------------------------------------------------
1 | import ip
2 | import requests
3 | from secrets import FRAME_ID
4 |
5 | stored_ip_address = ''
6 |
7 | def send_ip_to_server():
8 | global stored_ip_address
9 | #the ip is used in the app
10 | latest_ip_address = ip.get_ip_address()
11 | if not (latest_ip_address == stored_ip_address):
12 | ip_address_url = "http://"+latest_ip_address+":3000/"
13 |
14 | # the code for this is not open source. It basically just stores the global and local ip
15 | # r = requests.get("https://patrick.today/frame/set", params={'ip': ip_address_url, 'frameId': FRAME_ID})
16 | # print(r.url)
17 |
18 | # if r.status_code == 200:
19 | # # successful update
20 | # print("global ip updated")
21 | # pass
22 | # else:
23 | # print(r)
24 | # print("there was an error updating the global ip")
25 |
26 | stored_ip_address = latest_ip_address
27 |
28 | send_ip_to_server()
29 |
--------------------------------------------------------------------------------
/src/requirements.txt:
--------------------------------------------------------------------------------
1 | absl-py==0.9.0
2 | Adafruit-Blinka==5.2.4
3 | adafruit-circuitpython-busdevice==5.0.1
4 | Adafruit-PlatformDetect==2.14.3
5 | Adafruit-PureIO==1.1.5
6 | altair==4.1.0
7 | appnope==0.1.0
8 | argon2-cffi==20.1.0
9 | astor==0.8.1
10 | astunparse==1.6.3
11 | attrs==19.3.0
12 | backcall==0.2.0
13 | base58==2.0.1
14 | bleach==3.1.5
15 | blinker==1.4
16 | boto3==1.14.33
17 | botocore==1.17.33
18 | cachetools==4.1.1
19 | certifi==2020.4.5.1
20 | cffi==1.14.0
21 | chardet==3.0.4
22 | click==7.1.2
23 | cycler==0.10.0
24 | decorator==4.4.2
25 | defusedxml==0.6.0
26 | docutils==0.15.2
27 | entrypoints==0.3
28 | enum-compat==0.0.3
29 | ffprobe==0.5
30 | gast==0.3.3
31 | google-auth==1.20.0
32 | google-auth-oauthlib==0.4.1
33 | google-pasta==0.2.0
34 | grpcio==1.30.0
35 | h5py==2.10.0
36 | idna==2.9
37 | importlib-metadata==1.7.0
38 | ipykernel==5.3.4
39 | ipython==7.17.0
40 | ipython-genutils==0.2.0
41 | ipywidgets==7.5.1
42 | jedi==0.17.2
43 | Jinja2==2.11.2
44 | jmespath==0.10.0
45 | jsonschema==3.2.0
46 | jupyter-client==6.1.6
47 | jupyter-core==4.6.3
48 | Keras-Preprocessing==1.1.2
49 | kiwisolver==1.2.0
50 | Markdown==3.2.2
51 | MarkupSafe==1.1.1
52 | matplotlib==3.3.0
53 | mistune==0.8.4
54 | nbconvert==5.6.1
55 | nbformat==5.0.7
56 | notebook==6.1.0
57 | numpy==1.18.5
58 | oauthlib==3.1.0
59 | opt-einsum==3.3.0
60 | packaging==20.4
61 | pandas==1.1.0
62 | pandocfilters==1.4.2
63 | parso==0.7.1
64 | pathtools==0.1.2
65 | pexpect==4.8.0
66 | pickleshare==0.7.5
67 | Pillow==7.2.0
68 | prometheus-client==0.8.0
69 | prompt-toolkit==3.0.5
70 | protobuf==3.12.4
71 | psutil==5.7.2
72 | ptyprocess==0.6.0
73 | pyarrow==1.0.0
74 | pyasn1==0.4.8
75 | pyasn1-modules==0.2.8
76 | pycparser==2.20
77 | pydeck==0.4.0
78 | pydub==0.24.1
79 | pyftdi==0.51.2
80 | Pygments==2.6.1
81 | pyparsing==2.4.7
82 | pyrsistent==0.16.0
83 | pyserial==3.4
84 | python-dateutil==2.8.1
85 | pytz==2020.1
86 | pyusb==1.0.2
87 | pyzmq==19.0.2
88 | requests==2.23.0
89 | requests-oauthlib==1.3.0
90 | rsa==4.6
91 | s3transfer==0.3.3
92 | schedule==0.6.0
93 | scipy==1.4.1
94 | Send2Trash==1.5.0
95 | six==1.15.0
96 | sounddevice==0.4.0
97 | sysv-ipc==1.0.1
98 | tensorboard==2.3.0
99 | tensorboard-plugin-wit==1.7.0
100 | tensorflow==2.3.0
101 | tensorflow-estimator==2.3.0
102 | termcolor==1.1.0
103 | terminado==0.8.3
104 | testpath==0.4.4
105 | toml==0.10.1
106 | toolz==0.10.0
107 | tornado==6.0.4
108 | traitlets==4.3.3
109 | tzlocal==2.1
110 | urllib3==1.25.9
111 | validators==0.17.0
112 | watchdog==0.10.3
113 | wcwidth==0.2.5
114 | webencodings==0.5.1
115 | Werkzeug==1.0.1
116 | widgetsnbextension==3.5.1
117 | wrapt==1.12.1
118 | zipp==3.1.0
119 |
--------------------------------------------------------------------------------
/src/run.py:
--------------------------------------------------------------------------------
1 | # This script uses a running while loop to run index.py every so often
2 | # Totally honestly, I am not super proud of how this is done, but it must be done.
3 |
4 | import time
5 | import index
6 | import schedule
7 | import threading
8 | from http.server import BaseHTTPRequestHandler,HTTPServer
9 | import exceptions
10 | import publiship
11 |
12 | # initializes the last song so that way there is no error
13 | last_song = exceptions.exc_object('off')
14 | num_runs = 0
15 |
16 | def job():
17 | global last_song
18 | global num_runs
19 | # print('job called')
20 | num_runs += 1
21 | last_song = index.main(last_song.get('image_url'))
22 |
23 | def send_ip_to_server():
24 | publiship.send_ip_to_server()
25 |
26 | refresh_interval = 0.5 # seconds per refresh
27 | schedule.every(refresh_interval).seconds.do(job)
28 |
29 | schedule.every(1).minutes.do(send_ip_to_server)
30 |
31 | def music():
32 | while 1:
33 | schedule.run_pending()
34 |
35 | if __name__=='__main__':
36 | musicThread = threading.Thread(target=music)
37 | musicThread.start()
--------------------------------------------------------------------------------
/src/secrets.example.py:
--------------------------------------------------------------------------------
1 | # remove the .example with your own
2 |
3 | SPOTIPY_CLIENT_ID = 'your-spotify-client-id'
4 | SPOTIPY_CLIENT_SECRET = 'your-spotify-client-secret'
5 |
6 | # want to see what patrick has been listening to?
7 | # set username to 'jdiaalhsw8zdhpcdv391bj5we'
8 |
9 | username = 'your-username'
10 |
11 | FRAME_ID = 'your-frame-id'
--------------------------------------------------------------------------------
/src/settings.py:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 |
4 | # cur_path = os.path.dirname(__file__)
5 | # new_path = os.path.relpath('./')
6 | parsed = ''
7 | def get():
8 | global parsed
9 | f = open("./mobile/server/settings.json", "r")
10 | content = f.read()
11 | # print(content)
12 | try:
13 | parsed = json.loads(content)
14 | except:
15 | pass
16 |
17 | # print(parsed["brightness"])
18 | f.close()
19 | return parsed
20 |
21 | def put(name, val):
22 | f = open("./mobile/server/settings.json", "w")
23 | parsed[name] = val
24 | json.dump(parsed, f, indent=4)
25 | f.close()
26 |
27 | def check(name):
28 | get()
29 | try:
30 | return parsed[name]
31 | except:
32 | return
33 |
34 | def setTrigger(name):
35 | global parsed
36 | get()
37 | f = open("./mobile/server/settings.json", "w")
38 | parsed[name] = not(parsed[name])
39 | json.dump(parsed, f, indent=4)
40 | f.close()
41 | return
--------------------------------------------------------------------------------
/src/spotipy/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/phultquist/frame/58af7ba45ad41929d199d7819a611a4321c33862/src/spotipy/.DS_Store
--------------------------------------------------------------------------------
/src/spotipy/README.md:
--------------------------------------------------------------------------------
1 | # spotipy
--------------------------------------------------------------------------------
/src/spotipy/__init__.py:
--------------------------------------------------------------------------------
1 | from .client import * # noqa
2 | from .oauth2 import * # noqa
3 | from .util import * # noqa
4 | from .exceptions import * # noqa
5 |
--------------------------------------------------------------------------------
/src/spotipy/exceptions.py:
--------------------------------------------------------------------------------
1 | class SpotifyException(Exception):
2 |
3 | def __init__(self, http_status, code, msg, reason=None, headers=None):
4 | self.http_status = http_status
5 | self.code = code
6 | self.msg = msg
7 | self.reason = reason
8 | # `headers` is used to support `Retry-After` in the event of a
9 | # 429 status code.
10 | if headers is None:
11 | headers = {}
12 | self.headers = headers
13 |
14 | def __str__(self):
15 | return 'http status: {0}, code:{1} - {2}, reason: {3}'.format(
16 | self.http_status, self.code, self.msg, self.reason)
17 |
--------------------------------------------------------------------------------
/src/spotipy/oauth2.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | __all__ = [
4 | "is_token_expired",
5 | "SpotifyClientCredentials",
6 | "SpotifyOAuth",
7 | "SpotifyOauthError",
8 | "SpotifyStateError",
9 | "SpotifyImplicitGrant",
10 | "SpotifyPKCE"
11 | ]
12 |
13 | import base64
14 | import json
15 | import logging
16 | import os
17 | import time
18 | import warnings
19 | import webbrowser
20 |
21 | import requests
22 | from spotipy.util import CLIENT_CREDS_ENV_VARS, get_host_port
23 | from spotipy.exceptions import SpotifyException
24 |
25 | # Workaround to support both python 2 & 3
26 | import six
27 | import six.moves.urllib.parse as urllibparse
28 | from six.moves.BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
29 | from six.moves.urllib_parse import urlparse, parse_qsl
30 |
31 | logger = logging.getLogger(__name__)
32 |
33 |
34 | class SpotifyOauthError(Exception):
35 | """ Error during Auth Code or Implicit Grant flow """
36 |
37 | def __init__(self, message, error=None, error_description=None, *args, **kwargs):
38 | self.error = error
39 | self.error_description = error_description
40 | self.__dict__.update(kwargs)
41 | super(SpotifyOauthError, self).__init__(message, *args, **kwargs)
42 |
43 |
44 | class SpotifyStateError(SpotifyOauthError):
45 | """ The state sent and state recieved were different """
46 |
47 | def __init__(self, local_state=None, remote_state=None, message=None,
48 | error=None, error_description=None, *args, **kwargs):
49 | if not message:
50 | message = ("Expected " + local_state + " but recieved "
51 | + remote_state)
52 | super(SpotifyOauthError, self).__init__(message, error,
53 | error_description, *args,
54 | **kwargs)
55 |
56 |
57 | def _make_authorization_headers(client_id, client_secret):
58 | auth_header = base64.b64encode(
59 | six.text_type(client_id + ":" + client_secret).encode("ascii")
60 | )
61 | return {"Authorization": "Basic %s" % auth_header.decode("ascii")}
62 |
63 |
64 | def is_token_expired(token_info):
65 | now = int(time.time())
66 | return token_info["expires_at"] - now < 60
67 |
68 |
69 | def _ensure_value(value, env_key):
70 | env_val = CLIENT_CREDS_ENV_VARS[env_key]
71 | _val = value or os.getenv(env_val)
72 | if _val is None:
73 | msg = "No %s. Pass it or set a %s environment variable." % (
74 | env_key,
75 | env_val,
76 | )
77 | raise SpotifyOauthError(msg)
78 | return _val
79 |
80 |
81 | def _get_cache_path(cache_path, username):
82 | if cache_path:
83 | return cache_path
84 |
85 | cache_path = ".cache"
86 | if username:
87 | cache_path += "-" + str(username)
88 |
89 | return cache_path
90 |
91 |
92 | class SpotifyAuthBase(object):
93 | def __init__(self, requests_session):
94 | if isinstance(requests_session, requests.Session):
95 | self._session = requests_session
96 | else:
97 | if requests_session: # Build a new session.
98 | self._session = requests.Session()
99 | else: # Use the Requests API module as a "session".
100 | from requests import api
101 | self._session = api
102 |
103 | @property
104 | def client_id(self):
105 | return self._client_id
106 |
107 | @client_id.setter
108 | def client_id(self, val):
109 | self._client_id = _ensure_value(val, "client_id")
110 |
111 | @property
112 | def client_secret(self):
113 | return self._client_secret
114 |
115 | @client_secret.setter
116 | def client_secret(self, val):
117 | self._client_secret = _ensure_value(val, "client_secret")
118 |
119 | @property
120 | def redirect_uri(self):
121 | return self._redirect_uri
122 |
123 | @redirect_uri.setter
124 | def redirect_uri(self, val):
125 | self._redirect_uri = _ensure_value(val, "redirect_uri")
126 |
127 | @staticmethod
128 | def _get_user_input(prompt):
129 | try:
130 | return raw_input(prompt)
131 | except NameError:
132 | return input(prompt)
133 |
134 | def __del__(self):
135 | """Make sure the connection (pool) gets closed"""
136 | if isinstance(self._session, requests.Session):
137 | self._session.close()
138 |
139 |
140 | class SpotifyClientCredentials(SpotifyAuthBase):
141 | OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
142 |
143 | def __init__(self,
144 | client_id=None,
145 | client_secret=None,
146 | proxies=None,
147 | requests_session=True,
148 | requests_timeout=None):
149 | """
150 | You can either provide a client_id and client_secret to the
151 | constructor or set SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET
152 | environment variables
153 | """
154 |
155 | super(SpotifyClientCredentials, self).__init__(requests_session)
156 |
157 | self.client_id = client_id
158 | self.client_secret = client_secret
159 | self.token_info = None
160 | self.proxies = proxies
161 | self.requests_timeout = requests_timeout
162 |
163 | def get_access_token(self, as_dict=True):
164 | """
165 | If a valid access token is in memory, returns it
166 | Else feches a new token and returns it
167 |
168 | Parameters:
169 | - as_dict - a boolean indicating if returning the access token
170 | as a token_info dictionary, otherwise it will be returned
171 | as a string.
172 | """
173 | if as_dict:
174 | warnings.warn(
175 | "You're using 'as_dict = True'."
176 | "get_access_token will return the token string directly in future "
177 | "versions. Please adjust your code accordingly, or use "
178 | "get_cached_token instead.",
179 | DeprecationWarning,
180 | stacklevel=2,
181 | )
182 |
183 | if self.token_info and not self.is_token_expired(self.token_info):
184 | return self.token_info if as_dict else self.token_info["access_token"]
185 |
186 | token_info = self._request_access_token()
187 | token_info = self._add_custom_values_to_token_info(token_info)
188 | self.token_info = token_info
189 | return self.token_info["access_token"]
190 |
191 | def _request_access_token(self):
192 | """Gets client credentials access token """
193 | payload = {"grant_type": "client_credentials"}
194 |
195 | headers = _make_authorization_headers(
196 | self.client_id, self.client_secret
197 | )
198 |
199 | response = self._session.post(
200 | self.OAUTH_TOKEN_URL,
201 | data=payload,
202 | headers=headers,
203 | verify=True,
204 | proxies=self.proxies,
205 | timeout=self.requests_timeout,
206 | )
207 | if response.status_code != 200:
208 | error_payload = response.json()
209 | raise SpotifyOauthError(
210 | 'error: {0}, error_description: {1}'.format(
211 | error_payload['error'], error_payload['error_description']),
212 | error=error_payload['error'],
213 | error_description=error_payload['error_description'])
214 | token_info = response.json()
215 | return token_info
216 |
217 | def is_token_expired(self, token_info):
218 | return is_token_expired(token_info)
219 |
220 | def _add_custom_values_to_token_info(self, token_info):
221 | """
222 | Store some values that aren't directly provided by a Web API
223 | response.
224 | """
225 | token_info["expires_at"] = int(time.time()) + token_info["expires_in"]
226 | return token_info
227 |
228 |
229 | class SpotifyOAuth(SpotifyAuthBase):
230 | """
231 | Implements Authorization Code Flow for Spotify's OAuth implementation.
232 | """
233 | OAUTH_AUTHORIZE_URL = "https://accounts.spotify.com/authorize"
234 | OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
235 |
236 | def __init__(
237 | self,
238 | client_id=None,
239 | client_secret=None,
240 | redirect_uri=None,
241 | state=None,
242 | scope=None,
243 | cache_path=None,
244 | username=None,
245 | proxies=None,
246 | show_dialog=False,
247 | requests_session=True,
248 | requests_timeout=None
249 | ):
250 | """
251 | Creates a SpotifyOAuth object
252 |
253 | Parameters:
254 | * client_id: Must be supplied or set as environment variable
255 | * client_secret: Must be supplied or set as environment variable
256 | * redirect_uri: Must be supplied or set as environment variable
257 | * state: May be supplied, no verification is performed
258 | * scope: May be supplied, intuitively converted to proper format
259 | * cache_path: May be supplied, will otherwise be generated
260 | (takes precedence over `username`)
261 | * username: May be supplied or set as environment variable
262 | (will set `cache_path` to `.cache-{username}`)
263 | * proxies: Proxy for the requests library to route through
264 | * show_dialog: Interpreted as boolean
265 | * requests_timeout: Tell Requests to stop waiting for a response after a given number
266 | of seconds
267 | """
268 |
269 | super(SpotifyOAuth, self).__init__(requests_session)
270 |
271 | self.client_id = client_id
272 | self.client_secret = client_secret
273 | self.redirect_uri = redirect_uri
274 | self.state = state
275 | self.username = username or os.getenv(
276 | CLIENT_CREDS_ENV_VARS["client_username"]
277 | )
278 | self.cache_path = _get_cache_path(cache_path, self.username)
279 | self.scope = self._normalize_scope(scope)
280 | self.proxies = proxies
281 | self.requests_timeout = requests_timeout
282 | self.show_dialog = show_dialog
283 |
284 | def get_cached_token(self):
285 | """ Gets a cached auth token
286 | """
287 | token_info = None
288 |
289 | try:
290 | f = open(self.cache_path)
291 | token_info_string = f.read()
292 | f.close()
293 | token_info = json.loads(token_info_string)
294 |
295 | # if scopes don't match, then bail
296 | if "scope" not in token_info or not self._is_scope_subset(
297 | self.scope, token_info["scope"]
298 | ):
299 | return None
300 |
301 | if self.is_token_expired(token_info):
302 | token_info = self.refresh_access_token(
303 | token_info["refresh_token"]
304 | )
305 |
306 | except IOError:
307 | logger.warning("Couldn't read cache at: %s", self.cache_path)
308 |
309 | return token_info
310 |
311 | def _save_token_info(self, token_info):
312 | if self.cache_path:
313 | try:
314 | f = open(self.cache_path, "w")
315 | f.write(json.dumps(token_info))
316 | f.close()
317 | except IOError:
318 | logger.warning('Couldn\'t write token to cache at: %s',
319 | self.cache_path)
320 |
321 | def _is_scope_subset(self, needle_scope, haystack_scope):
322 | needle_scope = set(needle_scope.split()) if needle_scope else set()
323 | haystack_scope = (
324 | set(haystack_scope.split()) if haystack_scope else set()
325 | )
326 | return needle_scope <= haystack_scope
327 |
328 | def is_token_expired(self, token_info):
329 | return is_token_expired(token_info)
330 |
331 | def get_authorize_url(self, state=None):
332 | """ Gets the URL to use to authorize this app
333 | """
334 | payload = {
335 | "client_id": self.client_id,
336 | "response_type": "code",
337 | "redirect_uri": self.redirect_uri,
338 | }
339 | if self.scope:
340 | payload["scope"] = self.scope
341 | if state is None:
342 | state = self.state
343 | if state is not None:
344 | payload["state"] = state
345 | if self.show_dialog:
346 | payload["show_dialog"] = True
347 |
348 | urlparams = urllibparse.urlencode(payload)
349 |
350 | print("%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams))
351 | return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
352 |
353 | def parse_response_code(self, url):
354 | """ Parse the response code in the given response url
355 |
356 | Parameters:
357 | - url - the response url
358 | """
359 | _, code = self.parse_auth_response_url(url)
360 | if code is None:
361 | return url
362 | else:
363 | return code
364 |
365 | @staticmethod
366 | def parse_auth_response_url(url):
367 | query_s = urlparse(url).query
368 | form = dict(parse_qsl(query_s))
369 | if "error" in form:
370 | raise SpotifyOauthError("Received error from auth server: "
371 | "{}".format(form["error"]),
372 | error=form["error"])
373 | return tuple(form.get(param) for param in ["state", "code"])
374 |
375 | def _make_authorization_headers(self):
376 | return _make_authorization_headers(self.client_id, self.client_secret)
377 |
378 | def _open_auth_url(self):
379 | auth_url = self.get_authorize_url()
380 | try:
381 | webbrowser.open(auth_url)
382 | logger.info("Opened %s in your browser", auth_url)
383 | except webbrowser.Error:
384 | logger.error("Please navigate here: %s", auth_url)
385 |
386 | def _get_auth_response_interactive(self, open_browser=True):
387 | if open_browser:
388 | self._open_auth_url()
389 | prompt = "Enter the URL you were redirected to: "
390 | else:
391 | url = self.get_authorize_url()
392 | prompt = (
393 | "Go to the following URL: {}\n"
394 | "Enter the URL you were redirected to: ".format(url)
395 | )
396 | response = self._get_user_input(prompt)
397 | state, code = SpotifyOAuth.parse_auth_response_url(response)
398 | if self.state is not None and self.state != state:
399 | raise SpotifyStateError(self.state, state)
400 | return code
401 |
402 | def _get_auth_response_local_server(self, redirect_port):
403 | server = start_local_http_server(redirect_port)
404 | self._open_auth_url()
405 | server.handle_request()
406 |
407 | if self.state is not None and server.state != self.state:
408 | raise SpotifyStateError(self.state, server.state)
409 |
410 | if server.auth_code is not None:
411 | return server.auth_code
412 | elif server.error is not None:
413 | raise SpotifyOauthError("Received error from OAuth server: {}".format(server.error))
414 | else:
415 | raise SpotifyOauthError("Server listening on localhost has not been accessed")
416 |
417 | def get_auth_response(self, open_browser=True):
418 | logger.info('User authentication requires interaction with your '
419 | 'web browser. Once you enter your credentials and '
420 | 'give authorization, you will be redirected to '
421 | 'a url. Paste that url you were directed to to '
422 | 'complete the authorization.')
423 |
424 | redirect_info = urlparse(self.redirect_uri)
425 | redirect_host, redirect_port = get_host_port(redirect_info.netloc)
426 | print(redirect_host)
427 | if (
428 | open_browser
429 | and redirect_host in ("127.0.0.1", "localhost")
430 | and redirect_info.scheme == "http"
431 | ):
432 | # Only start a local http server if a port is specified
433 | if redirect_port:
434 | return self._get_auth_response_local_server(redirect_port)
435 | else:
436 | logger.warning('Using `%s` as redirect URI without a port. '
437 | 'Specify a port (e.g. `%s:8080`) to allow '
438 | 'automatic retrieval of authentication code '
439 | 'instead of having to copy and paste '
440 | 'the URL your browser is redirected to.',
441 | redirect_host, redirect_host)
442 |
443 | return self._get_auth_response_interactive(open_browser=open_browser)
444 |
445 | def get_authorization_code(self, response=None):
446 | if response:
447 | return self.parse_response_code(response)
448 | return self.get_auth_response()
449 |
450 | def get_access_token(self, code=None, as_dict=True, check_cache=True):
451 | """ Gets the access token for the app given the code
452 |
453 | Parameters:
454 | - code - the response code
455 | - as_dict - a boolean indicating if returning the access token
456 | as a token_info dictionary, otherwise it will be returned
457 | as a string.
458 | """
459 | if as_dict:
460 | warnings.warn(
461 | "You're using 'as_dict = True'."
462 | "get_access_token will return the token string directly in future "
463 | "versions. Please adjust your code accordingly, or use "
464 | "get_cached_token instead.",
465 | DeprecationWarning,
466 | stacklevel=2,
467 | )
468 | if check_cache:
469 | token_info = self.get_cached_token()
470 | if token_info is not None:
471 | if is_token_expired(token_info):
472 | token_info = self.refresh_access_token(
473 | token_info["refresh_token"]
474 | )
475 | return token_info if as_dict else token_info["access_token"]
476 |
477 | payload = {
478 | "redirect_uri": self.redirect_uri,
479 | "code": code or self.get_auth_response(),
480 | "grant_type": "authorization_code",
481 | }
482 | if self.scope:
483 | payload["scope"] = self.scope
484 | if self.state:
485 | payload["state"] = self.state
486 |
487 | headers = self._make_authorization_headers()
488 |
489 | response = self._session.post(
490 | self.OAUTH_TOKEN_URL,
491 | data=payload,
492 | headers=headers,
493 | verify=True,
494 | proxies=self.proxies,
495 | timeout=self.requests_timeout,
496 | )
497 | if response.status_code != 200:
498 | error_payload = response.json()
499 | raise SpotifyOauthError(
500 | 'error: {0}, error_description: {1}'.format(
501 | error_payload['error'], error_payload['error_description']),
502 | error=error_payload['error'],
503 | error_description=error_payload['error_description'])
504 | token_info = response.json()
505 | token_info = self._add_custom_values_to_token_info(token_info)
506 | self._save_token_info(token_info)
507 | return token_info if as_dict else token_info["access_token"]
508 |
509 | def _normalize_scope(self, scope):
510 | if scope:
511 | scopes = sorted(scope.split())
512 | return " ".join(scopes)
513 | else:
514 | return None
515 |
516 | def refresh_access_token(self, refresh_token):
517 | payload = {
518 | "refresh_token": refresh_token,
519 | "grant_type": "refresh_token",
520 | }
521 |
522 | headers = self._make_authorization_headers()
523 |
524 | response = self._session.post(
525 | self.OAUTH_TOKEN_URL,
526 | data=payload,
527 | headers=headers,
528 | proxies=self.proxies,
529 | timeout=self.requests_timeout,
530 | )
531 |
532 | try:
533 | response.raise_for_status()
534 | except BaseException:
535 | logger.error('Couldn\'t refresh token. Response Status Code: %s '
536 | 'Reason: %s', response.status_code, response.reason)
537 |
538 | message = "Couldn't refresh token: code:%d reason:%s" % (
539 | response.status_code,
540 | response.reason,
541 | )
542 | raise SpotifyException(response.status_code,
543 | -1,
544 | message,
545 | headers)
546 |
547 | token_info = response.json()
548 | token_info = self._add_custom_values_to_token_info(token_info)
549 | if "refresh_token" not in token_info:
550 | token_info["refresh_token"] = refresh_token
551 | self._save_token_info(token_info)
552 | return token_info
553 |
554 | def _add_custom_values_to_token_info(self, token_info):
555 | """
556 | Store some values that aren't directly provided by a Web API
557 | response.
558 | """
559 | token_info["expires_at"] = int(time.time()) + token_info["expires_in"]
560 | token_info["scope"] = self.scope
561 | return token_info
562 |
563 |
564 | class SpotifyPKCE(SpotifyAuthBase):
565 | """ Implements PKCE Authorization Flow for client apps
566 |
567 | This auth manager enables *user and non-user* endpoints with only
568 | a client secret, redirect uri, and username. When the app requests
569 | an an access token for the first time, the user is prompted to
570 | authorize the new client app. After authorizing the app, the client
571 | app is then given both access and refresh tokens. This is the
572 | preferred way of authorizing a mobile/desktop client.
573 |
574 | """
575 |
576 | OAUTH_AUTHORIZE_URL = "https://accounts.spotify.com/authorize"
577 | OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
578 |
579 | def __init__(self,
580 | client_id=None,
581 | redirect_uri=None,
582 | state=None,
583 | scope=None,
584 | cache_path=None,
585 | username=None,
586 | proxies=None,
587 | requests_timeout=None,
588 | requests_session=True,):
589 | """
590 | Creates Auth Manager with the PKCE Auth flow.
591 |
592 | Parameters:
593 | * client_id: Must be supplied or set as environment variable
594 | * client_secret: Must be supplied or set as environment variable
595 | * redirect_uri: Must be supplied or set as environment variable
596 | * state: May be supplied, no verification is performed
597 | * scope: May be supplied, intuitively converted to proper format
598 | * cache_path: May be supplied, will otherwise be generated
599 | (takes precedence over `username`)
600 | * username: May be supplied or set as environment variable
601 | (will set `cache_path` to `.cache-{username}`)
602 | * show_dialog: Interpreted as boolean
603 | * proxies: Proxy for the requests library to route through
604 | * requests_timeout: Tell Requests to stop waiting for a response after a given number
605 | of seconds
606 | """
607 |
608 | super(SpotifyPKCE, self).__init__(requests_session)
609 | self.client_id = client_id
610 | self.redirect_uri = redirect_uri
611 | self.state = state
612 | self.scope = self._normalize_scope(scope)
613 | self.username = username or os.getenv(
614 | CLIENT_CREDS_ENV_VARS["client_username"]
615 | )
616 | self.cache_path = _get_cache_path(cache_path, self.username)
617 | self.proxies = proxies
618 | self.requests_timeout = requests_timeout
619 |
620 | self._code_challenge_method = "S256" # Spotify requires SHA256
621 | self.code_verifier = None
622 | self.code_challenge = None
623 | self.authorization_code = None
624 |
625 | def _normalize_scope(self, scope):
626 | if scope:
627 | scopes = sorted(scope.split())
628 | return " ".join(scopes)
629 | else:
630 | return None
631 |
632 | def _get_code_verifier(self):
633 | """ Spotify PCKE code verifier - See step 1 of the reference guide below
634 | Reference:
635 | https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
636 | """
637 | # Range (33,96) is used to select between 44-128 base64 characters for the
638 | # next operation. The range looks weird because base64 is 6 bytes
639 | import random
640 | length = random.randint(33, 96)
641 |
642 | # The seeded length generates between a 44 and 128 base64 characters encoded string
643 | try:
644 | import secrets
645 | verifier = secrets.token_urlsafe(length)
646 | except ImportError: # For python 3.5 support
647 | import os
648 | import base64
649 | rand_bytes = os.urandom(length)
650 | verifier = base64.urlsafe_b64encode(rand_bytes).decode('utf-8').replace('=', '')
651 | return verifier
652 |
653 | def _get_code_challenge(self):
654 | """ Spotify PCKE code challenge - See step 1 of the reference guide below
655 | Reference:
656 | https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce
657 | """
658 | import hashlib
659 | import base64
660 | code_challenge_digest = hashlib.sha256(self.code_verifier.encode('utf-8')).digest()
661 | code_challenge = base64.urlsafe_b64encode(code_challenge_digest).decode('utf-8')
662 | return code_challenge.replace('=', '')
663 |
664 | def get_authorize_url(self, state=None):
665 | """ Gets the URL to use to authorize this app """
666 | if not self.code_challenge:
667 | self.get_pkce_handshake_parameters()
668 | payload = {
669 | "client_id": self.client_id,
670 | "response_type": "code",
671 | "redirect_uri": self.redirect_uri,
672 | "code_challenge_method": self._code_challenge_method,
673 | "code_challenge": self.code_challenge
674 | }
675 | if self.scope:
676 | payload["scope"] = self.scope
677 | if state is None:
678 | state = self.state
679 | if state is not None:
680 | payload["state"] = state
681 | urlparams = urllibparse.urlencode(payload)
682 | return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
683 |
684 | def _open_auth_url(self, state=None):
685 | auth_url = self.get_authorize_url(state)
686 | try:
687 | webbrowser.open(auth_url)
688 | logger.info("Opened %s in your browser", auth_url)
689 | except webbrowser.Error:
690 | logger.error("Please navigate here: %s", auth_url)
691 |
692 | def _get_auth_response(self, open_browser=True):
693 | logger.info('User authentication requires interaction with your '
694 | 'web browser. Once you enter your credentials and '
695 | 'give authorization, you will be redirected to '
696 | 'a url. Paste that url you were directed to to '
697 | 'complete the authorization.')
698 |
699 | redirect_info = urlparse(self.redirect_uri)
700 | redirect_host, redirect_port = get_host_port(redirect_info.netloc)
701 |
702 | if (
703 | open_browser
704 | and redirect_host in ("127.0.0.1", "localhost")
705 | and redirect_info.scheme == "http"
706 | ):
707 | # Only start a local http server if a port is specified
708 | if redirect_port:
709 | return self._get_auth_response_local_server(redirect_port)
710 | else:
711 | logger.warning('Using `%s` as redirect URI without a port. '
712 | 'Specify a port (e.g. `%s:8080`) to allow '
713 | 'automatic retrieval of authentication code '
714 | 'instead of having to copy and paste '
715 | 'the URL your browser is redirected to.',
716 | redirect_host, redirect_host)
717 | return self._get_auth_response_interactive(open_browser=open_browser)
718 |
719 | def _get_auth_response_local_server(self, redirect_port):
720 | server = start_local_http_server(redirect_port)
721 | self._open_auth_url()
722 | server.handle_request()
723 |
724 | if self.state is not None and server.state != self.state:
725 | raise SpotifyStateError(self.state, server.state)
726 |
727 | if server.auth_code is not None:
728 | return server.auth_code
729 | elif server.error is not None:
730 | raise SpotifyOauthError("Received error from OAuth server: {}".format(server.error))
731 | else:
732 | raise SpotifyOauthError("Server listening on localhost has not been accessed")
733 |
734 | def _get_auth_response_interactive(self, open_browser=True):
735 | if open_browser:
736 | self._open_auth_url()
737 | prompt = "Enter the URL you were redirected to: "
738 | else:
739 | url = self.get_authorize_url()
740 | prompt = (
741 | "Go to the following URL: {}\n"
742 | "Enter the URL you were redirected to: ".format(url)
743 | )
744 | response = self._get_user_input(prompt)
745 | state, code = self.parse_auth_response_url(response)
746 | if self.state is not None and self.state != state:
747 | raise SpotifyStateError(self.state, state)
748 | return code
749 |
750 | def get_authorization_code(self, response=None):
751 | if response:
752 | return self.parse_response_code(response)
753 | return self._get_auth_response()
754 |
755 | def get_cached_token(self):
756 | """ Gets a cached auth token
757 | """
758 | token_info = None
759 |
760 | try:
761 | f = open(self.cache_path)
762 | token_info_string = f.read()
763 | f.close()
764 | token_info = json.loads(token_info_string)
765 |
766 | # if scopes don't match, then bail
767 | if "scope" not in token_info or not self._is_scope_subset(
768 | self.scope, token_info["scope"]
769 | ):
770 | return None
771 |
772 | if self.is_token_expired(token_info):
773 | token_info = self.refresh_access_token(
774 | token_info["refresh_token"]
775 | )
776 |
777 | except IOError:
778 | logger.warning("Couldn't read cache at: %s", self.cache_path)
779 |
780 | return token_info
781 |
782 | def _is_scope_subset(self, needle_scope, haystack_scope):
783 | needle_scope = set(needle_scope.split()) if needle_scope else set()
784 | haystack_scope = (
785 | set(haystack_scope.split()) if haystack_scope else set()
786 | )
787 | return needle_scope <= haystack_scope
788 |
789 | def is_token_expired(self, token_info):
790 | return is_token_expired(token_info)
791 |
792 | def _save_token_info(self, token_info):
793 | if self.cache_path:
794 | try:
795 | f = open(self.cache_path, "w")
796 | f.write(json.dumps(token_info))
797 | f.close()
798 | except IOError:
799 | logger.warning('Couldn\'t write token to cache at: %s',
800 | self.cache_path)
801 |
802 | def _add_custom_values_to_token_info(self, token_info):
803 | """
804 | Store some values that aren't directly provided by a Web API
805 | response.
806 | """
807 | token_info["expires_at"] = int(time.time()) + token_info["expires_in"]
808 | return token_info
809 |
810 | def get_pkce_handshake_parameters(self):
811 | self.code_verifier = self._get_code_verifier()
812 | self.code_challenge = self._get_code_challenge()
813 |
814 | def get_access_token(self, code=None, check_cache=True):
815 | """ Gets the access token for the app
816 |
817 | If the code is not given and no cached token is used, an
818 | authentication window will be shown to the user to get a new
819 | code.
820 |
821 | Parameters:
822 | - code - the response code from authentication
823 | - check_cache - if true, checks for locally stored token
824 | before requesting a new token if True
825 | """
826 |
827 | if check_cache:
828 | token_info = self.get_cached_token()
829 | if token_info is not None:
830 | if is_token_expired(token_info):
831 | token_info = self.refresh_access_token(
832 | token_info["refresh_token"]
833 | )
834 | return token_info["access_token"]
835 |
836 | if self.code_verifier is None or self.code_challenge is None:
837 | self.get_pkce_handshake_parameters()
838 |
839 | payload = {
840 | "client_id": self.client_id,
841 | "grant_type": "authorization_code",
842 | "code": code or self.get_authorization_code(),
843 | "redirect_uri": self.redirect_uri,
844 | "code_verifier": self.code_verifier
845 | }
846 |
847 | headers = {"Content-Type": "application/x-www-form-urlencoded"}
848 |
849 | response = self._session.post(
850 | self.OAUTH_TOKEN_URL,
851 | data=payload,
852 | headers=headers,
853 | verify=True,
854 | proxies=self.proxies,
855 | timeout=self.requests_timeout,
856 | )
857 | if response.status_code != 200:
858 | error_payload = response.json()
859 | raise SpotifyOauthError('error: {0}, error_descr: {1}'.format(error_payload['error'],
860 | error_payload[
861 | 'error_description'
862 | ]),
863 | error=error_payload['error'],
864 | error_description=error_payload['error_description'])
865 | token_info = response.json()
866 | token_info = self._add_custom_values_to_token_info(token_info)
867 | self._save_token_info(token_info)
868 | return token_info["access_token"]
869 |
870 | def refresh_access_token(self, refresh_token):
871 | payload = {
872 | "refresh_token": refresh_token,
873 | "grant_type": "refresh_token",
874 | "client_id": self.client_id,
875 | }
876 |
877 | headers = {"Content-Type": "application/x-www-form-urlencoded"}
878 |
879 | response = self._session.post(
880 | self.OAUTH_TOKEN_URL,
881 | data=payload,
882 | headers=headers,
883 | proxies=self.proxies,
884 | timeout=self.requests_timeout,
885 | )
886 |
887 | try:
888 | response.raise_for_status()
889 | except BaseException:
890 | logger.error('Couldn\'t refresh token. Response Status Code: %s '
891 | 'Reason: %s', response.status_code, response.reason)
892 |
893 | message = "Couldn't refresh token: code:%d reason:%s" % (
894 | response.status_code,
895 | response.reason,
896 | )
897 | raise SpotifyException(response.status_code,
898 | -1,
899 | message,
900 | headers)
901 |
902 | token_info = response.json()
903 | token_info = self._add_custom_values_to_token_info(token_info)
904 | if "refresh_token" not in token_info:
905 | token_info["refresh_token"] = refresh_token
906 | self._save_token_info(token_info)
907 | return token_info
908 |
909 | def parse_response_code(self, url):
910 | """ Parse the response code in the given response url
911 |
912 | Parameters:
913 | - url - the response url
914 | """
915 | _, code = self.parse_auth_response_url(url)
916 | if code is None:
917 | return url
918 | else:
919 | return code
920 |
921 | @staticmethod
922 | def parse_auth_response_url(url):
923 | return SpotifyOAuth.parse_auth_response_url(url)
924 |
925 |
926 | class SpotifyImplicitGrant(SpotifyAuthBase):
927 | """ Implements Implicit Grant Flow for client apps
928 |
929 | This auth manager enables *user and non-user* endpoints with only
930 | a client secret, redirect uri, and username. The user will need to
931 | copy and paste a URI from the browser every hour.
932 |
933 | Security Warning
934 | -----------------
935 | The OAuth standard no longer recommends the Implicit Grant Flow for
936 | client-side code. Spotify has implemented the OAuth-suggested PKCE
937 | extension that removes the need for a client secret in the
938 | Authentication Code flow. Use the SpotifyPKCE auth manager instead
939 | of SpotifyImplicitGrant.
940 |
941 | SpotifyPKCE contains all of the functionality of
942 | SpotifyImplicitGrant, plus automatic response retrieval and
943 | refreshable tokens. Only a few replacements need to be made:
944 |
945 | * get_auth_response()['access_token'] ->
946 | get_access_token(get_authorization_code())
947 | * get_auth_response() ->
948 | get_access_token(get_authorization_code()); get_cached_token()
949 | * parse_response_token(url)['access_token'] ->
950 | get_access_token(parse_response_code(url))
951 | * parse_response_token(url) ->
952 | get_access_token(parse_response_code(url)); get_cached_token()
953 |
954 | The security concern in the Implict Grant flow is that the token is
955 | returned in the URL and can be intercepted through the browser. A
956 | request with an authorization code and proof of origin could not be
957 | easily intercepted without a compromised network.
958 | """
959 | OAUTH_AUTHORIZE_URL = "https://accounts.spotify.com/authorize"
960 |
961 | def __init__(self,
962 | client_id=None,
963 | redirect_uri=None,
964 | state=None,
965 | scope=None,
966 | cache_path=None,
967 | username=None,
968 | show_dialog=False):
969 | """ Creates Auth Manager using the Implicit Grant flow
970 |
971 | **See help(SpotifyImplictGrant) for full Security Warning**
972 |
973 | Parameters
974 | ----------
975 | * client_id: Must be supplied or set as environment variable
976 | * redirect_uri: Must be supplied or set as environment variable
977 | * state: May be supplied, no verification is performed
978 | * scope: May be supplied, intuitively converted to proper format
979 | * cache_path: May be supplied, will otherwise be generated
980 | (takes precedence over `username`)
981 | * username: May be supplied or set as environment variable
982 | (will set `cache_path` to `.cache-{username}`)
983 | * show_dialog: Interpreted as boolean
984 | """
985 | logger.warning("The OAuth standard no longer recommends the Implicit "
986 | "Grant Flow for client-side code. Use the SpotifyPKCE "
987 | "auth manager instead of SpotifyImplicitGrant. For "
988 | "more details and a guide to switching, see "
989 | "help(SpotifyImplictGrant).")
990 |
991 | self.client_id = client_id
992 | self.redirect_uri = redirect_uri
993 | self.state = state
994 | self.username = username or os.getenv(
995 | CLIENT_CREDS_ENV_VARS["client_username"]
996 | )
997 | self.cache_path = _get_cache_path(cache_path, self.username)
998 | self.scope = self._normalize_scope(scope)
999 | self.show_dialog = show_dialog
1000 | self._session = None # As to not break inherited __del__
1001 |
1002 | def get_cached_token(self):
1003 | """ Gets a cached auth token
1004 | """
1005 | token_info = None
1006 |
1007 | try:
1008 | f = open(self.cache_path)
1009 | token_info_string = f.read()
1010 | f.close()
1011 | token_info = json.loads(token_info_string)
1012 |
1013 | # if scopes don't match, then bail
1014 | if "scope" not in token_info or not self._is_scope_subset(
1015 | self.scope, token_info["scope"]
1016 | ):
1017 | return None
1018 |
1019 | if self.is_token_expired(token_info):
1020 | return None
1021 |
1022 | except IOError:
1023 | logger.warning("Couldn't read cache at: %s", self.cache_path)
1024 |
1025 | return token_info
1026 |
1027 | def _save_token_info(self, token_info):
1028 | try:
1029 | f = open(self.cache_path, "w")
1030 | f.write(json.dumps(token_info))
1031 | f.close()
1032 | except IOError:
1033 | logger.warning("Couldn't write token to cache at: %s", self.cache_path)
1034 |
1035 | def _is_scope_subset(self, needle_scope, haystack_scope):
1036 | needle_scope = set(needle_scope.split()) if needle_scope else set()
1037 | haystack_scope = (
1038 | set(haystack_scope.split()) if haystack_scope else set()
1039 | )
1040 | return needle_scope <= haystack_scope
1041 |
1042 | def is_token_expired(self, token_info):
1043 | return is_token_expired(token_info)
1044 |
1045 | def get_access_token(self,
1046 | state=None,
1047 | response=None,
1048 | check_cache=True):
1049 | """ Gets Auth Token from cache (preferred) or user interaction
1050 |
1051 | Parameters
1052 | ----------
1053 | * state: May be given, overrides (without changing) self.state
1054 | * response: URI with token, can break expiration checks
1055 | * check_cache: Interpreted as boolean
1056 | """
1057 | if check_cache:
1058 | token_info = self.get_cached_token()
1059 | if not (token_info is None or is_token_expired(token_info)):
1060 | return token_info["access_token"]
1061 |
1062 | if response:
1063 | token_info = self.parse_response_token(response)
1064 | else:
1065 | token_info = self.get_auth_response(state)
1066 | token_info = self._add_custom_values_to_token_info(token_info)
1067 | self._save_token_info(token_info)
1068 |
1069 | return token_info["access_token"]
1070 |
1071 | def _normalize_scope(self, scope):
1072 | if scope:
1073 | scopes = sorted(scope.split())
1074 | return " ".join(scopes)
1075 | else:
1076 | return None
1077 |
1078 | def get_authorize_url(self, state=None):
1079 | """ Gets the URL to use to authorize this app """
1080 | payload = {
1081 | "client_id": self.client_id,
1082 | "response_type": "token",
1083 | "redirect_uri": self.redirect_uri,
1084 | }
1085 | if self.scope:
1086 | payload["scope"] = self.scope
1087 | if state is None:
1088 | state = self.state
1089 | if state is not None:
1090 | payload["state"] = state
1091 | if self.show_dialog:
1092 | payload["show_dialog"] = True
1093 |
1094 | urlparams = urllibparse.urlencode(payload)
1095 |
1096 | return "%s?%s" % (self.OAUTH_AUTHORIZE_URL, urlparams)
1097 |
1098 | def parse_response_token(self, url, state=None):
1099 | """ Parse the response code in the given response url """
1100 | remote_state, token, t_type, exp_in = self.parse_auth_response_url(url)
1101 | if state is None:
1102 | state = self.state
1103 | if state is not None and remote_state != state:
1104 | raise SpotifyStateError(state, remote_state)
1105 | return {"access_token": token, "token_type": t_type,
1106 | "expires_in": exp_in, "state": state}
1107 |
1108 | @staticmethod
1109 | def parse_auth_response_url(url):
1110 | url_components = urlparse(url)
1111 | fragment_s = url_components.fragment
1112 | query_s = url_components.query
1113 | form = dict(i.split('=') for i
1114 | in (fragment_s or query_s or url).split('&'))
1115 | if "error" in form:
1116 | raise SpotifyOauthError("Received error from auth server: "
1117 | "{}".format(form["error"]),
1118 | state=form["state"])
1119 | if "expires_in" in form:
1120 | form["expires_in"] = int(form["expires_in"])
1121 | return tuple(form.get(param) for param in ["state", "access_token",
1122 | "token_type", "expires_in"])
1123 |
1124 | def _open_auth_url(self, state=None):
1125 | auth_url = self.get_authorize_url(state)
1126 | try:
1127 | webbrowser.open(auth_url)
1128 | logger.info("Opened %s in your browser", auth_url)
1129 | except webbrowser.Error:
1130 | logger.error("Please navigate here: %s", auth_url)
1131 |
1132 | def get_auth_response(self, state=None):
1133 | """ Gets a new auth **token** with user interaction """
1134 | logger.info('User authentication requires interaction with your '
1135 | 'web browser. Once you enter your credentials and '
1136 | 'give authorization, you will be redirected to '
1137 | 'a url. Paste that url you were directed to to '
1138 | 'complete the authorization.')
1139 |
1140 | redirect_info = urlparse(self.redirect_uri)
1141 | redirect_host, redirect_port = get_host_port(redirect_info.netloc)
1142 | # Implicit Grant tokens are returned in a hash fragment
1143 | # which is only available to the browser. Therefore, interactive
1144 | # URL retrival is required.
1145 | if (redirect_host in ("127.0.0.1", "localhost")
1146 | and redirect_info.scheme == "http" and redirect_port):
1147 | logger.warning('Using a local redirect URI with a '
1148 | 'port, likely expecting automatic '
1149 | 'retrieval. Due to technical limitations, '
1150 | 'the authentication token cannot be '
1151 | 'automatically retrieved and must be '
1152 | 'copied and pasted.')
1153 |
1154 | self._open_auth_url(state)
1155 | logger.info('Paste that url you were directed to in order to '
1156 | 'complete the authorization')
1157 | response = SpotifyImplicitGrant._get_user_input("Enter the URL you "
1158 | "were redirected to: ")
1159 | return self.parse_response_token(response, state)
1160 |
1161 | def _add_custom_values_to_token_info(self, token_info):
1162 | """
1163 | Store some values that aren't directly provided by a Web API
1164 | response.
1165 | """
1166 | token_info["expires_at"] = int(time.time()) + token_info["expires_in"]
1167 | token_info["scope"] = self.scope
1168 | return token_info
1169 |
1170 |
1171 | class RequestHandler(BaseHTTPRequestHandler):
1172 | def do_GET(self):
1173 | self.server.auth_code = self.server.error = None
1174 | try:
1175 | state, auth_code = SpotifyOAuth.parse_auth_response_url(self.path)
1176 | self.server.state = state
1177 | self.server.auth_code = auth_code
1178 | except SpotifyOauthError as err:
1179 | self.server.state = err.state
1180 | self.server.error = err.error
1181 |
1182 | self.send_response(200)
1183 | self.send_header("Content-Type", "text/html")
1184 | self.end_headers()
1185 |
1186 | if self.server.auth_code:
1187 | status = "successful"
1188 | elif self.server.error:
1189 | status = "failed ({})".format(self.server.error)
1190 | else:
1191 | self._write("