├── .github └── workflows │ └── deploy.yml ├── LICENSE ├── README.md ├── server ├── .env.example ├── .eslintrc.js ├── .gitignore ├── .vscode │ └── launch.json ├── package-lock.json ├── package.json ├── prisma │ ├── migrations │ │ ├── 20230321001753_init │ │ │ └── migration.sql │ │ ├── 20230321004112_init │ │ │ └── migration.sql │ │ └── migration_lock.toml │ └── schema.prisma ├── src │ ├── api │ │ ├── index.js │ │ └── songs │ │ │ ├── middlewares.js │ │ │ ├── songs.routes.js │ │ │ └── songs.services.js │ ├── app.js │ ├── config.js │ ├── index.js │ ├── middlewares.js │ └── utils │ │ └── db.js └── test │ └── api.test.js └── static ├── CNAME ├── assets ├── interaction.wav ├── key0.mp3 ├── key1.mp3 ├── key2.mp3 ├── key3.mp3 └── placeholder.png ├── favicon.ico ├── index.html ├── manifest.webmanifest ├── scripts ├── index.js ├── lastfm.api.cache.js ├── lastfm.api.js └── lastfm.api.md5.js └── styles └── index.css /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy 2 | 3 | on: 4 | push: 5 | paths: 6 | - static/* 7 | workflow_dispatch: 8 | 9 | jobs: 10 | deploy: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | 15 | - name: Deploy 16 | uses: s0/git-publish-subdir-action@develop 17 | env: 18 | REPO: self 19 | BRANCH: gh-pages 20 | FOLDER: static 21 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 22 | -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # osum!player - A music player for the web 2 | 3 | A music player built in vanilla web technologies out of the need of a good music player. 4 | 5 | ## 🔬 Demo 6 | 7 | Visit [music.osumatrix.me](https://music.osumatrix.me/) for a demo! 8 | 9 | ## 🖼️ Previews 10 | 11 | Get a glimpse of osum!player and it's features. 12 | 13 | ### ▶️ Player 14 | 15 | Intuitive and minimalistic player with your keyboard in mind. 16 | 17 | 18 | 19 | ### 🔍 Search 20 | 21 | Effortless instant global search. 22 | 23 | 24 | 25 | ### 🚩 Marker 26 | 27 | Add marker to your favourite spots or highlights. 28 | 29 | 30 | 31 | ### 📱 Mobile view 32 | 33 | Access the player from any device. 34 | 35 | 36 | 37 | ## ⭐ Features 38 | 39 | - Fast & responsive 40 | - Mark hot spots 41 | - Intuitive UX 42 | - Minimal design 43 | - Keyboard oriented 44 | - Autoplay, shuffle, repeat or play once 45 | - Global search 46 | - Play history 47 | 48 | ## 🪛 Server setup 49 | 50 | 1. Clone the repository: 51 | 52 | ```bash 53 | git clone git@github.com/oSumAtrIX/osum-player 54 | cd osum-player/server 55 | ``` 56 | 57 | 2. Install dependencies 58 | 59 | 1. Install libjpeg development package if you are on Linux 60 | 2. Run `npm i` 61 | 62 | 3. Migrate the database: 63 | 64 | ```bash 65 | npx prisma migrate deploy 66 | ``` 67 | 68 | 4. Configure environment variables following the example from `env.example`: 69 | 70 | 5. Start the server 71 | 72 | ```bash 73 | npm start 74 | ``` 75 | 76 | ## ⌨️ Keybinds 77 | 78 | | Shortcut | Description | 79 | | ------------ | ----------------------------------------------------------------------------------------------- | 80 | | `CTRL+P` | Rotate between play modes (Autoplay, shuffle, repeat or play once) | 81 | | `CTRL+M` | Add marker to highlight hotspots in your songs | 82 | | `CTRL+C` | Clear all markers | 83 | | `CTRL+A` | Toggle animations | 84 | | `CTRL+E` | Rotate between endpoints | 85 | | `CTRL+S` | Sort by modified date or added | 86 | | `CTRL+Plus` | Increase volume | 87 | | `CTRL+Minus` | Decrease volume | 88 | | `CTRL+R` | Quick reload songs to update the database | 89 | | `CTRL+H` | Rotate between random themes | 90 | | `A-Za-z` | Start a search | 91 | | `Escape` | Exit search | 92 | | `Space` | Play, pause, or start a song | 93 | | `Enter` | Start the currently selected song or search result | 94 | | `ArrowLeft` | Scrub backward (Hold `SHIFT` for fine and `CTRL` for rough scrubbing) or play the previous song | 95 | | `ArrowRight` | Scrub forward (Hold `SHIFT` for fine and `CTRL` for rough scrubbing) | 96 | | `ArrowUp` | Select the previous song or the previous search result | 97 | | `ArrowDown` | Play the next song or select the next search result | 98 | | `Home` | Skip to the beginning of the current song | 99 | | `End` | Skip to the end of the current song | 100 | | `PageUp` | Play the previous song | 101 | | `PageDown` | Play the next song | 102 | | `0-9` | Seek to the corresponding time of the song | 103 | 104 | > **Note**: You can use your mouse wheel on the seekbar or album cover to adjust the volume. 105 | 106 | ## 🚀 Action launcher 107 | 108 | You can use the action launcher to quickly perform actions such as playing a song, or changing and toggling settings. 109 | The acton launcher can be opened anytime by typing `>` everywhere or in the quick search bar. 110 | 111 | ## 🚩 Marker 112 | 113 | To add a marker, press `CTRL+M`. The marker will appear on the seekbar which can be useful to highlight or mark favourite parts. 114 | To clear all markers, press `CTRL+C`. The markers will automatically show up when playing songs. 115 | 116 | ## 🐔 Easter egg 117 | 118 | Play with the album cover. 119 | 120 | ## 📝 Todo 121 | 122 | - [x] Backend server 123 | - [x] Adjusting volume with keybinds 124 | - [x] Sort by newest modification date 125 | - [x] Marker 126 | - [x] Various play modes 127 | - [x] Rainbow seekbar (Rotate between themes) 128 | - [x] Last.FM integration 129 | - [ ] Keybinds menu 130 | - [ ] Playlists 131 | - [ ] Queues 132 | - [ ] Sync live changes 133 | - [ ] Global hotkeys 134 | - [ ] Add new audio files with drag & drop 135 | - [ ] Share links 136 | -------------------------------------------------------------------------------- /server/.env.example: -------------------------------------------------------------------------------- 1 | SERVER_PORT=3000 # the port the server will listen on 2 | SONGS_PATH=songs/ # the path to the songs folder 3 | SONGS_PER_OFFSET=32 # the number of songs to return per offset 4 | DATABASE_URL="file:./database.db?connection_limit=1" # database url 5 | IMAGE_CACHE_PATH=cache/ # the path to the image cache folder 6 | DEMO_MODE=false # whether to enable demo mode 7 | AUTH_TOKEN= # optional authorization token -------------------------------------------------------------------------------- /server/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | es2021: true, 4 | node: true 5 | }, 6 | extends: 'standard', 7 | overrides: [ 8 | ], 9 | parserOptions: { 10 | ecmaVersion: 'latest', 11 | sourceType: 'module' 12 | }, 13 | rules: { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | /songs 4 | database.db 5 | cache -------------------------------------------------------------------------------- /server/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "node", 6 | "request": "launch", 7 | "name": "nodemon", 8 | "runtimeExecutable": "nodemon", 9 | "program": "${workspaceFolder}/src/index.js", 10 | "restart": true, 11 | "console": "integratedTerminal", 12 | "internalConsoleOptions": "neverOpen" 13 | } 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "osum-player", 3 | "version": "0.1.0", 4 | "description": "A music player built in vanilla web technologies out of the need of a good music player", 5 | "main": "index.js", 6 | "scripts": { 7 | "lint": "eslint --fix src", 8 | "test": "mocha --exit", 9 | "start": "node src/index.js", 10 | "debug": "nodemon src/index.js" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/oSumAtrIX/osum-player.git" 15 | }, 16 | "author": "oSumAtrIX", 17 | "license": "GPL-3.0-or-later", 18 | "bugs": { 19 | "url": "https://github.com/oSumAtrIX/osum-player/issues" 20 | }, 21 | "type": "module", 22 | "homepage": "https://osumatrix.me", 23 | "dependencies": { 24 | "@prisma/client": "^4.11.0", 25 | "chokidar": "^3.5.3", 26 | "cookie-parser": "^1.4.6", 27 | "cors": "^2.8.5", 28 | "dotenv": "^16.0.3", 29 | "express": "^4.18.2", 30 | "hound": "^1.0.5", 31 | "imagemin": "^8.0.1", 32 | "imagemin-webp": "^8.0.0", 33 | "music-metadata": "^8.1.3", 34 | "parse-filepath": "^1.0.2", 35 | "sha1": "^1.1.1" 36 | }, 37 | "devDependencies": { 38 | "eslint": "^8.35.0", 39 | "eslint-config-standard": "^17.0.0", 40 | "eslint-plugin-import": "^2.27.5", 41 | "eslint-plugin-n": "^15.6.1", 42 | "eslint-plugin-promise": "^6.1.1", 43 | "morgan": "^1.10.0", 44 | "prisma": "^4.11.0", 45 | "supertest": "^6.3.1" 46 | } 47 | } -------------------------------------------------------------------------------- /server/prisma/migrations/20230321001753_init/migration.sql: -------------------------------------------------------------------------------- 1 | -- CreateTable 2 | CREATE TABLE "Song" ( 3 | "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 4 | "title" TEXT, 5 | "artist" TEXT, 6 | "filename" TEXT NOT NULL, 7 | "image" BOOLEAN NOT NULL, 8 | "modified" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP 9 | ); 10 | 11 | -- CreateTable 12 | CREATE TABLE "Marker" ( 13 | "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 14 | "songId" INTEGER NOT NULL, 15 | "marker" REAL NOT NULL, 16 | CONSTRAINT "Marker_songId_fkey" FOREIGN KEY ("songId") REFERENCES "Song" ("id") ON DELETE RESTRICT ON UPDATE CASCADE 17 | ); 18 | 19 | -- CreateIndex 20 | CREATE UNIQUE INDEX "Song_filename_key" ON "Song"("filename"); 21 | -------------------------------------------------------------------------------- /server/prisma/migrations/20230321004112_init/migration.sql: -------------------------------------------------------------------------------- 1 | -- RedefineTables 2 | PRAGMA foreign_keys=OFF; 3 | CREATE TABLE "new_Marker" ( 4 | "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 5 | "songId" INTEGER NOT NULL, 6 | "marker" REAL NOT NULL, 7 | CONSTRAINT "Marker_songId_fkey" FOREIGN KEY ("songId") REFERENCES "Song" ("id") ON DELETE CASCADE ON UPDATE CASCADE 8 | ); 9 | INSERT INTO "new_Marker" ("id", "marker", "songId") SELECT "id", "marker", "songId" FROM "Marker"; 10 | DROP TABLE "Marker"; 11 | ALTER TABLE "new_Marker" RENAME TO "Marker"; 12 | PRAGMA foreign_key_check; 13 | PRAGMA foreign_keys=ON; 14 | -------------------------------------------------------------------------------- /server/prisma/migrations/migration_lock.toml: -------------------------------------------------------------------------------- 1 | # Please do not edit this file manually 2 | # It should be added in your version-control system (i.e. Git) 3 | provider = "sqlite" -------------------------------------------------------------------------------- /server/prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | generator client { 2 | provider = "prisma-client-js" 3 | } 4 | 5 | datasource db { 6 | provider = "sqlite" 7 | url = env("DATABASE_URL") 8 | } 9 | 10 | model Song { 11 | id Int @id @default(autoincrement()) 12 | title String? 13 | artist String? 14 | filename String @unique 15 | image Boolean 16 | modified DateTime @default(now()) 17 | marker Marker[] 18 | } 19 | 20 | model Marker { 21 | id Int @id @default(autoincrement()) 22 | songId Int 23 | marker Float 24 | song Song @relation(fields: [songId], references: [id], onDelete: Cascade) 25 | } 26 | -------------------------------------------------------------------------------- /server/src/api/index.js: -------------------------------------------------------------------------------- 1 | import { Router } from "express"; 2 | 3 | import songs from "./songs/songs.routes.js"; 4 | 5 | const router = Router(); 6 | 7 | router.get("/", (_, res) => { 8 | res.json({ 9 | message: "osum!player server API v1", 10 | }); 11 | }); 12 | 13 | router.use("/songs", songs); 14 | 15 | export default router; 16 | -------------------------------------------------------------------------------- /server/src/api/songs/middlewares.js: -------------------------------------------------------------------------------- 1 | import { findSong } from "./songs.services.js"; 2 | import config from "../../config.js"; 3 | 4 | export function checkDemoMode(_req, res, next) { 5 | if (config.DEMO_MODE) return res.json({ message: "This API is not available in demo mode" }); 6 | 7 | next(); 8 | } 9 | 10 | export function getId(req, _res, next) { 11 | const id = parseInt(req.params.id); 12 | 13 | if (isNaN(id)) return next(new Error("Invalid song id")); 14 | 15 | req.id = id; 16 | 17 | next(); 18 | } 19 | 20 | export async function getSong(req, _res, next) { 21 | if (!req.id) return next(new Error("No id")); 22 | 23 | try { 24 | req.song = await findSong(req.id); 25 | 26 | if (req.song === null) return next(new Error("Song not found")); 27 | } catch (err) { 28 | return next(err); 29 | } 30 | 31 | next(); 32 | } -------------------------------------------------------------------------------- /server/src/api/songs/songs.routes.js: -------------------------------------------------------------------------------- 1 | import { Router } from "express"; 2 | import { 3 | findSongs, 4 | getSongFile, 5 | getSongImage, 6 | getMarker, 7 | findSongIdsByQuery, 8 | findIdsByOffset, 9 | findIdsByModifiedDate, 10 | reload, 11 | watch, 12 | stopWatch, 13 | clearMarker, 14 | addMarker, 15 | findSongRandom, 16 | } from "./songs.services.js"; 17 | import { getSong, getId, checkDemoMode } from "./middlewares.js"; 18 | 19 | const router = Router(); 20 | 21 | const defaultSongColumnsSelection = { 22 | artist: true, 23 | title: true, 24 | id: true, 25 | image: true, 26 | modified: true, 27 | }; 28 | 29 | router.get("/", async (req, res, next) => { 30 | if (req.query.hasOwnProperty("q")) { 31 | return res.json( 32 | await findSongIdsByQuery( 33 | req.query.q, 34 | parseInt(req.query.limit || 8), 35 | parseInt(req.query.offset || 0) 36 | ) 37 | ); 38 | } 39 | next(); 40 | }); 41 | 42 | router.patch("/", checkDemoMode, async (req, res, _next) => { 43 | if (req.query.hasOwnProperty("watch")) { 44 | watch(); 45 | res.json({ message: "Watching for changes" }); 46 | } else { 47 | stopWatch(); 48 | res.json({ message: "Stopped watching for changes" }); 49 | } 50 | }); 51 | 52 | router.post("/reload", checkDemoMode, async (req, res, next) => { 53 | const start = Date.now(); 54 | 55 | const full = req.query.hasOwnProperty("full"); 56 | try { 57 | await reload(full); 58 | } catch (err) { 59 | return next(err); 60 | } 61 | 62 | const end = Date.now(); 63 | res.json(`Reloaded songs in ${end - start}ms`); 64 | }); 65 | 66 | router.patch("/:id/marker", checkDemoMode, getId, async (req, res, next) => { 67 | if (!req.body.marker) return next(new Error("Invalid body")); 68 | if (req.body.marker === "clear") { 69 | try { 70 | await clearMarker(req.id); 71 | } catch (err) { 72 | return next(err); 73 | } 74 | 75 | return res.json({ message: "Cleared marker" }); 76 | } 77 | 78 | const marker = parseFloat(req.body.marker); 79 | 80 | if (isNaN(marker)) return next(new Error("Marker must be a number")); 81 | 82 | try { 83 | await addMarker(req.id, marker); 84 | } catch (err) { 85 | return next(err); 86 | } 87 | 88 | res.json({ message: "Added marker" }); 89 | }); 90 | 91 | router.get("/offset/:offset", async (req, res, next) => { 92 | const offset = parseInt(req.params.offset); 93 | 94 | if (isNaN(offset)) return next(new Error("Invalid offset")); 95 | 96 | const sortByModifiedDate = req.query.hasOwnProperty("sortByModifiedDate"); 97 | 98 | let songs = null; 99 | try { 100 | songs = sortByModifiedDate 101 | ? await findIdsByModifiedDate(offset) 102 | : await findIdsByOffset(offset); 103 | } catch (err) { 104 | return next(err); 105 | } 106 | 107 | if (songs == null) return next(new Error("Failed to get songs")); 108 | 109 | res.json(songs); 110 | }); 111 | 112 | router.get("/random", async (_req, res, _next) => { 113 | const song = await findSongRandom(defaultSongColumnsSelection); 114 | res.json(song); 115 | }); 116 | 117 | router.get("/:id/file", getId, async (req, res, next) => { 118 | let filename = null; 119 | try { 120 | filename = await getSongFile(req.id); 121 | } catch (err) { 122 | return next(err); 123 | } 124 | 125 | if (filename === null) { 126 | res.status(404); 127 | res.end(); 128 | return; 129 | } 130 | 131 | res.setHeader("Content-Type", "audio/mpeg"); 132 | res.sendFile(filename); 133 | }); 134 | 135 | router.get("/:id/image", getId, async (req, res, next) => { 136 | const full = req.query.hasOwnProperty("full"); 137 | 138 | let image; 139 | try { 140 | image = await getSongImage(req.id, full); 141 | } catch (err) { 142 | return next(err); 143 | } 144 | 145 | if (image === null) { 146 | res.status(404); 147 | res.end(); 148 | return; 149 | } 150 | 151 | res.setHeader("Cache-control", "public, max-age=3600"); 152 | res.setHeader("Content-Type", "image"); 153 | res.end(image); 154 | }); 155 | 156 | router.post("/multiple", async (req, res, next) => { 157 | if (!req.body.ids) return next(new Error("Invalid body")); 158 | if (req.query.ids == "") return res.json([]); 159 | 160 | const songs = await findSongs(req.body.ids, defaultSongColumnsSelection); 161 | res.json(songs); 162 | }); 163 | 164 | router.get("/:id/marker", getId, async (req, res, next) => { 165 | const marker = await getMarker(req.id); 166 | 167 | res.json(marker); 168 | }); 169 | 170 | router.get("/:id", getId, getSong, async (req, res, next) => { 171 | const song = req.song; 172 | 173 | if (song == null) { 174 | res.status(404); 175 | res.end(); 176 | return; 177 | } 178 | 179 | res.json(song); 180 | }); 181 | 182 | router.get("/changes", async (req, res, _next) => { 183 | // TODO: Get changes such as when songs are deleted or added to reflect to the client. Use request query to determine if the changes should be flushed. 184 | // WebSocket is probably the best way to do this. 185 | 186 | res.end(); 187 | }); 188 | 189 | export default router; 190 | -------------------------------------------------------------------------------- /server/src/api/songs/songs.services.js: -------------------------------------------------------------------------------- 1 | import db from "../../utils/db.js"; 2 | import { parseFile } from "music-metadata"; 3 | import path from "path"; 4 | import imagemin from "imagemin"; 5 | import imageminWebp from "imagemin-webp"; 6 | import chokidar from "chokidar"; 7 | import parsePath from "parse-filepath"; 8 | import fs from "fs"; 9 | import sha1 from "sha1"; 10 | import config from "../../config.js"; 11 | 12 | let watcher = null; 13 | 14 | // TODO: Watch on startup of server if enabled previously by saving when enabling and by env variable. 15 | /** 16 | * Start watching for changes. 17 | */ 18 | export function watch() { 19 | stopWatch(); 20 | 21 | const getBaseName = (file) => parsePath(file).basename; 22 | 23 | watcher = chokidar.watch(config.SONGS_PATH, { 24 | ignoreInitial: true, 25 | awaitWriteFinish: { 26 | stabilityThreshold: 2000, 27 | pollInterval: 500, 28 | }, 29 | binaryInterval: 2000, 30 | }); 31 | 32 | watcher 33 | .on("add", async (path) => { 34 | const filename = getBaseName(path); 35 | if (!(await isMissing(getBaseName(filename)))) return; 36 | 37 | await addSongByName(filename); 38 | }) 39 | .on("unlink", async (path) => { 40 | const song = await findByFilename(getBaseName(path)); 41 | await removeSong(song); 42 | }); 43 | } 44 | 45 | /** 46 | * Stop watching for changes. 47 | */ 48 | export async function stopWatch() { 49 | await watcher?.close(); 50 | } 51 | 52 | /** 53 | * Find a song by its id and a list of fields to select. 54 | * @param {number} id The id of the song. 55 | * @param {any} select The fields to select. 56 | * @returns A song. 57 | */ 58 | export function findSong(id, select) { 59 | return db.song.findUnique({ 60 | where: { 61 | id, 62 | }, 63 | select, 64 | }); 65 | } 66 | 67 | /** 68 | * Find songs by their ids. 69 | * @param {number[]} ids The ids of the song. 70 | * @param {any} select The fields to select. 71 | * @returns A list of song ids. 72 | */ 73 | export function findSongs(ids, select) { 74 | return db.song.findMany({ 75 | where: { 76 | id: { in: ids }, 77 | }, 78 | select, 79 | }); 80 | } 81 | 82 | export async function findSongRandom(select) { 83 | const skip = Math.floor(Math.random() * (await db.song.count())); 84 | 85 | const results = await db.song.findMany({ 86 | take: 1, 87 | skip, 88 | select, 89 | }); 90 | 91 | return results[0]; 92 | } 93 | 94 | export async function getSongFile(id) { 95 | const song = await findSong(id, { 96 | filename: true, 97 | }); 98 | 99 | if (song === null) return null; 100 | 101 | return path.join(config.SONGS_PATH, song.filename); 102 | } 103 | 104 | /** 105 | * Get the path to an image given a filename. 106 | * 107 | * @param {string} filename The filename of the song. 108 | * @param {boolean} full If the full image should be returned. 109 | * @returns 110 | */ 111 | function getImagePath(filename, full = false) { 112 | const imageName = sha1(filename + (full ? "_full" : "")); 113 | return path.join(config.IMAGE_CACHE_PATH, imageName); 114 | } 115 | 116 | export async function getSongImage(id, full = false) { 117 | const song = await findSong(id, { 118 | filename: true, 119 | }); 120 | 121 | if (song === null) return null; 122 | 123 | // create path to image 124 | const imagePath = getImagePath(song.filename, full); 125 | 126 | // check if image exists and return it or create it 127 | const imageExists = await fileExists(imagePath); 128 | if (imageExists) return readFile(imagePath); 129 | 130 | let parsedSong; 131 | try { 132 | parsedSong = await parseSongFromFile(song.filename, true); 133 | } catch (e) { 134 | console.log(e); 135 | } 136 | 137 | if (!(parsedSong && parsedSong.image)) return null; 138 | 139 | const image = await compressImage(parsedSong.image, full ? 600 : 64); 140 | 141 | fs.createWriteStream(imagePath).end(image); 142 | 143 | return image; 144 | } 145 | 146 | /** 147 | * Find song ids given a query. 148 | * @param {string} query The query to search for. 149 | * @param {number} limit The limit of songs to return. 150 | * @param {number} offset The offset to start at. 151 | * @param {boolean} orderByModifiedDate Whether to order by modified date. 152 | * @returns A list of song ids. 153 | */ 154 | export function findSongIdsByQuery(query, limit, offset, orderByModifiedDate) { 155 | const args = { 156 | where: { 157 | OR: [ 158 | { title: { contains: query } }, 159 | { artist: { contains: query } }, 160 | { filename: { contains: query } }, 161 | ], 162 | }, 163 | take: limit, 164 | skip: offset, 165 | select: { 166 | id: true, 167 | }, 168 | }; 169 | 170 | if (orderByModifiedDate) 171 | args.orderBy = { 172 | modified: "desc", 173 | }; 174 | 175 | return db.song.findMany(args); 176 | } 177 | 178 | /** 179 | * Find all songs in the database given an offset id. 180 | * @param {number} offset The offset id to start at. 181 | * @returns A list of songs. 182 | */ 183 | export function findIdsByOffset(offset) { 184 | const args = { 185 | where: { id: { gte: offset } }, 186 | take: config.SONGS_PER_OFFSET, 187 | select: { 188 | id: true, 189 | }, 190 | }; 191 | 192 | return db.song.findMany(args); 193 | } 194 | 195 | /** 196 | * Find all songs in the database given an offset id ordered by the song file modified date. 197 | * @param {number} page The page to start at. 198 | * @returns A list of songs. 199 | */ 200 | export function findIdsByModifiedDate(page) { 201 | const args = { 202 | orderBy: { 203 | modified: "desc", 204 | }, 205 | skip: config.SONGS_PER_OFFSET * page, 206 | take: config.SONGS_PER_OFFSET, 207 | select: { 208 | id: true, 209 | }, 210 | }; 211 | 212 | return db.song.findMany(args); 213 | } 214 | 215 | /** 216 | * Add a song to the database. 217 | * @param {Song} song The song to add. 218 | */ 219 | function add(song) { 220 | return db.song.create({ 221 | data: song, 222 | }); 223 | } 224 | 225 | /** 226 | * Add a marker to a song. 227 | * @param {integer} songId The id of the song to add the marker to. 228 | * @param {*} marker The time of the marker. 229 | */ 230 | export function addMarker(songId, marker) { 231 | return db.marker.create({ 232 | data: { 233 | marker, 234 | song: { 235 | connect: { 236 | id: songId, 237 | }, 238 | }, 239 | }, 240 | }); 241 | } 242 | 243 | /** 244 | * Get all markers from a song. 245 | * @param {integer} songId The id of the song to get the markers from. 246 | * @returns A list of markers. 247 | */ 248 | export async function getMarker(songId) { 249 | const marker = await db.marker.findMany({ 250 | where: { 251 | songId, 252 | }, 253 | select: { 254 | marker: true, 255 | }, 256 | }); 257 | return marker.map((marker) => marker.marker); 258 | } 259 | /** 260 | * Clear all marker from a song. 261 | * @param {integer} songId The id of the song to remove the markers from. 262 | */ 263 | export function clearMarker(songId) { 264 | return db.marker.deleteMany({ 265 | where: { 266 | songId, 267 | }, 268 | }); 269 | } 270 | 271 | /** 272 | * Remove a song from the database. 273 | * @param {Song} song The song to remove. 274 | */ 275 | async function removeSong(song) { 276 | const songId = song.id; 277 | 278 | song = await findSong(songId, { 279 | filename: true, 280 | }); 281 | 282 | if (song === null) return; 283 | 284 | deleteCache(song); 285 | 286 | return db.song.delete({ 287 | where: { 288 | id: songId, 289 | }, 290 | }); 291 | } 292 | 293 | function deleteCache(song) { 294 | deleteFile(getImagePath(song.filename)); 295 | deleteFile(getImagePath(song.filename, true)); 296 | } 297 | 298 | function resetCache() { 299 | return new Promise((resolve, _) => 300 | fs.readdir(config.IMAGE_CACHE_PATH, (err, files) => { 301 | if (err) throw err; 302 | 303 | for (const file of files) { 304 | fs.unlink(path.join(config.IMAGE_CACHE_PATH, file), (err) => { 305 | if (err) throw err; 306 | }); 307 | } 308 | 309 | resolve(); 310 | }) 311 | ); 312 | } 313 | 314 | function deleteFile(file) { 315 | if (fileExists(file)) { 316 | fs.unlink(file, () => { }); 317 | } 318 | } 319 | 320 | async function fileExists(filePath) { 321 | return new Promise((resolve) => 322 | fs.access(filePath, fs.constants.F_OK, (err) => resolve(err === null)) 323 | ); 324 | } 325 | 326 | async function readFile(file) { 327 | return new Promise((resolve, reject) => 328 | fs.readFile(file, (err, data) => (err ? reject(err) : resolve(data))) 329 | ); 330 | } 331 | /** 332 | * Removes songs from the database. 333 | * @param {Song[]} songs The songs to remove. 334 | * @returns The number of songs removed. 335 | */ 336 | function removeSongs(songs) { 337 | songs.forEach(deleteCache); 338 | 339 | return db.song.deleteMany({ 340 | where: { 341 | id: { in: songs.map((song) => song.id) }, 342 | }, 343 | }); 344 | } 345 | 346 | /** 347 | * Finds songs by their filename. 348 | * @param {string[]} names A list of filenames 349 | * @returns A list of songs. 350 | */ 351 | function findByFilenames(names) { 352 | return db.song.findMany({ 353 | where: { 354 | filename: { in: names }, 355 | }, 356 | }); 357 | } 358 | 359 | /** 360 | * Finds song by their filename. 361 | * @param {string} name A filename. 362 | * @returns A song. 363 | */ 364 | function findByFilename(name) { 365 | return db.song.findUnique({ 366 | where: { 367 | filename: name, 368 | }, 369 | }); 370 | } 371 | 372 | /** 373 | * Parses a song from a file. 374 | * @param {string} name The filename of the song. 375 | * @param {boolean} getImage Whether to return the image. If false, only the information if the song has an image is returned. 376 | */ 377 | async function parseSongFromFile(name, getImage = false) { 378 | const songPath = path.join(config.SONGS_PATH, name); 379 | 380 | let metadata = await parseFile(songPath); 381 | 382 | return new Promise((resolve, reject) => { 383 | fs.stat(songPath, (err, stats) => { 384 | if (err) return reject(err); 385 | 386 | const modified = stats.mtime; 387 | const song = { 388 | title: metadata.common.title || name, 389 | artist: metadata.common.artist, 390 | filename: name, 391 | modified, 392 | }; 393 | 394 | const picture = metadata.common.picture; 395 | 396 | if (getImage && picture) song.image = picture[0].data; 397 | else song.image = picture != null; 398 | 399 | resolve(song); 400 | }); 401 | }); 402 | } 403 | 404 | async function compressImage(image, size = 64) { 405 | return imagemin.buffer(image, { 406 | plugins: [ 407 | imageminWebp({ resize: { width: size, height: size }, method: 0 }), 408 | ], 409 | }); 410 | } 411 | /** 412 | * Gets all file names from the songs folder. 413 | * @returns A list of filenames. 414 | */ 415 | function getFileNamesFromPath() { 416 | return new Promise((resolve, reject) => 417 | fs.readdir( 418 | config.SONGS_PATH, 419 | { withFileTypes: true }, 420 | (err, files) => { 421 | if (err) return reject(err); 422 | resolve(files.filter((file) => file.isFile()).map((file) => file.name)); 423 | } 424 | ) 425 | ); 426 | } 427 | 428 | /** 429 | * Adds songs to the database given a list of filenames. 430 | * @param {string[]} filenames A list of song filenames. 431 | */ 432 | async function addSongsByName(filenames) { 433 | // Add 10 songs at a time 434 | const chunkSize = 10; 435 | for (let i = 0; i < filenames.length; i += chunkSize) { 436 | const chunk = filenames.slice(i, i + chunkSize); 437 | 438 | const results = await Promise.allSettled( 439 | chunk.map((filename) => parseSongFromFile(filename)) 440 | ); 441 | const songs = results 442 | .filter((result) => result.status === "fulfilled") 443 | .map((result) => result.value); 444 | 445 | await Promise.all(songs.map(add)); 446 | } 447 | } 448 | 449 | /** 450 | * Adds a song to the database given a filename. 451 | * @param {string} filename The filename of the song. 452 | */ 453 | async function addSongByName(filename) { 454 | let parsedSong; 455 | 456 | try { 457 | parsedSong = await parseSongFromFile(filename); 458 | } catch (e) { 459 | console.error(e); 460 | } 461 | 462 | if (!parsedSong) return add({ filename }); 463 | 464 | const song = { 465 | title: parsedSong.title, 466 | artist: parsedSong.artist, 467 | }; 468 | 469 | return add(song); 470 | } 471 | 472 | /** 473 | * Finds the names of songs that are not in the database. 474 | * @param {string[]} filenames A list of song filenames. If not provided, it will get all the songs in the songs folder. 475 | * @returns {string[]} A list of song filenames that are not in the database. 476 | */ 477 | async function findMissingSongs(filenames) { 478 | const names = filenames || (await getFileNamesFromPath()); 479 | 480 | const existing = await findByFilenames(names); 481 | const missingSongs = names.filter( 482 | (song) => !existing.find((name) => song === name.filename) 483 | ); 484 | 485 | return missingSongs; 486 | } 487 | 488 | /** 489 | * Checks if a song is missing from the database. 490 | * @param {string} filename The filename of the song. 491 | * @returns {boolean} True if the song is missing, false otherwise. 492 | */ 493 | async function isMissing(filename) { 494 | const existing = await findByFilename(filename); 495 | return !existing; 496 | } 497 | 498 | /** 499 | * Finds the songs that are orphaned in the database. 500 | * @param {string[]} filenames A list of song filenames. If not provided, it will get all the songs in the songs folder. 501 | * @returns {string[]} A list of songs that do not exist anymore. 502 | */ 503 | async function findOrphanedSongs(filenames) { 504 | const names = filenames || (await getFileNamesFromPath()); 505 | 506 | const existing = await db.song.findMany({ 507 | select: { 508 | id: true, 509 | filename: true, 510 | }, 511 | }); 512 | 513 | const orphaned = existing.filter( 514 | (song) => !names.find((name) => song.filename === name) 515 | ); 516 | 517 | return orphaned; 518 | } 519 | 520 | /** 521 | * Reloads the database with the songs in the songs folder. 522 | * It will add songs that are missing and remove songs that are orphaned. 523 | * @param {boolean} full Whether to delete all songs before reloading. 524 | */ 525 | export async function reload(full = false) { 526 | if (full) { 527 | await db.song.deleteMany({}); 528 | resetCache(); 529 | } 530 | 531 | const songNames = await getFileNamesFromPath(); 532 | 533 | const missingSongs = await findMissingSongs(songNames); 534 | await addSongsByName(missingSongs); 535 | 536 | const orphanedSongs = await findOrphanedSongs(songNames); 537 | await removeSongs(orphanedSongs); 538 | } 539 | -------------------------------------------------------------------------------- /server/src/app.js: -------------------------------------------------------------------------------- 1 | import express, { json } from "express"; 2 | import morgan from "morgan"; 3 | import cors from "cors"; 4 | 5 | import { notFound, handleError, checkAuthorization } from "./middlewares.js"; 6 | import api from "./api/index.js"; 7 | import cookieParser from "cookie-parser"; 8 | 9 | const app = express(); 10 | 11 | app.use(morgan("dev")); 12 | app.use(cors({ origin: true, credentials: true })); 13 | app.use(cookieParser()); 14 | app.use(checkAuthorization); 15 | app.use(json()); 16 | 17 | app.get("/", (_req, res) => { 18 | res.json({ 19 | message: "osum!player server API", 20 | }); 21 | }); 22 | 23 | app.use("/api/v1", api); 24 | 25 | app.use(notFound); 26 | app.use(handleError); 27 | 28 | export default app; 29 | -------------------------------------------------------------------------------- /server/src/config.js: -------------------------------------------------------------------------------- 1 | import dotenv from "dotenv"; 2 | 3 | dotenv.config(); 4 | 5 | const config = { 6 | SERVER_PORT: parseInt(process.env.SERVER_PORT), 7 | SONGS_PATH: process.env.SONGS_PATH, 8 | IMAGE_CACHE_PATH: process.env.IMAGE_CACHE_PATH, 9 | SONGS_PER_OFFSET: parseInt(process.env.SONGS_PER_OFFSET), 10 | DEMO_MODE: process.env.DEMO_MODE === "true", 11 | AUTH_TOKEN: process.env.AUTH_TOKEN 12 | }; 13 | 14 | export default config; -------------------------------------------------------------------------------- /server/src/index.js: -------------------------------------------------------------------------------- 1 | import app from "./app.js"; 2 | import config from "./config.js"; 3 | 4 | const port = config.SERVER_PORT; 5 | app.listen(port, () => { 6 | console.log(`Listening: http://localhost:${port}`); 7 | }); 8 | -------------------------------------------------------------------------------- /server/src/middlewares.js: -------------------------------------------------------------------------------- 1 | import config from "./config.js"; 2 | 3 | export function notFound(_req, res, next) { 4 | res.status(404); 5 | next(new Error(`Not found`)); 6 | } 7 | 8 | export function handleError(err, _req, res, _next) { 9 | const statusCode = res.statusCode !== 200 ? res.statusCode : 400; 10 | res.status(statusCode); 11 | res.json({ 12 | message: err.message, 13 | stack: err.stack, 14 | }); 15 | } 16 | 17 | export function checkAuthorization(req, res, next) { 18 | if (req.method === "OPTIONS") 19 | return next(); 20 | 21 | if (!config.AUTH_TOKEN || req.cookies.authorization === config.AUTH_TOKEN) 22 | return next(); 23 | 24 | res.status(401); 25 | res.end(); 26 | } -------------------------------------------------------------------------------- /server/src/utils/db.js: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from "@prisma/client"; 2 | 3 | /** 4 | * @type {import('@prisma/client').PrismaClient} 5 | */ 6 | const db = new PrismaClient(); 7 | 8 | export default db; 9 | -------------------------------------------------------------------------------- /server/test/api.test.js: -------------------------------------------------------------------------------- 1 | import request from "supertest"; 2 | 3 | import app from "../src/app"; 4 | 5 | describe("GET /api/v1", () => { 6 | it("responds with a json message", (done) => { 7 | request(app) 8 | .get("/api/v1") 9 | .set("Accept", "application/json") 10 | .expect("Content-Type", /json/) 11 | .expect( 12 | 200, 13 | { 14 | message: "osum!player server API v1", 15 | }, 16 | done 17 | ); 18 | }); 19 | }); 20 | -------------------------------------------------------------------------------- /static/CNAME: -------------------------------------------------------------------------------- 1 | music.osumatrix.me -------------------------------------------------------------------------------- /static/assets/interaction.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/interaction.wav -------------------------------------------------------------------------------- /static/assets/key0.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/key0.mp3 -------------------------------------------------------------------------------- /static/assets/key1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/key1.mp3 -------------------------------------------------------------------------------- /static/assets/key2.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/key2.mp3 -------------------------------------------------------------------------------- /static/assets/key3.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/key3.mp3 -------------------------------------------------------------------------------- /static/assets/placeholder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/assets/placeholder.png -------------------------------------------------------------------------------- /static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oSumAtrIX/osum-player/98f8b76c7227e697513e62f151b18585b115d67b/static/favicon.ico -------------------------------------------------------------------------------- /static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | osum!player 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 |
18 |
19 | 20 |
21 |
    22 | 23 |
24 |
25 |
26 |
27 |
28 |
    29 | 30 |
31 |
32 |
33 | song-image 34 |
35 |
36 |
37 | 40 |
41 |
42 |
43 |
44 |
45 |
/
46 |
47 | 48 |
49 |
50 |
51 |
52 |
53 | 54 | 57 | 66 | 77 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /static/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "background_color": "black", 3 | "description": "A music player built in vanilla web technologies out of the need of a good music player.", 4 | "display": "fullscreen", 5 | "icons": [ 6 | { 7 | "src": "assets/placeholder.png", 8 | "sizes": "192x192", 9 | "type": "image/png" 10 | } 11 | ], 12 | "name": "osum!player", 13 | "short_name": "osum!player", 14 | "start_url": "/" 15 | } -------------------------------------------------------------------------------- /static/scripts/index.js: -------------------------------------------------------------------------------- 1 | const $ = (selector, target) => (target || document).querySelector(selector); 2 | 3 | class Song { 4 | constructor(title, artist, image, modified, id) { 5 | const api = `${Song.api}/${id}`; 6 | 7 | this.title = title; 8 | this.artist = artist; 9 | this.image = image ? `${api}/image` : "assets/placeholder.png"; 10 | this.file = `${api}/file`; 11 | this.modified = new Date(modified); 12 | this.marker = undefined; 13 | this.id = id; 14 | } 15 | 16 | addMarker(marker) { 17 | return this.uploadMarkerDelayedAction( 18 | () => this.marker.push(marker), 19 | "Marked", 20 | marker 21 | ); 22 | } 23 | 24 | clearMarker() { 25 | return this.uploadMarkerDelayedAction( 26 | () => (this.marker = []), 27 | "Cleared", 28 | "clear" 29 | ); 30 | } 31 | 32 | getMarker() { 33 | return this.marker; 34 | } 35 | 36 | async loadMarker() { 37 | // if the marker is already loaded, don't load it again 38 | // this is pulled off by setting the marker to undefined initially, 39 | // indicating that it hasn't been loaded yet 40 | if (this.marker) { 41 | SeekbarManager.loadMarkers(); 42 | return; 43 | } 44 | 45 | const marker = await ApiManager.getMarker(this.id); 46 | 47 | this.setMarker(marker); 48 | SeekbarManager.loadMarkers(); 49 | } 50 | 51 | setMarker(marker) { 52 | this.marker = marker; 53 | } 54 | 55 | upload(marker) { 56 | return ApiManager.editSongMarker(this.id, marker); 57 | } 58 | 59 | /** 60 | * Uploads a marker and performs an action on success. 61 | * @param {()} action The action to perform on upload success. 62 | * @param {*} popupMessage The message to show on upload success. 63 | * @param {*} marker The marker to upload. 64 | * @returns {Promise} A promise that resolves when the upload is done. 65 | */ 66 | uploadMarkerDelayedAction(action, popupMessage, marker) { 67 | const uploadTime = 20; // assumed ping to prevent the wrong popup from showing up too early 68 | 69 | const timeout = setTimeout( 70 | () => PopupManager.showPopup(popupMessage), 71 | uploadTime 72 | ); 73 | 74 | return this.upload(marker) 75 | .then(() => action()) 76 | .catch(() => { 77 | clearTimeout(timeout); 78 | PopupManager.showPopup("Failed"); 79 | 80 | return Promise.reject("Failed to upload"); 81 | }); 82 | } 83 | 84 | getFullImage() { 85 | return this.image + "?full"; 86 | } 87 | 88 | static fromJSON(json) { 89 | return new Song( 90 | json.title, 91 | json.artist, 92 | json.image, 93 | json.modified, 94 | json.id 95 | ); 96 | } 97 | 98 | static setApi(api) { 99 | this.api = api; 100 | } 101 | } 102 | 103 | class Action { 104 | static { 105 | this.INPUT = "input"; 106 | this.TOGGLE = "toggle"; 107 | this.ACTION = "action"; 108 | 109 | this.TOGGLE_ON = true; 110 | this.TOGGLE_OFF = false; 111 | 112 | this.HIDDEN = "hidden_input"; 113 | } 114 | 115 | constructor(name, action, type = Action.ACTION, update) { 116 | this.name = name; 117 | this.action = action; 118 | this.type = type; 119 | 120 | this.update = update; 121 | this.updateValue() 122 | } 123 | 124 | updateValue() { 125 | this.value = typeof this.update === "function" ? this.update() : this.update; 126 | } 127 | 128 | select() { 129 | if (this.type == Action.TOGGLE) 130 | this.value = !this.value; 131 | 132 | this.action(this) 133 | } 134 | } 135 | 136 | class PopupManager { 137 | static initialize() { 138 | this.PERMANENT = -1; 139 | 140 | this.popup = $("#popup"); 141 | this.popupContent = $("#popup-text"); 142 | } 143 | 144 | static showPopup(content, duration = 1000) { 145 | // Avoid XSS 146 | if (typeof content === "string") 147 | this.popupContent.innerText = content; 148 | else 149 | this.popupContent.innerHTML = content; 150 | 151 | this.popup.classList.add("popup-active"); 152 | 153 | if (duration < 0) return; 154 | 155 | clearTimeout(this.popupActive); 156 | this.popupActive = setTimeout( 157 | () => this.popup.classList.remove("popup-active"), 158 | duration 159 | ); 160 | } 161 | } 162 | 163 | class SeekbarManager { 164 | static initialize() { 165 | this.seekbar = $("#seekbar"); 166 | this.marker = $("#marker-template").content.firstElementChild; 167 | 168 | this.progress = $("#seekbar-progress", seekbar); 169 | this.knob = $("#seekbar-knob", seekbar); 170 | this.knobCircle = $("#seekbar-knob-circle", this.knob); 171 | 172 | this.currentTime = $("#seekbar-current-time", seekbar); 173 | this.currentTimeText = $("#seekbar-current-time-text", this.currentTime); 174 | this.durationText = $( 175 | "#seekbar-current-song-duration-text", 176 | this.currentTime 177 | ); 178 | 179 | this.isMouseOverSeekbarProp = false; 180 | 181 | this.markerHoverStyle = document.createElement("style"); 182 | this.markerHoverStyle.type = "text/css"; 183 | this.markerHoverStyle.innerHTML = `.marker { 184 | height: 15px !important; 185 | box-shadow: 0 0 20px 3px var(--highlight-yellow) !important; 186 | }`; 187 | 188 | this.seekbarShrunken = true; 189 | this.setSmoothProgressBar(); 190 | 191 | // the last x position of the mouse on the seekbar 192 | this.lastProgressX = 0; 193 | const setProgress = (touch) => { 194 | if (touch.time - this.lastSetProgressCall < 4) return; 195 | this.lastSetProgressCall = touch.time; 196 | 197 | if (Math.abs(this.lastProgressX - touch.x) > 20) { 198 | AudioManager.playInteractionAudio(60); 199 | this.lastProgressX = touch.x; 200 | } 201 | 202 | const calculateProgress = touch.x / this.seekbar.offsetWidth; 203 | SeekbarManager.setProgress(calculateProgress); 204 | AudioManager.setProgress(calculateProgress); 205 | 206 | PopupManager.showPopup(this.currentTimeText.innerText, 800); 207 | }; 208 | 209 | // update seekbar on mouse events 210 | // document is used instead of seekbar because the mouse can leave the seekbar 211 | // and events will stop firing, for that reason mouseDownOriginIsSeekbar is used 212 | 213 | let mouseDownOriginIsSeekbar = false; 214 | 215 | const onSeek = (time, x) => { 216 | 217 | mouseDownOriginIsSeekbar = true; 218 | 219 | AudioManager.pause(); 220 | 221 | // Update the progress instantly. 222 | setProgress({ time, x }) 223 | 224 | document.onmousemove = (e) => { 225 | if (Math.abs(this.lastProgressX - e.clientX) > 20) { 226 | this.setInstantProgressBar(); 227 | } 228 | 229 | setProgress(e) 230 | } 231 | }; 232 | 233 | const onSeekStop = (time, x) => { 234 | this.setSmoothProgressBar(); 235 | 236 | if (!mouseDownOriginIsSeekbar) return; 237 | mouseDownOriginIsSeekbar = false; 238 | 239 | setProgress({ time, x }); 240 | AudioManager.play(); 241 | 242 | // if the mouse is over the seekbar, keep the hover effect 243 | if (!this.isMouseOverSeekbar()) this.shrinkSeekbar(); 244 | 245 | document.onmousemove = null; 246 | }; 247 | 248 | const isTouchDevice = 'ontouchstart' in window; 249 | 250 | if (isTouchDevice) { 251 | this.seekbar.ontouchstart = (e) => onSeek(e.timeStamp, e.changedTouches[0].clientX); 252 | this.seekbar.addEventListener("touchmove", this.seekbar.ontouchstart); 253 | 254 | this.seekbar.addEventListener("touchend", (e) => onSeekStop(e.timeStamp, e.changedTouches[0].clientX)); 255 | } else { 256 | this.seekbar.onmousedown = (e) => onSeek(e.timeStamp, e.clientX); 257 | document.onmouseup = (e) => onSeekStop(e.timeStamp, e.clientX); 258 | } 259 | 260 | // hover effect 261 | 262 | const onHover = () => { 263 | this.isMouseOverSeekbarProp = true; 264 | this.enlargeSeekbar(); 265 | }; 266 | 267 | const onHoverStop = () => { 268 | this.isMouseOverSeekbarProp = false; 269 | 270 | // if the mouse is currently down on seekbar, do not the remove hover effect 271 | if (!mouseDownOriginIsSeekbar && !AudioManager.isPaused()) 272 | this.shrinkSeekbar(); 273 | }; 274 | 275 | if (isTouchDevice) { 276 | this.seekbar.addEventListener("touchmove", onHover) 277 | this.seekbar.addEventListener("touchend", onHoverStop) 278 | } else { 279 | this.seekbar.onmouseenter = onHover; 280 | this.seekbar.onmouseleave = onHoverStop; 281 | } 282 | } 283 | 284 | static loadMarkers() { 285 | this.clearSeekbarMarker(); 286 | 287 | SongManager.getCurrentSong() 288 | .getMarker() 289 | .forEach((marker) => this.addMarkerToSeekbar(marker)); 290 | } 291 | 292 | static setSmoothProgressBar() { 293 | if (this.smoothSeekbar) return; 294 | this.smoothSeekbar = true; 295 | 296 | this.progress.classList.add("seekbar-smooth"); 297 | } 298 | 299 | static setInstantProgressBar() { 300 | if (!this.smoothSeekbar) return; 301 | this.smoothSeekbar = false; 302 | 303 | this.progress.classList.remove("seekbar-smooth"); 304 | } 305 | 306 | static addMarker() { 307 | const marker = 308 | (AudioManager.getCurrentTime() / AudioManager.getDuration()) * 100; 309 | 310 | const song = SongManager.getCurrentSong(); 311 | if (!song) return; 312 | 313 | const markerNode = SeekbarManager.addMarkerToSeekbar(marker); 314 | song.addMarker(marker).catch(() => markerNode.remove()); 315 | } 316 | 317 | static async clearMarker() { 318 | const song = SongManager.getCurrentSong(); 319 | 320 | if (!song) return; 321 | 322 | if (!song.getMarker().length) return; 323 | 324 | song.clearMarker().then(() => SeekbarManager.clearSeekbarMarker()); 325 | } 326 | 327 | static addMarkerToSeekbar(marker) { 328 | const markerNode = this.marker.cloneNode(true); 329 | markerNode.style.left = `${marker}%`; 330 | this.seekbar.appendChild(markerNode); 331 | 332 | return markerNode; 333 | } 334 | 335 | static clearSeekbarMarker() { 336 | this.seekbar 337 | .querySelectorAll(".marker") 338 | .forEach((marker) => marker.remove()); 339 | } 340 | 341 | static hideSeekbar() { 342 | if (!this.seekbarShowing) return; 343 | this.seekbarShowing = false; 344 | 345 | this.seekbar.classList.add("seekbar-hidden"); 346 | } 347 | 348 | static showSeekbar() { 349 | if (this.seekbarShowing) return; 350 | this.seekbarShowing = true; 351 | 352 | this.seekbar.classList.remove("seekbar-hidden"); 353 | } 354 | 355 | static getSeekbar() { 356 | return this.seekbar; 357 | } 358 | 359 | static isMouseOverSeekbar() { 360 | return this.isMouseOverSeekbarProp; 361 | } 362 | 363 | static enlargeSeekbar() { 364 | if (!this.seekbarShrunken) return; 365 | 366 | this.currentTime.classList.add("current-time-active"); 367 | this.knobCircle.classList.add("knob-circle-active"); 368 | this.progress.classList.add("seekbar-hover"); 369 | 370 | this.seekbar.appendChild(this.markerHoverStyle); 371 | 372 | this.seekbarShrunken = false; 373 | } 374 | 375 | static shrinkSeekbar() { 376 | if (this.seekbarShrunken) return; 377 | 378 | this.currentTime.classList.remove("current-time-active"); 379 | this.knobCircle.classList.remove("knob-circle-active"); 380 | this.progress.classList.remove("seekbar-hover"); 381 | 382 | this.seekbar.removeChild(this.markerHoverStyle); 383 | 384 | this.seekbarShrunken = true; 385 | } 386 | 387 | static formatMinutes(time) { 388 | // get total minutes and seconds 389 | const minutes = Math.floor(time / 60); 390 | const seconds = Math.floor(time % 60); 391 | 392 | return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`; 393 | } 394 | /** 395 | * @param {number} progress The progress in the range [0, 1]. 396 | */ 397 | static setProgress(progress) { 398 | if (progress < 0) progress = 0; 399 | if (progress > 1) progress = 1; 400 | this.progress.style.width = progress * 100 + "%"; 401 | 402 | const currentTime = AudioManager.getDuration() * progress; 403 | 404 | // Prevent updating the current time too often. 405 | if (Math.abs(currentTime - this.lastTimeUpdate) < 1) return; 406 | this.lastTimeUpdate = currentTime; 407 | 408 | this.currentTimeText.innerText = this.formatMinutes(currentTime); 409 | } 410 | 411 | /** 412 | * @param {number} duration The duration in seconds. 413 | */ 414 | static setDuration(duration) { 415 | this.durationText.innerText = this.formatMinutes(duration); 416 | } 417 | } 418 | 419 | class ThemeManager { 420 | static initialize() { 421 | const root = document.querySelector(":root"); 422 | const color = localStorage.getItem("highlight") || getComputedStyle(root).getPropertyValue("--highlight"); 423 | this.setTheme(color); 424 | } 425 | 426 | static setTheme(color) { 427 | localStorage.setItem("highlight", color); 428 | 429 | const root = document.querySelector(":root"); 430 | root.style.setProperty("--highlight", color); 431 | } 432 | 433 | static getTheme() { 434 | return getComputedStyle(document.querySelector(":root")).getPropertyValue("--highlight"); 435 | } 436 | 437 | static rotateTheme() { 438 | const rotation = Math.round(Math.random() * 360); 439 | 440 | PopupManager.showPopup(rotation); 441 | 442 | this.setTheme(`hsl(${rotation}, 100%, 50%)`); 443 | } 444 | 445 | static resetTheme() { 446 | this.setTheme("#FF003D"); 447 | } 448 | } 449 | 450 | class EventManager { 451 | static initialize() { 452 | document.onkeydown = (e) => { 453 | switch (e.code) { 454 | case "ControlLeft": 455 | this.control = true; 456 | case "Space": 457 | this.space = true; 458 | case "ShiftLeft": 459 | this.shift = true; 460 | } 461 | 462 | if (!ApiManager.isConnected()) { 463 | if (this.control) { 464 | switch (e.code) { 465 | case "KeyE": 466 | e.preventDefault(); 467 | ApiManager.rotateEndpoint(); 468 | return; 469 | case "KeyR": 470 | e.preventDefault(); 471 | ApiManager.reloadSongs(); 472 | return; 473 | } 474 | } 475 | 476 | return; 477 | } 478 | 479 | 480 | if (!SearchManager.isActive()) { 481 | e.preventDefault(); 482 | 483 | if (this.control) { 484 | AnimationManager.scaleMain(true); 485 | } 486 | 487 | switch (e.code) { 488 | case "ArrowLeft": 489 | if (this.control) AudioManager.scrub(-20); 490 | else if (AudioManager.getCurrentTime() < 5) { 491 | if (this.confirmedPlayPrevious) { 492 | this.confirmedPlayPrevious = false; 493 | SongManager.playPreviousSong(); 494 | return; 495 | } 496 | else { 497 | this.confirmedPlayPrevious = true; 498 | setTimeout(() => this.confirmedPlayPrevious = false, 2000); 499 | PopupManager.showPopup("Previous?", 2000); 500 | } 501 | } 502 | 503 | if (this.shift) AudioManager.scrub(-1); 504 | else AudioManager.scrub(-5); 505 | return; 506 | case "ArrowRight": 507 | if (this.control) AudioManager.scrub(20); 508 | else if (this.shift) AudioManager.scrub(1); 509 | else AudioManager.scrub(5); 510 | 511 | return; 512 | case "ArrowUp": 513 | SongManager.selectPrevious(); 514 | return; 515 | case "ArrowDown": 516 | SongManager.selectNext(); 517 | return; 518 | case "Space": 519 | AudioManager.toggle(); 520 | return; 521 | case "Enter": 522 | SongManager.playCurrentSongItem(); 523 | return; 524 | case "Home": 525 | PopupManager.showPopup("Start"); 526 | AudioManager.toStart(); 527 | return; 528 | case "End": 529 | PopupManager.showPopup("End"); 530 | AudioManager.toEnd(); 531 | return; 532 | case "PageDown": 533 | PopupManager.showPopup("Next"); 534 | SongManager.next(); 535 | return; 536 | case "PageUp": 537 | PopupManager.showPopup("Previous"); 538 | SongManager.playPreviousSong(); 539 | return; 540 | default: 541 | if (e.key >= 0 && e.key <= 9) { 542 | const index = e.key == 0 ? 10 : (e.key - 1); 543 | AudioManager.setProgress(index / 10); 544 | return; 545 | } 546 | } 547 | 548 | if (this.control) { 549 | switch (e.code) { 550 | case "BracketRight": 551 | AudioManager.changeVolume(true); 552 | return; 553 | case "Slash": 554 | AudioManager.changeVolume(false); 555 | return; 556 | case "KeyA": 557 | if ( 558 | !SearchManager.isActive() || !SearchManager.isSearchSelected() 559 | ) { 560 | e.preventDefault(); 561 | AnimationManager.toggleAnimations(); 562 | } 563 | return; 564 | case "KeyM": 565 | e.preventDefault(); 566 | SeekbarManager.addMarker(); 567 | return; 568 | case "KeyC": 569 | e.preventDefault(); 570 | SeekbarManager.clearMarker(); 571 | return; 572 | case "KeyS": 573 | e.preventDefault(); 574 | SongManager.toggleSortByModifiedDate(); 575 | return; 576 | case "KeyP": 577 | e.preventDefault(); 578 | PlayModeManager.rotatePlayMode(); 579 | return; 580 | case "KeyE": 581 | e.preventDefault(); 582 | ApiManager.rotateEndpoint(); 583 | return; 584 | case "KeyR": 585 | e.preventDefault(); 586 | ApiManager.reloadSongs(); 587 | return; 588 | case "KeyH": 589 | e.preventDefault(); 590 | ThemeManager.rotateTheme(); 591 | return; 592 | } 593 | 594 | return; 595 | } 596 | } 597 | 598 | const eligibleToOpenSearch = (e.keyCode >= 48 && e.keyCode <= 90) || e.keyCode == 226; 599 | if (eligibleToOpenSearch) AudioManager.playTypingAudio(); 600 | 601 | // Enter should not select the search input and instead select the current search result 602 | if (e.code != "Enter") 603 | SearchManager.selectSearchInput(); 604 | 605 | if (SearchManager.isActive()) { 606 | switch (e.code) { 607 | case "ArrowUp": 608 | e.preventDefault(); 609 | SearchManager.selectPrevious(); 610 | return; 611 | case "ArrowDown": 612 | e.preventDefault(); 613 | SearchManager.selectNext(); 614 | return; 615 | case "Enter": 616 | if (SearchManager.isActionInputMode()) 617 | SearchManager.exitActionInputModeAndToggle(); 618 | else 619 | SearchManager.selectCurrentResultItem(); 620 | 621 | return; 622 | case "Escape": 623 | if (SearchManager.isActionInputMode()) 624 | SearchManager.exitActionInputMode(); 625 | else 626 | SearchManager.toggle(); 627 | return; 628 | } 629 | } else { 630 | if (eligibleToOpenSearch) { 631 | SearchManager.toggle(); 632 | SearchManager.searchInput.value = e.key; 633 | SearchManager.updateSearch(); 634 | } 635 | } 636 | 637 | }; 638 | 639 | document.onkeyup = (e) => { 640 | if (e.code == "Space") this.space = false; 641 | if (e.code == "ShiftLeft") this.shift = false; 642 | if (e.code == "ControlLeft") this.control = false; 643 | 644 | if (!ApiManager.isConnected()) return; 645 | 646 | if (!this.control) { 647 | AnimationManager.scaleMain(false); 648 | } 649 | }; 650 | 651 | document.oncontextmenu = (e) => e.preventDefault(); 652 | } 653 | } 654 | 655 | class ApiManager { 656 | static initialize() { 657 | this.apiVersion = 1; 658 | 659 | this.defaultEndpoints = ["https://demomusicapi.osumatrix.me", "http://localhost:3000"]; 660 | this.endpoints = this.loadEndpoints() || this.defaultEndpoints; 661 | this.currentEndpoint = this.getCurrentEndpoint(); 662 | 663 | this.currentEndpointIndex = 0; 664 | 665 | this.sendOption = (method = "POST") => ({ 666 | method, 667 | headers: { 668 | "Content-Type": "application/json", 669 | }, 670 | }); 671 | 672 | Song.setApi(`${this.getApi()}/songs`); 673 | } 674 | 675 | static setAuthorizationToken(token) { 676 | let name = window.location.hostname; 677 | const parts = name.split("."); 678 | if (parts.length > 1) name = parts.slice(-2).join("."); 679 | 680 | document.cookie = `authorization=${token};domain=.${name};max-age=31536000`; 681 | } 682 | 683 | // TODO: Add frontend for this 684 | static saveEndpoints() { 685 | localStorage.setItem("endpoints", JSON.parse(this.endpoints)); 686 | } 687 | 688 | static loadEndpoints() { 689 | const endpoints = localStorage.getItem("endpoints"); 690 | if (endpoints == null) return null; 691 | 692 | this.endpoints = JSON.parse(localStorage.getItem("endpoints")); 693 | } 694 | 695 | // TODO: Add frontend for this 696 | static addEndpoint(endpoint) { 697 | this.endpoints.push(endpoint); 698 | this.saveEndpoints(); 699 | } 700 | 701 | // TODO: Add frontend for this 702 | static resetEndpoints() { 703 | this.endpoints = this.defaultEndpoints; 704 | } 705 | 706 | static rotateEndpoint() { 707 | this.currentEndpointIndex = (this.currentEndpointIndex + 1) % this.endpoints.length; 708 | 709 | this.setAndSaveEndpoint(this.endpoints[this.currentEndpointIndex]); 710 | } 711 | 712 | static setAndSaveEndpoint(endpoint) { 713 | this.setEndpoint(endpoint); 714 | this.saveCurrentEndpoint(); 715 | } 716 | 717 | static getCurrentEndpoint() { 718 | const endpoint = localStorage.getItem("currentEndpoint"); 719 | return endpoint == null ? this.endpoints[0] : endpoint; 720 | } 721 | 722 | static saveCurrentEndpoint() { 723 | localStorage.setItem("currentEndpoint", this.currentEndpoint); 724 | } 725 | 726 | static setEndpoint(endpoint) { 727 | if (this.currentEndpoint == endpoint) return; 728 | this.currentEndpoint = endpoint; 729 | 730 | PopupManager.showPopup(endpoint); 731 | } 732 | 733 | static async reloadSongs() { 734 | PopupManager.showPopup("Reloading"); 735 | 736 | await this.request("/songs/reload", this.sendOption()).catch(() => { }); 737 | 738 | AnimationManager.turnOff(); 739 | setTimeout(() => { 740 | window.location.reload(); 741 | }, 1000); 742 | } 743 | 744 | // TODO: make use of limit and offset 745 | static async querySongs(query, limit = 20, offset = 0) { 746 | const songs = await this.request( 747 | `/songs?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}` 748 | ); 749 | 750 | const ids = []; 751 | for (const song of songs) ids.push(song.id); 752 | 753 | return ids; 754 | } 755 | 756 | // TODO: implement frontend for this 757 | static watchForChanges(watch) { 758 | return this.request( 759 | "/songs/watch" + watch ? "?watch" : "", 760 | this.sendOption() 761 | ); 762 | } 763 | 764 | static async getMarker(id) { 765 | return await this.request(`/songs/${id}/marker`); 766 | } 767 | 768 | static async getRandomSong() { 769 | const json = await this.request(`/songs/random`); 770 | return Song.fromJSON(json); 771 | } 772 | static async getSongs(ids) { 773 | const json = await this.request(`/songs/multiple`, { 774 | ...this.sendOption(), 775 | body: JSON.stringify({ ids }), 776 | }); 777 | 778 | const songs = []; 779 | for (const song of json) { 780 | songs.push(Song.fromJSON(song)); 781 | } 782 | 783 | return songs; 784 | } 785 | 786 | static async getSong(id) { 787 | const json = await this.request(`/songs/${id}`); 788 | return Song.fromJSON(json); 789 | } 790 | 791 | static async getSongIds(offset, sortByModifiedDate) { 792 | const ids = []; 793 | 794 | let api = `/songs/offset/${offset}`; 795 | if (sortByModifiedDate) api += "?sortByModifiedDate"; 796 | 797 | const response = await this.request(api); 798 | response.forEach((song) => ids.push(song.id)); 799 | 800 | return ids; 801 | } 802 | 803 | static async editSongMarker(id, marker) { 804 | return this.request(`/songs/${id}/marker`, { 805 | ...this.sendOption("PATCH"), 806 | body: JSON.stringify({ marker }), 807 | }); 808 | } 809 | 810 | static async ping() { 811 | return this.request("/").then(() => this.connected = true) 812 | } 813 | 814 | static isConnected() { 815 | return this.connected; 816 | } 817 | 818 | static getApi() { 819 | return `${this.currentEndpoint}/api/v${this.apiVersion}`; 820 | } 821 | 822 | static async request(api, options) { 823 | const response = await fetch(`${this.getApi()}${api}`, { 824 | credentials: 'include', 825 | ...options 826 | }); 827 | 828 | if (!response.ok) return Promise.reject(response.status); 829 | 830 | return response.json(); 831 | } 832 | } 833 | 834 | class PlayModeManager { 835 | static initialize() { 836 | this.AUTOPLAY = 0; 837 | this.SHUFFLE = 1; 838 | this.REPEAT = 2; 839 | this.ONCE = 3; 840 | 841 | this.playModes = new Map([ 842 | [this.AUTOPLAY, "Autoplay"], 843 | [this.SHUFFLE, "Shuffle"], 844 | [this.REPEAT, "Repeat"], 845 | [this.ONCE, "Once"], 846 | ]); 847 | 848 | this.currentPlayMode = parseInt(localStorage.getItem("playMode")) || 0; 849 | } 850 | 851 | static getCurrentPlayMode() { 852 | return this.currentPlayMode; 853 | } 854 | 855 | static rotatePlayMode() { 856 | this.currentPlayMode = (this.currentPlayMode + 1) % this.playModes.size; // rotate play mode 857 | 858 | localStorage.setItem("playMode", this.currentPlayMode); 859 | 860 | const playMode = this.playModes.get(this.currentPlayMode); 861 | PopupManager.showPopup(playMode); 862 | } 863 | } 864 | 865 | class SongManager { 866 | static initialize() { 867 | this.history = []; 868 | this.image = $("#image"); 869 | this.songList = $("#song-list"); 870 | this.songItem = $("#song-item-template").content.firstElementChild; 871 | 872 | this.songs = new Map(); 873 | 874 | this.currentSongItem = null; 875 | this.currentSong = null; 876 | 877 | this.offset = 0; 878 | 879 | this.selectPrevNextWaitTime = 100; 880 | 881 | this.sortByModifiedDate = 882 | localStorage.getItem("sortByModifiedDate") || true; 883 | 884 | // handle song playback 885 | this.songList.onclick = (e) => { 886 | if (e.target.classList.contains("song-item")) { 887 | this.setActive(e.target); 888 | this.playSongItem(e.target); 889 | this.scrollToCurrentSongItem(); 890 | } 891 | }; 892 | 893 | this.songList.onscroll = (e) => { 894 | clearTimeout(this.scrollTimeout); 895 | this.scrollTimeout = setTimeout(() => { 896 | if ( 897 | e.target.scrollTop + e.target.clientHeight >= 898 | e.target.scrollHeight - 899 | (e.target.scrollHeight - e.target.scrollTop) / 2 900 | ) 901 | SongManager.getNewSongs(); 902 | }, 5); 903 | }; 904 | 905 | this.image.onclick = () => { 906 | AudioManager.toggle(); 907 | }; 908 | 909 | this.getNewSongs() 910 | } 911 | 912 | static async next() { 913 | switch (PlayModeManager.getCurrentPlayMode()) { 914 | case PlayModeManager.AUTOPLAY: 915 | SongManager.selectNextAndPlay(); 916 | break; 917 | case PlayModeManager.SHUFFLE: 918 | const song = await ApiManager.getRandomSong(); 919 | SongManager.add(song); 920 | SongManager.playSongAndSetActive(song); 921 | break; 922 | case PlayModeManager.REPEAT: 923 | SongManager.playSong(SongManager.getCurrentSong()); 924 | break; 925 | } 926 | } 927 | 928 | static isSortedByModifiedDate() { 929 | return this.sortByModifiedDate; 930 | } 931 | 932 | static async toggleSortByModifiedDate() { 933 | this.sortByModifiedDate = !this.sortByModifiedDate; 934 | localStorage.setItem("sortByModifiedDate", this.sortByModifiedDate); 935 | 936 | this.songList.innerHTML = ""; 937 | this.offset = 0; 938 | 939 | this.songs.clear(); // sadly required, otherwise songs will not be added 940 | 941 | this.getNewSongs().then(() => 942 | PopupManager.showPopup( 943 | "Date " + (this.sortByModifiedDate ? "modified" : "added") 944 | ) 945 | ); 946 | } 947 | 948 | static getImage() { 949 | return this.image; 950 | } 951 | 952 | // TODO: this method adds songs to the song list, when new songs are loaded 953 | // order of songs is not guaranteed, this should be fixed 954 | static async getSongs(ids) { 955 | const songs = []; 956 | 957 | // record ids of songs not in cache 958 | let missingSongs = []; 959 | 960 | // add songs from cache 961 | for (const id of ids) { 962 | if (this.songs.has(id)) songs.push(this.songs.get(id)); 963 | else missingSongs.push(id); 964 | } 965 | 966 | if (missingSongs.length == 0) return songs; 967 | 968 | let newSongs = await ApiManager.getSongs(missingSongs); 969 | 970 | if (this.sortByModifiedDate) 971 | newSongs = newSongs.sort((a, b) => b.modified - a.modified); 972 | 973 | // add newly found songs to cache 974 | for (const song of newSongs) { 975 | this.add(song); 976 | 977 | // merge with songs from cache 978 | songs.push(song); 979 | } 980 | 981 | return songs; 982 | } 983 | 984 | static add(song) { 985 | if (this.songs.has(song.id)) return; 986 | 987 | this.songs.set(song.id, song); 988 | this.addSongToList(song); 989 | } 990 | 991 | static async getNewSongs() { 992 | if (this.offset == -1) return; // no more songs to load (end of list 993 | 994 | const ids = await ApiManager.getSongIds( 995 | this.offset, 996 | this.sortByModifiedDate 997 | ); 998 | 999 | if (ids.length == 0) { 1000 | this.offset = -1; // no more songs to load (end of list) 1001 | return; 1002 | } 1003 | 1004 | this.offset = this.sortByModifiedDate 1005 | ? this.offset + 1 // if sorting by modified date, paginate by 1 1006 | : ids[ids.length - 1] + 1; // otherwise, paginate by last id 1007 | 1008 | const songs = this.getSongs(ids); 1009 | return songs; 1010 | } 1011 | 1012 | static async querySongs(query) { 1013 | const ids = await ApiManager.querySongs(query); 1014 | 1015 | if (ids.length == 0) return []; 1016 | 1017 | const newSongs = this.getSongs(ids); 1018 | return newSongs; 1019 | } 1020 | 1021 | static playPreviousSong() { 1022 | if (this.history.length <= 1) { 1023 | AudioManager.toStart(); 1024 | AudioManager.scrub(-1); 1025 | return; 1026 | } 1027 | 1028 | this.history.pop(); // Remove current song. 1029 | 1030 | this.playSongAndSetActive(this.history.pop()); // Play previous song. 1031 | } 1032 | 1033 | static playSongAndSetActive(song) { 1034 | this.playSong(song); 1035 | this.setActiveById(song.id); 1036 | } 1037 | 1038 | static playSong(song) { 1039 | if (this.history[this.history.length - 1] != song) 1040 | this.history.push(song); 1041 | 1042 | this.currentSong = song; 1043 | this.currentSong.loadMarker(); 1044 | 1045 | this.image.src = this.currentSong.getFullImage(); 1046 | 1047 | AudioManager.setSong(this.currentSong); 1048 | AudioManager.play(); 1049 | 1050 | SeekbarManager.toString(); 1051 | SeekbarManager.showSeekbar(); 1052 | 1053 | document.title = `${song.artist} - ${song.title}`; 1054 | $("link[rel='icon']").href = song.image; 1055 | 1056 | } 1057 | 1058 | static playSongId(id) { 1059 | const song = this.songs.get(parseInt(id)); 1060 | 1061 | this.playSong(song); 1062 | } 1063 | 1064 | static playSongItem(songItem) { 1065 | this.playSongId(songItem.id); 1066 | } 1067 | 1068 | static scrollToCurrentSongItem() { 1069 | this.currentSongItem.scrollIntoView({ 1070 | behavior: "smooth", 1071 | block: "center", 1072 | inline: "center", 1073 | }); 1074 | } 1075 | 1076 | static getCurrentSong() { 1077 | return this.currentSong; 1078 | } 1079 | 1080 | static setActive(songItem) { 1081 | if (this.currentSongItem) 1082 | this.currentSongItem.classList.remove("song-item-active"); 1083 | 1084 | this.currentSongItem = songItem; 1085 | if (songItem) { 1086 | this.currentSongItem.classList.add("song-item-active"); 1087 | this.currentSongItem.scrollIntoViewIfNeeded(true); 1088 | } 1089 | } 1090 | 1091 | static setActiveById(id) { 1092 | const songItem = $("#" + CSS.escape(id), this.songList); 1093 | this.setActive(songItem); 1094 | } 1095 | 1096 | static selectNext() { 1097 | if (Date.now() - this.selectNextTimeout < this.selectPrevNextWaitTime) 1098 | return; 1099 | this.selectNextTimeout = Date.now(); 1100 | 1101 | let next; 1102 | if (this.currentSongItem) { 1103 | next = this.currentSongItem.nextElementSibling; 1104 | 1105 | // if there is no next song, play the first song 1106 | if (!next) next = this.songList.firstElementChild; 1107 | } else { 1108 | next = this.songList.firstElementChild; 1109 | } 1110 | 1111 | this.setActive(next); 1112 | this.scrollToCurrentSongItem(); 1113 | } 1114 | 1115 | static selectNextAndPlay() { 1116 | this.selectNext(); 1117 | this.playCurrentSongItem(); 1118 | } 1119 | 1120 | static selectPrevious() { 1121 | if (Date.now() - this.selectPreviousTimeout < this.selectPrevNextWaitTime) 1122 | return; 1123 | this.selectPreviousTimeout = Date.now(); 1124 | 1125 | let next; 1126 | if (this.currentSongItem) { 1127 | next = this.currentSongItem.previousElementSibling; 1128 | if (!next) next = this.songList.lastElementChild; 1129 | } else { 1130 | next = this.songList.lastElementChild; 1131 | } 1132 | 1133 | this.setActive(next); 1134 | this.scrollToCurrentSongItem(); 1135 | } 1136 | 1137 | static playCurrentSongItem() { 1138 | if (this.currentSongItem) 1139 | this.playSongItem(this.currentSongItem); 1140 | } 1141 | 1142 | static createSongItem(song) { 1143 | const songItem = this.songItem.cloneNode(true); 1144 | 1145 | songItem.id = song.id; 1146 | 1147 | $(".song-title", songItem).innerText = song.title; 1148 | $(".song-artist", songItem).innerText = song.artist; 1149 | $(".song-image", songItem).src = song.image; 1150 | 1151 | return songItem; 1152 | } 1153 | 1154 | static addSongToList(song) { 1155 | const songItem = SongManager.createSongItem(song); 1156 | SongManager.songList.appendChild(songItem); 1157 | } 1158 | } 1159 | 1160 | class AudioManager { 1161 | static initialize() { 1162 | this.imagePaused = false; 1163 | 1164 | this.songAudio = new Audio(); 1165 | 1166 | this.interactionAudio = new Audio("assets/interaction.wav"); 1167 | 1168 | this.keys = [...Array(4)].map((_, i) => new Audio(`assets/key${i}.mp3`)); 1169 | 1170 | this.setVolume(localStorage.getItem("volume") || 50); 1171 | 1172 | this.songAudio.onplay = () => { 1173 | if (this.songAudio.readyState == 0) this.pauseImage(); 1174 | else this.resumeImage(); 1175 | }; 1176 | this.songAudio.onpause = () => this.pauseImage(); 1177 | this.songAudio.onended = async () => { 1178 | this.pauseImage(); 1179 | LastFMManager.resetLast(); 1180 | await SongManager.next(); 1181 | } 1182 | this.songAudio.addEventListener("loadedmetadata", () => this.resumeImage()); 1183 | 1184 | // update seekbar on audio events 1185 | 1186 | this.songAudio.addEventListener("loadedmetadata", () => 1187 | SeekbarManager.setDuration(this.getDuration()) 1188 | ); 1189 | 1190 | const updateSeekbar = () => { 1191 | SeekbarManager.setProgress(this.getCurrentTime() / this.getDuration()); 1192 | 1193 | requestAnimationFrame(updateSeekbar); 1194 | }; 1195 | requestAnimationFrame(updateSeekbar); 1196 | 1197 | const changeVolume = (e) => AudioManager.changeVolume(e.deltaY < 0); 1198 | 1199 | SeekbarManager.getSeekbar().onwheel = changeVolume; 1200 | SongManager.getImage().onwheel = changeVolume; 1201 | } 1202 | 1203 | static toStart() { 1204 | this.setProgress(0); 1205 | } 1206 | 1207 | static toEnd() { 1208 | this.setProgress(1); 1209 | } 1210 | 1211 | static pauseImage() { 1212 | if (this.imagePaused) return; 1213 | 1214 | SongManager.getImage().classList.add("image-paused"); 1215 | 1216 | this.imagePaused = true; 1217 | } 1218 | 1219 | static resumeImage() { 1220 | if (!this.imagePaused) return; 1221 | 1222 | SongManager.getImage().classList.remove("image-paused"); 1223 | 1224 | this.imagePaused = false; 1225 | } 1226 | 1227 | static playInteractionAudio(wait = 0) { 1228 | if (Date.now() - this.lastInteractionAudioPlay < wait) return; 1229 | this.lastInteractionAudioPlay = Date.now(); 1230 | 1231 | this.playAudio(this.interactionAudio); 1232 | } 1233 | 1234 | static playTypingAudio() { 1235 | this.playAudio(this.keys[Math.floor(Math.random() * this.keys.length)], 0.5); 1236 | } 1237 | 1238 | static playAudio(audio, volumeMultiplier = 1) { 1239 | audio.volume = (this.getVolume() / 100) * volumeMultiplier; 1240 | audio.currentTime = 0; 1241 | audio.play(); 1242 | } 1243 | 1244 | static changeVolume(increase = true) { 1245 | let delta; 1246 | 1247 | let currentVolume = AudioManager.getVolume(); 1248 | if (increase) { 1249 | delta = currentVolume < 5 ? 1 : 5; 1250 | } else { 1251 | delta = currentVolume <= 5 ? -1 : -5; 1252 | } 1253 | 1254 | AudioManager.addVolume(delta); 1255 | } 1256 | 1257 | /** 1258 | * @param {Song} song The song to play. 1259 | */ 1260 | static setSong(song) { 1261 | this.songAudio.src = song.file; 1262 | } 1263 | 1264 | static play() { 1265 | if (this.songAudio.src) { 1266 | this.songAudio.play(); 1267 | LastFMManager.updateNowPlaying(SongManager.getCurrentSong()); 1268 | 1269 | // TODO: Properly scrobble by checking if the song has been actually played for 50% or 4 minutes 1270 | this.songAudio.ontimeupdate = () => { 1271 | if (this.songAudio.currentTime < 30) return; 1272 | 1273 | // AudioManager.toEnd() should not trigger scrobble 1274 | if (this.songAudio.currentTime == this.getDuration()) return; 1275 | 1276 | if (this.songAudio.currentTime >= this.songAudio.duration / 2 || this.songAudio.currentTime >= 4 * 60) { 1277 | LastFMManager.scrobble(SongManager.getCurrentSong()); 1278 | this.songAudio.ontimeupdate = null; 1279 | } 1280 | } 1281 | } 1282 | 1283 | else SongManager.selectNextAndPlay(); 1284 | } 1285 | 1286 | static getVolume() { 1287 | return Math.round(this.songAudio.volume * 100); 1288 | } 1289 | 1290 | static addVolume(amount) { 1291 | this.setVolume(this.getVolume() + amount); 1292 | this.playInteractionAudio(); 1293 | 1294 | AudioManager.showVolumePopup(); 1295 | } 1296 | 1297 | static setVolume(volume) { 1298 | if (volume < 0) volume = 0; 1299 | else if (volume > 100) volume = 100; 1300 | 1301 | localStorage.setItem("volume", volume); 1302 | 1303 | this.songAudio.volume = volume / 100; 1304 | } 1305 | 1306 | static showVolumePopup() { 1307 | PopupManager.showPopup(this.getVolume() + "%"); 1308 | } 1309 | 1310 | static pause() { 1311 | this.songAudio.pause(); 1312 | } 1313 | 1314 | static isPaused() { 1315 | return this.songAudio.paused; 1316 | } 1317 | 1318 | static toggle() { 1319 | if (this.isPaused()) { 1320 | this.play(); 1321 | 1322 | if (!SeekbarManager.isMouseOverSeekbar()) SeekbarManager.shrinkSeekbar(); 1323 | } else { 1324 | this.pause(); 1325 | 1326 | SeekbarManager.enlargeSeekbar(); 1327 | } 1328 | } 1329 | 1330 | static getDuration() { 1331 | return this.songAudio.duration || 0; 1332 | } 1333 | 1334 | static getCurrentTime() { 1335 | return this.songAudio.currentTime; 1336 | } 1337 | 1338 | /** 1339 | * @param {number} progress The progress in the range [0, 1]. 1340 | */ 1341 | static setProgress(progress) { 1342 | this.songAudio.currentTime = this.getDuration() * progress; 1343 | } 1344 | 1345 | static scrub(seconds) { 1346 | // prevent glitching sound by pausing and playing the audio after scrubbing stops 1347 | this.pause(); 1348 | 1349 | clearTimeout(this.scrubTimeout); 1350 | this.scrubTimeout = setTimeout(() => this.play(), 100); 1351 | 1352 | this.songAudio.currentTime += seconds; 1353 | } 1354 | } 1355 | 1356 | class LastFMManager { 1357 | static initialize() { 1358 | this.apiKey = localStorage.getItem("lastfm-api-key") 1359 | this.apiSecret = localStorage.getItem("lastfm-api-secret") 1360 | this.session = JSON.parse(localStorage.getItem("lastfm-session")) 1361 | 1362 | this.lastfm = new LastFM({ 1363 | cache: new LastFMCache(), 1364 | apiKey: this.apiKey, 1365 | apiSecret: this.apiSecret, 1366 | }); 1367 | 1368 | if (this.session) this.authed = true; 1369 | } 1370 | 1371 | static auth(apiKey, apiSecret) { 1372 | if (apiKey) { 1373 | this.lastfm.setApiKey(apiKey); 1374 | localStorage.setItem("lastfm-api-key", apiKey); 1375 | this.apiKey = apiKey; 1376 | } 1377 | if (apiSecret) { 1378 | this.lastfm.setApiSecret(apiSecret); 1379 | localStorage.setItem("lastfm-api-secret", apiSecret); 1380 | this.apiSecret = apiSecret; 1381 | } 1382 | 1383 | this.lastfm.auth.getToken({ 1384 | success: (data) => { 1385 | window.open(`https://www.last.fm/api/auth?api_key=${this.apiKey}&token=${data.token}`, "_blank"); 1386 | localStorage.setItem("lastfm-token", data.token); 1387 | 1388 | var attemptsLeft = 10; 1389 | clearInterval(this.authAttempt); 1390 | this.authAttempt = setInterval(() => { 1391 | this.lastfm.auth.getSession({ 1392 | token: data.token, 1393 | }, { 1394 | success: (data) => { 1395 | localStorage.setItem("lastfm-session", JSON.stringify(data.session)); 1396 | this.session = data.session; 1397 | PopupManager.showPopup("Last.FM authenticated", 2000); 1398 | this.authed = true; 1399 | clearInterval(this.authAttempt); 1400 | } 1401 | }) 1402 | 1403 | if (attemptsLeft-- == 0) { 1404 | this.warnNotAuthed(); 1405 | clearInterval(this.authAttempt); 1406 | } 1407 | }, 5000); 1408 | } 1409 | }) 1410 | } 1411 | 1412 | static updateNowPlaying(song) { 1413 | if (!this.authed) return this.warnNotAuthed(); 1414 | 1415 | if (this.lastPlaying == song) return; 1416 | this.lastPlaying = song; 1417 | 1418 | this.lastfm.track.updateNowPlaying({ artist: song.artist, track: song.title }, this.session); 1419 | this.timestamp = Math.floor(Date.now() / 1000); 1420 | } 1421 | 1422 | static resetLast() { 1423 | this.lastScrobble = null; 1424 | this.lastPlaying = null; 1425 | } 1426 | 1427 | static scrobble(song) { 1428 | if (!this.authed) return this.warnNotAuthed(); 1429 | 1430 | if (this.lastScrobble == song) return; 1431 | this.lastScrobble = song; 1432 | 1433 | this.lastfm.track.scrobble({ artist: song.artist, track: song.title, timestamp: this.timestamp }, this.session); 1434 | } 1435 | 1436 | static warnNotAuthed() { 1437 | if (this.showedWarning) return; 1438 | PopupManager.showPopup("Last.FM not authenticated", 2000); 1439 | this.showedWarning = true; 1440 | } 1441 | } 1442 | 1443 | class ActionManager { 1444 | static initialize() { 1445 | this.actions = [ 1446 | new Action("Play", () => AudioManager.play(), Action.ACTION, "Play the current song"), 1447 | new Action("Pause", () => AudioManager.pause(), Action.ACTION, "Pause the current song"), 1448 | new Action("Endpoint", (a) => ApiManager.setAndSaveEndpoint(a.value), Action.INPUT, () => ApiManager.getCurrentEndpoint()), 1449 | new Action("Animations", () => AnimationManager.toggleAnimations(), Action.TOGGLE, () => AnimationManager.isAnimationsEnabled() ? Action.TOGGLE_ON : Action.TOGGLE_OFF), 1450 | new Action("Auth", (a) => ApiManager.setAuthorizationToken(a.value), Action.INPUT, Action.HIDDEN), 1451 | new Action("Theme", (a) => ThemeManager.setTheme(a.value), Action.INPUT, () => ThemeManager.getTheme()), 1452 | new Action("Last.FM (Input format: )", (a) => { 1453 | const [apiKey, apiSecret] = a.value.split(" "); 1454 | LastFMManager.auth(apiKey, apiSecret); 1455 | }, Action.INPUT, Action.HIDDEN), 1456 | ]; 1457 | 1458 | this.actionsByName = new Map(); 1459 | this.actions.forEach((action) => this.actionsByName.set(action.name, action)); 1460 | } 1461 | 1462 | static queryActions(query) { 1463 | query = query.toLowerCase(); 1464 | 1465 | const actions = []; 1466 | 1467 | this.actions.forEach((action) => { 1468 | if (action.name.toLowerCase().includes(query)) { 1469 | action.updateValue(); 1470 | actions.push(action); 1471 | } 1472 | }); 1473 | 1474 | return actions; 1475 | } 1476 | 1477 | static getAction(name) { 1478 | return this.actionsByName.get(name); 1479 | } 1480 | 1481 | static updateActionInput(action, value) { 1482 | action.value = value; 1483 | } 1484 | 1485 | 1486 | save(action) { 1487 | localStorage.setItem(`action-${action.name}`, action.value); 1488 | } 1489 | 1490 | restore(action) { 1491 | action.value = localStorage.getItem(`action-${action.name}`); 1492 | } 1493 | } 1494 | 1495 | class SearchManager { 1496 | static initialize() { 1497 | this.searchInputIsSelected = false; 1498 | this.visible = false; 1499 | this.search = $("#search-main"); 1500 | this.searchContainer = $("#search-container", this.search); 1501 | this.searchInput = $("#search-input", this.search); 1502 | 1503 | this.results = $("#search-results"); 1504 | this.songResultItem = $("#search-result-song-item-template").content.firstElementChild; 1505 | this.actionResultItem = $("#search-result-action-item-template").content.firstElementChild; 1506 | this.currentResultItem = null; 1507 | 1508 | this.searchInput.onfocus = () => (this.searchInputIsSelected = true); 1509 | this.searchInput.onblur = () => (this.searchInputIsSelected = false); 1510 | 1511 | this.actionInputMode = false 1512 | 1513 | this.results.onclick = (e) => { 1514 | if (e.target == this.results) return; 1515 | 1516 | if (SearchManager.isActionInputMode()) 1517 | SearchManager.exitActionInputModeAndToggle(); 1518 | else 1519 | this.selectItem(e.target); 1520 | }; 1521 | 1522 | this.search.onclick = (e) => { 1523 | if (e.target != this.search && e.target != this.searchContainer) return; 1524 | SearchManager.toggle(); 1525 | }; 1526 | 1527 | this.searchInput.addEventListener("input", this.updateSearch); 1528 | } 1529 | 1530 | static enterActionInputMode(action) { 1531 | this.actionInputMode = true; 1532 | this.currentAction = action; 1533 | this.lastSearchInputValue = this.searchInput.value; 1534 | 1535 | this.clearSearchInput(); 1536 | this.selectSearchInput(); 1537 | 1538 | if (action.value != Action.HIDDEN) 1539 | this.searchInput.value = action.value; 1540 | } 1541 | 1542 | static exitActionInputModeAndToggle() { 1543 | SearchManager.toggle(); 1544 | } 1545 | 1546 | static exitActionInputMode(select = false) { 1547 | if (!this.isActionInputMode()) return; 1548 | 1549 | if (select) 1550 | this.currentAction.select(); 1551 | this.actionInputMode = false; 1552 | this.currentAction = null; 1553 | this.searchInput.value = this.lastSearchInputValue; 1554 | } 1555 | 1556 | 1557 | static isActionInputMode() { 1558 | return this.actionInputMode; 1559 | } 1560 | 1561 | static updateSearch() { 1562 | if (SearchManager.isActionInputMode()) { 1563 | ActionManager.updateActionInput(SearchManager.currentAction, SearchManager.searchInput.value); 1564 | SearchManager.updateCurrentActionResultItemValue(); 1565 | return; 1566 | } 1567 | // prevent searching for empty string 1568 | if (SearchManager.searchInput.value.length == 0) { 1569 | clearTimeout(this.searchTimeout); 1570 | SearchManager.clearResults(); 1571 | return; 1572 | } 1573 | 1574 | if (SearchManager.searchInput.value.startsWith(">")) { 1575 | SearchManager.clearResults(); 1576 | 1577 | ActionManager 1578 | .queryActions(SearchManager.searchInput.value.slice(1)) 1579 | .forEach((action) => { 1580 | SearchManager.addActionResult(action); 1581 | }); 1582 | 1583 | SearchManager.selectNext(); 1584 | } else { 1585 | 1586 | clearTimeout(this.searchTimeout); 1587 | this.searchTimeout = setTimeout(() => { 1588 | SongManager.querySongs(SearchManager.searchInput.value).then((found) => { 1589 | SearchManager.clearResults(); 1590 | 1591 | if (SongManager.isSortedByModifiedDate()) { 1592 | found = found.sort((a, b) => b.modified - a.modified); 1593 | } 1594 | found.forEach((song) => SearchManager.addSongResult(song)); 1595 | 1596 | SearchManager.selectNext(); 1597 | }); 1598 | }, 200); 1599 | } 1600 | } 1601 | 1602 | static selectItem(item) { 1603 | if (item.classList.contains("action")) { 1604 | this.selectAction(item.name); 1605 | this.setActive(item); 1606 | } else 1607 | this.playResult(item); 1608 | } 1609 | 1610 | static selectCurrentResultItem() { 1611 | this.selectItem(this.currentResultItem); 1612 | } 1613 | 1614 | static updateCurrentActionResultItemValue() { 1615 | $(".search-result-action-value", this.currentResultItem).innerText = SearchManager.searchInput.value; 1616 | } 1617 | 1618 | static selectAction(name) { 1619 | const action = ActionManager.getAction(name); 1620 | 1621 | switch (action.type) { 1622 | case Action.INPUT: 1623 | this.enterActionInputMode(action); 1624 | break; 1625 | default: 1626 | action.select(); 1627 | SearchManager.toggle(); 1628 | } 1629 | } 1630 | 1631 | static playResult(resultItem) { 1632 | // Unset song from song list, otherwise we need to search for it. 1633 | SongManager.setActiveById(resultItem.id); 1634 | SongManager.playSongId(resultItem.id); 1635 | SearchManager.toggle(); 1636 | } 1637 | 1638 | static setActive(resultItem) { 1639 | if (resultItem) this.unselectSearchInput(); 1640 | else this.selectSearchInput(); 1641 | 1642 | if (this.currentResultItem) 1643 | this.currentResultItem.classList.remove("search-result-item-active"); 1644 | 1645 | if (resultItem) resultItem.classList.add("search-result-item-active"); 1646 | 1647 | this.currentResultItem = resultItem; 1648 | 1649 | this.currentResultItem?.scrollIntoView({ 1650 | behavior: "smooth", 1651 | block: "center", 1652 | }); 1653 | } 1654 | 1655 | static selectSearchInput() { 1656 | this.searchInput.focus(); 1657 | } 1658 | 1659 | static unselectSearchInput() { 1660 | this.searchInput.blur(); 1661 | } 1662 | 1663 | static selectNext() { 1664 | this.exitActionInputMode() 1665 | 1666 | let next; 1667 | if (this.currentResultItem) { 1668 | next = this.currentResultItem.nextElementSibling; 1669 | 1670 | if (!next) { 1671 | this.setActive(null); 1672 | return; 1673 | } 1674 | } else next = this.results.firstElementChild; 1675 | 1676 | this.setActive(next); 1677 | } 1678 | 1679 | static selectPrevious() { 1680 | this.exitActionInputMode() 1681 | 1682 | let next; 1683 | if (this.currentResultItem) { 1684 | next = this.currentResultItem.previousElementSibling; 1685 | 1686 | if (!next) { 1687 | this.setActive(null); 1688 | return; 1689 | } 1690 | } else next = this.results.lastElementChild; 1691 | 1692 | this.setActive(next); 1693 | } 1694 | static addActionResult(action) { 1695 | const resultItem = this.actionResultItem.cloneNode(true); 1696 | 1697 | resultItem.name = action.name; 1698 | 1699 | $(".search-result-action-name", resultItem).innerText = action.name; 1700 | $(".search-result-action-value", resultItem).innerText = action.value == Action.HIDDEN ? "Hidden" : action.value; 1701 | 1702 | this.results.appendChild(resultItem); 1703 | } 1704 | 1705 | static addSongResult(song) { 1706 | const resultItem = this.songResultItem.cloneNode(true); 1707 | 1708 | resultItem.id = song.id; 1709 | 1710 | $(".search-result-song-image", resultItem).src = song.image; 1711 | $(".search-result-song-title", resultItem).innerText = song.title; 1712 | $(".search-result-song-artist", resultItem).innerText = song.artist; 1713 | 1714 | this.results.appendChild(resultItem); 1715 | } 1716 | 1717 | static clearResults() { 1718 | this.currentResultItem = null; 1719 | this.results.innerHTML = ""; 1720 | } 1721 | 1722 | static isSearchSelected() { 1723 | return this.searchInputIsSelected; 1724 | } 1725 | 1726 | static isActive() { 1727 | return this.visible; 1728 | } 1729 | 1730 | static toggle() { 1731 | if (this.visible) { 1732 | this.search.classList.remove("search-active"); 1733 | this.exitActionInputMode(true) 1734 | 1735 | // wait for animation to finish 1736 | setTimeout(() => { 1737 | this.clearSearchInput(); 1738 | this.clearResults(); 1739 | }, 100); 1740 | } else { 1741 | this.search.classList.add("search-active"); 1742 | } 1743 | 1744 | this.visible = !this.visible; 1745 | } 1746 | 1747 | static clearSearchInput() { 1748 | this.searchInput.value = ""; 1749 | } 1750 | } 1751 | 1752 | class AnimationManager { 1753 | static initialize() { 1754 | this.main = $("#main"); 1755 | this.animationsEnabled = localStorage.getItem("animations") === "true"; 1756 | if (this.animationsEnabled == null) this.animationsEnabled = true; 1757 | this.image = $("#image"); 1758 | this.breathingAnimationInterval = null; 1759 | 1760 | this.animateImage = (x, y) => image.style.transform = `perspective(600px) translate(${x * 16}px, ${y * 16}px) rotateX(${-y}deg) rotateY(${x}deg) rotate(${x * y * 0.8}deg)`; 1761 | 1762 | let time = 0; 1763 | this.breathingAnimation = () => { 1764 | if (this.isMouseOnImage || AudioManager.isPaused()) return; 1765 | 1766 | time += 0.2; 1767 | 1768 | this.animateImage( 1769 | Math.sin(time) * 0.5, 1770 | Math.cos(time / 2) * 0.5 1771 | ); 1772 | }; 1773 | 1774 | this.imageOnMouseMove = (e) => { 1775 | if (e.timeStamp - this.lastMouseMoveCall < 100) return; 1776 | this.lastMouseMoveCall = e.timeStamp; 1777 | 1778 | const imagePosition = image.getBoundingClientRect(); 1779 | 1780 | const absoluteMouseX = e.pageX - imagePosition.left 1781 | const relativeMouseX = absoluteMouseX / imagePosition.width 1782 | const normalizedMouseX = (relativeMouseX - 0.5) * 2 1783 | 1784 | const absoluteMouseY = e.pageY - imagePosition.top 1785 | const relativeMouseY = absoluteMouseY / imagePosition.height 1786 | const normalizedMouseY = (relativeMouseY - 0.5) * 2 1787 | 1788 | this.animateImage(normalizedMouseX, normalizedMouseY); 1789 | }; 1790 | 1791 | this.imageOnMouseOut = () => { 1792 | image.style.transform = "translate(0px, 0px)"; 1793 | }; 1794 | 1795 | this.imageOnMouseMoveTouch = (e) => this.imageOnMouseMove(this.transformTouchEvent(e)); 1796 | this.imageOnMouseMoveOutTouch = (e) => this.imageOnMouseOut(this.transformTouchEvent(e)); 1797 | 1798 | const setMouseOnImageTrue = () => (this.isMouseOnImage = true); 1799 | const setMouseOnImageFalse = () => (this.isMouseOnImage = false); 1800 | 1801 | this.isTouchDevice = "ontouchstart" in window; 1802 | 1803 | if (this.isTouchDevice) { 1804 | this.image.addEventListener("touchstart", setMouseOnImageTrue); 1805 | this.image.addEventListener("touchend", setMouseOnImageFalse); 1806 | } else { 1807 | image.onmouseenter = setMouseOnImageTrue 1808 | image.onmouseleave = setMouseOnImageFalse 1809 | } 1810 | 1811 | if (this.animationsEnabled) this.start(); 1812 | } 1813 | 1814 | static turnOff() { 1815 | document.body.style.opacity = 0; 1816 | } 1817 | 1818 | static scaleMain(fade) { 1819 | if (fade) { 1820 | this.main.style.scale = 0.99; 1821 | } 1822 | else { 1823 | this.main.style.scale = 1; 1824 | } 1825 | } 1826 | 1827 | static stop() { 1828 | this.imageOnMouseOut(); 1829 | 1830 | if (this.isTouchDevice) { 1831 | this.image.removeEventListener("touchmove", this.imageOnMouseMoveTouch); 1832 | this.image.removeEventListener("touchend", this.imageOnMouseMoveOutTouch); 1833 | } else { 1834 | this.image.onmousemove = null; 1835 | this.image.onmouseout = null; 1836 | } 1837 | 1838 | clearInterval(this.breathingAnimationInterval); 1839 | } 1840 | 1841 | static transformTouchEvent(e) { 1842 | const changedTouches = e.changedTouches[0]; 1843 | 1844 | return { 1845 | pageX: changedTouches.pageX, 1846 | pageY: changedTouches.pageY, 1847 | timeStamp: e.timeStamp 1848 | } 1849 | } 1850 | 1851 | static start() { 1852 | this.stop(); 1853 | 1854 | if (this.isTouchDevice) { 1855 | this.image.ontouchmove = this.imageOnMouseMoveTouch; 1856 | this.image.addEventListener("touchend", this.imageOnMouseMoveOutTouch); 1857 | } else { 1858 | this.image.onmousemove = this.imageOnMouseMove; 1859 | this.image.onmouseout = this.imageOnMouseOut; 1860 | } 1861 | this.breathingAnimationInterval = setInterval( 1862 | this.breathingAnimation, 1863 | 1000 / 4 1864 | ); 1865 | } 1866 | 1867 | static isAnimationsEnabled() { 1868 | return this.animationsEnabled; 1869 | } 1870 | 1871 | static toggleAnimations() { 1872 | if (this.animationsEnabled = !this.animationsEnabled) this.start(); 1873 | else this.stop(); 1874 | 1875 | PopupManager.showPopup( 1876 | "Animations " + (this.isAnimationsEnabled() ? "enabled" : "disabled") 1877 | ); 1878 | 1879 | if (this.isAnimationsEnabled()) { 1880 | this.start(); 1881 | } else { 1882 | this.stop(); 1883 | } 1884 | 1885 | localStorage.setItem("animations", this.isAnimationsEnabled()); 1886 | } 1887 | } 1888 | 1889 | const initialize = (managers) => managers.forEach((manager) => manager.initialize()); 1890 | 1891 | ApiManager.initialize(); 1892 | ApiManager.ping().then(() => 1893 | initialize([ 1894 | PopupManager, 1895 | LastFMManager, 1896 | SeekbarManager, 1897 | SongManager, 1898 | AudioManager, 1899 | EventManager, 1900 | ActionManager, 1901 | PlayModeManager, 1902 | SearchManager, 1903 | AnimationManager, 1904 | ThemeManager, 1905 | ]) 1906 | ).catch((e) => { 1907 | console.log(e) 1908 | 1909 | // Minimum initialization after failure to connect to the API. 1910 | initialize([ 1911 | EventManager, 1912 | PopupManager, 1913 | ]); 1914 | 1915 | PopupManager.showPopup("Disconnected", PopupManager.PERMANENT); 1916 | }) 1917 | -------------------------------------------------------------------------------- /static/scripts/lastfm.api.cache.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright (c) 2008-2009, Felix Bruns 4 | * 5 | */ 6 | 7 | /* Set an object on a Storage object. */ 8 | Storage.prototype.setObject = function(key, value){ 9 | this.setItem(key, JSON.stringify(value)); 10 | } 11 | 12 | /* Get an object from a Storage object. */ 13 | Storage.prototype.getObject = function(key){ 14 | var item = this.getItem(key); 15 | 16 | return JSON.parse(item); 17 | } 18 | 19 | /* Creates a new cache object. */ 20 | function LastFMCache(){ 21 | /* Expiration times. */ 22 | var MINUTE = 60; 23 | var HOUR = MINUTE * 60; 24 | var DAY = HOUR * 24; 25 | var WEEK = DAY * 7; 26 | var MONTH = WEEK * 4.34812141; 27 | var YEAR = MONTH * 12; 28 | 29 | /* Methods with weekly expiration. */ 30 | var weeklyMethods = [ 31 | 'artist.getSimilar', 32 | 'tag.getSimilar', 33 | 'track.getSimilar', 34 | 'artist.getTopAlbums', 35 | 'artist.getTopTracks', 36 | 'geo.getTopArtists', 37 | 'geo.getTopTracks', 38 | 'tag.getTopAlbums', 39 | 'tag.getTopArtists', 40 | 'tag.getTopTags', 41 | 'tag.getTopTracks', 42 | 'user.getTopAlbums', 43 | 'user.getTopArtists', 44 | 'user.getTopTags', 45 | 'user.getTopTracks' 46 | ]; 47 | 48 | /* Name for this cache. */ 49 | var name = 'lastfm'; 50 | 51 | /* Create cache if it doesn't exist yet. */ 52 | if(localStorage.getObject(name) == null){ 53 | localStorage.setObject(name, {}); 54 | } 55 | 56 | /* Get expiration time for given parameters. */ 57 | this.getExpirationTime = function(params){ 58 | var method = params.method; 59 | 60 | if((/Weekly/).test(method) && !(/List/).test(method)){ 61 | if(typeof(params.to) != 'undefined' && typeof(params.from) != 'undefined'){ 62 | return YEAR; 63 | } 64 | else{ 65 | return WEEK; 66 | } 67 | } 68 | 69 | for(var key in weeklyMethods){ 70 | if(method == weeklyMethods[key]){ 71 | return WEEK; 72 | } 73 | } 74 | 75 | return -1; 76 | }; 77 | 78 | /* Check if this cache contains specific data. */ 79 | this.contains = function(hash){ 80 | return typeof(localStorage.getObject(name)[hash]) != 'undefined' && 81 | typeof(localStorage.getObject(name)[hash].data) != 'undefined'; 82 | }; 83 | 84 | /* Load data from this cache. */ 85 | this.load = function(hash){ 86 | return localStorage.getObject(name)[hash].data; 87 | }; 88 | 89 | /* Remove data from this cache. */ 90 | this.remove = function(hash){ 91 | var object = localStorage.getObject(name); 92 | 93 | object[hash] = undefined; 94 | 95 | localStorage.setObject(name, object); 96 | }; 97 | 98 | /* Store data in this cache with a given expiration time. */ 99 | this.store = function(hash, data, expiration){ 100 | var object = localStorage.getObject(name); 101 | var time = Math.round(new Date().getTime() / 1000); 102 | 103 | object[hash] = { 104 | data : data, 105 | expiration : time + expiration 106 | }; 107 | 108 | localStorage.setObject(name, object); 109 | }; 110 | 111 | /* Check if some specific data expired. */ 112 | this.isExpired = function(hash){ 113 | var object = localStorage.getObject(name); 114 | var time = Math.round(new Date().getTime() / 1000); 115 | 116 | if(time > object[hash].expiration){ 117 | return true; 118 | } 119 | 120 | return false; 121 | }; 122 | 123 | /* Clear this cache. */ 124 | this.clear = function(){ 125 | localStorage.setObject(name, {}); 126 | }; 127 | }; 128 | -------------------------------------------------------------------------------- /static/scripts/lastfm.api.js: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Copyright (c) 2008-2010, Felix Bruns 4 | * 5 | */ 6 | 7 | function LastFM(options) { 8 | /* Set default values for required options. */ 9 | var apiKey = options.apiKey || ''; 10 | var apiSecret = options.apiSecret || ''; 11 | var apiUrl = options.apiUrl || 'https://ws.audioscrobbler.com/2.0/'; 12 | var cache = options.cache || undefined; 13 | 14 | /* Set API key. */ 15 | this.setApiKey = function (_apiKey) { 16 | apiKey = _apiKey; 17 | }; 18 | 19 | /* Set API key. */ 20 | this.setApiSecret = function (_apiSecret) { 21 | apiSecret = _apiSecret; 22 | }; 23 | 24 | /* Set API URL. */ 25 | this.setApiUrl = function (_apiUrl) { 26 | apiUrl = _apiUrl; 27 | }; 28 | 29 | /* Set cache. */ 30 | this.setCache = function (_cache) { 31 | cache = _cache; 32 | }; 33 | 34 | /* Set the JSONP callback identifier counter. This is used to ensure the callbacks are unique */ 35 | var jsonpCounter = 0; 36 | 37 | /* Internal call (POST, GET). */ 38 | var internalCall = function (params, callbacks, requestMethod) { 39 | /* Cross-domain POST request (doesn't return any data, always successful). */ 40 | if (requestMethod == 'POST') { 41 | /* Create iframe element to post data. */ 42 | var html = document.getElementsByTagName('html')[0]; 43 | var iframe = document.createElement('iframe'); 44 | var doc; 45 | 46 | /* Set iframe attributes. */ 47 | iframe.width = 1; 48 | iframe.height = 1; 49 | iframe.style.border = 'none'; 50 | 51 | /* Append iframe. */ 52 | html.appendChild(iframe); 53 | iframe.onload = function () { 54 | /* Remove iframe element. */ 55 | html.removeChild(iframe); 56 | 57 | /* Call user callback. */ 58 | if (typeof (callbacks.success) != 'undefined') { 59 | callbacks.success(); 60 | } 61 | }; 62 | 63 | /* Get iframe document. */ 64 | if (typeof (iframe.contentWindow) != 'undefined') { 65 | doc = iframe.contentWindow.document; 66 | } 67 | else if (typeof (iframe.contentDocument.document) != 'undefined') { 68 | doc = iframe.contentDocument.document.document; 69 | } 70 | else { 71 | doc = iframe.contentDocument.document; 72 | } 73 | 74 | /* Open iframe document and write a form. */ 75 | doc.open(); 76 | doc.clear(); 77 | doc.write('
'); 78 | 79 | /* Write POST parameters as input fields. */ 80 | for (var param in params) { 81 | doc.write(''); 82 | } 83 | 84 | /* Write automatic form submission code. */ 85 | doc.write('
'); 86 | doc.write(''); 89 | 90 | /* Close iframe document. */ 91 | doc.close(); 92 | } 93 | /* Cross-domain GET request (JSONP). */ 94 | else { 95 | /* Get JSONP callback name. */ 96 | var jsonp = 'jsonp' + new Date().getTime() + jsonpCounter; 97 | 98 | /* Update the unique JSONP callback counter */ 99 | jsonpCounter += 1; 100 | 101 | /* Calculate cache hash. */ 102 | var hash = auth.getApiSignature(params); 103 | 104 | /* Check cache. */ 105 | if (typeof (cache) != 'undefined' && cache.contains(hash) && !cache.isExpired(hash)) { 106 | if (typeof (callbacks.success) != 'undefined') { 107 | callbacks.success(cache.load(hash)); 108 | } 109 | 110 | return; 111 | } 112 | 113 | /* Set callback name and response format. */ 114 | params.callback = jsonp; 115 | params.format = 'json'; 116 | 117 | /* Create JSONP callback function. */ 118 | window[jsonp] = function (data) { 119 | /* Is a cache available?. */ 120 | if (typeof (cache) != 'undefined') { 121 | var expiration = cache.getExpirationTime(params); 122 | 123 | if (expiration > 0) { 124 | cache.store(hash, data, expiration); 125 | } 126 | } 127 | 128 | /* Call user callback. */ 129 | if (typeof (data.error) != 'undefined') { 130 | if (typeof (callbacks.error) != 'undefined') { 131 | callbacks.error(data.error, data.message); 132 | } 133 | } 134 | else if (typeof (callbacks.success) != 'undefined') { 135 | callbacks.success(data); 136 | } 137 | 138 | /* Garbage collect. */ 139 | window[jsonp] = undefined; 140 | 141 | try { 142 | delete window[jsonp]; 143 | } 144 | catch (e) { 145 | /* Nothing. */ 146 | } 147 | 148 | /* Remove script element. */ 149 | if (head) { 150 | head.removeChild(script); 151 | } 152 | }; 153 | 154 | /* Create script element to load JSON data. */ 155 | var head = document.getElementsByTagName("head")[0]; 156 | var script = document.createElement("script"); 157 | 158 | /* Build parameter string. */ 159 | var array = []; 160 | 161 | for (var param in params) { 162 | array.push(encodeURIComponent(param) + "=" + encodeURIComponent(params[param])); 163 | } 164 | 165 | /* Set script source. */ 166 | script.src = apiUrl + '?' + array.join('&').replace(/%20/g, '+'); 167 | 168 | /* Append script element. */ 169 | head.appendChild(script); 170 | } 171 | }; 172 | 173 | /* Normal method call. */ 174 | var call = function (method, params, callbacks, requestMethod) { 175 | /* Set default values. */ 176 | params = params || {}; 177 | callbacks = callbacks || {}; 178 | requestMethod = requestMethod || 'GET'; 179 | 180 | /* Add parameters. */ 181 | params.method = method; 182 | params.api_key = apiKey; 183 | 184 | /* Call method. */ 185 | internalCall(params, callbacks, requestMethod); 186 | }; 187 | 188 | /* Signed method call. */ 189 | var signedCall = function (method, params, session, callbacks, requestMethod) { 190 | /* Set default values. */ 191 | params = params || {}; 192 | callbacks = callbacks || {}; 193 | requestMethod = requestMethod || 'GET'; 194 | 195 | /* Add parameters. */ 196 | params.method = method; 197 | params.api_key = apiKey; 198 | 199 | /* Add session key. */ 200 | if (session && typeof (session.key) != 'undefined') { 201 | params.sk = session.key; 202 | } 203 | 204 | /* Get API signature. */ 205 | params.api_sig = auth.getApiSignature(params); 206 | 207 | /* Call method. */ 208 | internalCall(params, callbacks, requestMethod); 209 | }; 210 | 211 | /* Album methods. */ 212 | this.album = { 213 | addTags: function (params, session, callbacks) { 214 | /* Build comma separated tags string. */ 215 | if (typeof (params.tags) == 'object') { 216 | params.tags = params.tags.join(','); 217 | } 218 | 219 | signedCall('album.addTags', params, session, callbacks, 'POST'); 220 | }, 221 | 222 | getBuylinks: function (params, callbacks) { 223 | call('album.getBuylinks', params, callbacks); 224 | }, 225 | 226 | getInfo: function (params, callbacks) { 227 | call('album.getInfo', params, callbacks); 228 | }, 229 | 230 | getTags: function (params, session, callbacks) { 231 | signedCall('album.getTags', params, session, callbacks); 232 | }, 233 | 234 | getTopTags: function (params, callbacks) { 235 | signedCall('album.getTopTags', params, callbacks); 236 | }, 237 | 238 | removeTag: function (params, session, callbacks) { 239 | signedCall('album.removeTag', params, session, callbacks, 'POST'); 240 | }, 241 | 242 | search: function (params, callbacks) { 243 | call('album.search', params, callbacks); 244 | }, 245 | 246 | share: function (params, session, callbacks) { 247 | /* Build comma separated recipients string. */ 248 | if (typeof (params.recipient) == 'object') { 249 | params.recipient = params.recipient.join(','); 250 | } 251 | 252 | signedCall('album.share', params, callbacks); 253 | } 254 | }; 255 | 256 | /* Artist methods. */ 257 | this.artist = { 258 | addTags: function (params, session, callbacks) { 259 | /* Build comma separated tags string. */ 260 | if (typeof (params.tags) == 'object') { 261 | params.tags = params.tags.join(','); 262 | } 263 | 264 | signedCall('artist.addTags', params, session, callbacks, 'POST'); 265 | }, 266 | 267 | getCorrection: function (params, callbacks) { 268 | call('artist.getCorrection', params, callbacks); 269 | }, 270 | 271 | getEvents: function (params, callbacks) { 272 | call('artist.getEvents', params, callbacks); 273 | }, 274 | 275 | getImages: function (params, callbacks) { 276 | call('artist.getImages', params, callbacks); 277 | }, 278 | 279 | getInfo: function (params, callbacks) { 280 | call('artist.getInfo', params, callbacks); 281 | }, 282 | 283 | getPastEvents: function (params, callbacks) { 284 | call('artist.getPastEvents', params, callbacks); 285 | }, 286 | 287 | getPodcast: function (params, callbacks) { 288 | call('artist.getPodcast', params, callbacks); 289 | }, 290 | 291 | getShouts: function (params, callbacks) { 292 | call('artist.getShouts', params, callbacks); 293 | }, 294 | 295 | getSimilar: function (params, callbacks) { 296 | call('artist.getSimilar', params, callbacks); 297 | }, 298 | 299 | getTags: function (params, session, callbacks) { 300 | signedCall('artist.getTags', params, session, callbacks); 301 | }, 302 | 303 | getTopAlbums: function (params, callbacks) { 304 | call('artist.getTopAlbums', params, callbacks); 305 | }, 306 | 307 | getTopFans: function (params, callbacks) { 308 | call('artist.getTopFans', params, callbacks); 309 | }, 310 | 311 | getTopTags: function (params, callbacks) { 312 | call('artist.getTopTags', params, callbacks); 313 | }, 314 | 315 | getTopTracks: function (params, callbacks) { 316 | call('artist.getTopTracks', params, callbacks); 317 | }, 318 | 319 | removeTag: function (params, session, callbacks) { 320 | signedCall('artist.removeTag', params, session, callbacks, 'POST'); 321 | }, 322 | 323 | search: function (params, callbacks) { 324 | call('artist.search', params, callbacks); 325 | }, 326 | 327 | share: function (params, session, callbacks) { 328 | /* Build comma separated recipients string. */ 329 | if (typeof (params.recipient) == 'object') { 330 | params.recipient = params.recipient.join(','); 331 | } 332 | 333 | signedCall('artist.share', params, session, callbacks, 'POST'); 334 | }, 335 | 336 | shout: function (params, session, callbacks) { 337 | signedCall('artist.shout', params, session, callbacks, 'POST'); 338 | } 339 | }; 340 | 341 | /* Auth methods. */ 342 | this.auth = { 343 | getMobileSession: function (params, callbacks) { 344 | /* Set new params object with authToken. */ 345 | params = { 346 | username: params.username, 347 | authToken: md5(params.username + md5(params.password)) 348 | }; 349 | 350 | signedCall('auth.getMobileSession', params, null, callbacks); 351 | }, 352 | 353 | getSession: function (params, callbacks) { 354 | signedCall('auth.getSession', params, null, callbacks); 355 | }, 356 | 357 | getToken: function (callbacks) { 358 | signedCall('auth.getToken', null, null, callbacks); 359 | }, 360 | 361 | /* Deprecated. Security hole was fixed. */ 362 | getWebSession: function (callbacks) { 363 | /* Save API URL and set new one (needs to be done due to a cookie!). */ 364 | var previuousApiUrl = apiUrl; 365 | 366 | apiUrl = 'http://ext.last.fm/2.0/'; 367 | 368 | signedCall('auth.getWebSession', null, null, callbacks); 369 | 370 | /* Restore API URL. */ 371 | apiUrl = previuousApiUrl; 372 | } 373 | }; 374 | 375 | /* Chart methods. */ 376 | this.chart = { 377 | getHypedArtists: function (params, session, callbacks) { 378 | call('chart.getHypedArtists', params, callbacks); 379 | }, 380 | 381 | getHypedTracks: function (params, session, callbacks) { 382 | call('chart.getHypedTracks', params, callbacks); 383 | }, 384 | 385 | getLovedTracks: function (params, session, callbacks) { 386 | call('chart.getLovedTracks', params, callbacks); 387 | }, 388 | 389 | getTopArtists: function (params, session, callbacks) { 390 | call('chart.getTopArtists', params, callbacks); 391 | }, 392 | 393 | getTopTags: function (params, session, callbacks) { 394 | call('chart.getTopTags', params, callbacks); 395 | }, 396 | 397 | getTopTracks: function (params, session, callbacks) { 398 | call('chart.getTopTracks', params, callbacks); 399 | } 400 | }; 401 | 402 | /* Event methods. */ 403 | this.event = { 404 | attend: function (params, session, callbacks) { 405 | signedCall('event.attend', params, session, callbacks, 'POST'); 406 | }, 407 | 408 | getAttendees: function (params, session, callbacks) { 409 | call('event.getAttendees', params, callbacks); 410 | }, 411 | 412 | getInfo: function (params, callbacks) { 413 | call('event.getInfo', params, callbacks); 414 | }, 415 | 416 | getShouts: function (params, callbacks) { 417 | call('event.getShouts', params, callbacks); 418 | }, 419 | 420 | share: function (params, session, callbacks) { 421 | /* Build comma separated recipients string. */ 422 | if (typeof (params.recipient) == 'object') { 423 | params.recipient = params.recipient.join(','); 424 | } 425 | 426 | signedCall('event.share', params, session, callbacks, 'POST'); 427 | }, 428 | 429 | shout: function (params, session, callbacks) { 430 | signedCall('event.shout', params, session, callbacks, 'POST'); 431 | } 432 | }; 433 | 434 | /* Geo methods. */ 435 | this.geo = { 436 | getEvents: function (params, callbacks) { 437 | call('geo.getEvents', params, callbacks); 438 | }, 439 | 440 | getMetroArtistChart: function (params, callbacks) { 441 | call('geo.getMetroArtistChart', params, callbacks); 442 | }, 443 | 444 | getMetroHypeArtistChart: function (params, callbacks) { 445 | call('geo.getMetroHypeArtistChart', params, callbacks); 446 | }, 447 | 448 | getMetroHypeTrackChart: function (params, callbacks) { 449 | call('geo.getMetroHypeTrackChart', params, callbacks); 450 | }, 451 | 452 | getMetroTrackChart: function (params, callbacks) { 453 | call('geo.getMetroTrackChart', params, callbacks); 454 | }, 455 | 456 | getMetroUniqueArtistChart: function (params, callbacks) { 457 | call('geo.getMetroUniqueArtistChart', params, callbacks); 458 | }, 459 | 460 | getMetroUniqueTrackChart: function (params, callbacks) { 461 | call('geo.getMetroUniqueTrackChart', params, callbacks); 462 | }, 463 | 464 | getMetroWeeklyChartlist: function (params, callbacks) { 465 | call('geo.getMetroWeeklyChartlist', params, callbacks); 466 | }, 467 | 468 | getMetros: function (params, callbacks) { 469 | call('geo.getMetros', params, callbacks); 470 | }, 471 | 472 | getTopArtists: function (params, callbacks) { 473 | call('geo.getTopArtists', params, callbacks); 474 | }, 475 | 476 | getTopTracks: function (params, callbacks) { 477 | call('geo.getTopTracks', params, callbacks); 478 | } 479 | }; 480 | 481 | /* Group methods. */ 482 | this.group = { 483 | getHype: function (params, callbacks) { 484 | call('group.getHype', params, callbacks); 485 | }, 486 | 487 | getMembers: function (params, callbacks) { 488 | call('group.getMembers', params, callbacks); 489 | }, 490 | 491 | getWeeklyAlbumChart: function (params, callbacks) { 492 | call('group.getWeeklyAlbumChart', params, callbacks); 493 | }, 494 | 495 | getWeeklyArtistChart: function (params, callbacks) { 496 | call('group.getWeeklyArtistChart', params, callbacks); 497 | }, 498 | 499 | getWeeklyChartList: function (params, callbacks) { 500 | call('group.getWeeklyChartList', params, callbacks); 501 | }, 502 | 503 | getWeeklyTrackChart: function (params, callbacks) { 504 | call('group.getWeeklyTrackChart', params, callbacks); 505 | } 506 | }; 507 | 508 | /* Library methods. */ 509 | this.library = { 510 | addAlbum: function (params, session, callbacks) { 511 | signedCall('library.addAlbum', params, session, callbacks, 'POST'); 512 | }, 513 | 514 | addArtist: function (params, session, callbacks) { 515 | signedCall('library.addArtist', params, session, callbacks, 'POST'); 516 | }, 517 | 518 | addTrack: function (params, session, callbacks) { 519 | signedCall('library.addTrack', params, session, callbacks, 'POST'); 520 | }, 521 | 522 | getAlbums: function (params, callbacks) { 523 | call('library.getAlbums', params, callbacks); 524 | }, 525 | 526 | getArtists: function (params, callbacks) { 527 | call('library.getArtists', params, callbacks); 528 | }, 529 | 530 | getTracks: function (params, callbacks) { 531 | call('library.getTracks', params, callbacks); 532 | } 533 | }; 534 | 535 | /* Playlist methods. */ 536 | this.playlist = { 537 | addTrack: function (params, session, callbacks) { 538 | signedCall('playlist.addTrack', params, session, callbacks, 'POST'); 539 | }, 540 | 541 | create: function (params, session, callbacks) { 542 | signedCall('playlist.create', params, session, callbacks, 'POST'); 543 | }, 544 | 545 | fetch: function (params, callbacks) { 546 | call('playlist.fetch', params, callbacks); 547 | } 548 | }; 549 | 550 | /* Radio methods. */ 551 | this.radio = { 552 | getPlaylist: function (params, session, callbacks) { 553 | signedCall('radio.getPlaylist', params, session, callbacks); 554 | }, 555 | 556 | search: function (params, session, callbacks) { 557 | signedCall('radio.search', params, session, callbacks); 558 | }, 559 | 560 | tune: function (params, session, callbacks) { 561 | signedCall('radio.tune', params, session, callbacks); 562 | } 563 | }; 564 | 565 | /* Tag methods. */ 566 | this.tag = { 567 | getInfo: function (params, callbacks) { 568 | call('tag.getInfo', params, callbacks); 569 | }, 570 | 571 | getSimilar: function (params, callbacks) { 572 | call('tag.getSimilar', params, callbacks); 573 | }, 574 | 575 | getTopAlbums: function (params, callbacks) { 576 | call('tag.getTopAlbums', params, callbacks); 577 | }, 578 | 579 | getTopArtists: function (params, callbacks) { 580 | call('tag.getTopArtists', params, callbacks); 581 | }, 582 | 583 | getTopTags: function (callbacks) { 584 | call('tag.getTopTags', null, callbacks); 585 | }, 586 | 587 | getTopTracks: function (params, callbacks) { 588 | call('tag.getTopTracks', params, callbacks); 589 | }, 590 | 591 | getWeeklyArtistChart: function (params, callbacks) { 592 | call('tag.getWeeklyArtistChart', params, callbacks); 593 | }, 594 | 595 | getWeeklyChartList: function (params, callbacks) { 596 | call('tag.getWeeklyChartList', params, callbacks); 597 | }, 598 | 599 | search: function (params, callbacks) { 600 | call('tag.search', params, callbacks); 601 | } 602 | }; 603 | 604 | /* Tasteometer method. */ 605 | this.tasteometer = { 606 | compare: function (params, callbacks) { 607 | call('tasteometer.compare', params, callbacks); 608 | }, 609 | 610 | compareGroup: function (params, callbacks) { 611 | call('tasteometer.compareGroup', params, callbacks); 612 | } 613 | }; 614 | 615 | /* Track methods. */ 616 | this.track = { 617 | addTags: function (params, session, callbacks) { 618 | signedCall('track.addTags', params, session, callbacks, 'POST'); 619 | }, 620 | 621 | ban: function (params, session, callbacks) { 622 | signedCall('track.ban', params, session, callbacks, 'POST'); 623 | }, 624 | 625 | getBuylinks: function (params, callbacks) { 626 | call('track.getBuylinks', params, callbacks); 627 | }, 628 | 629 | getCorrection: function (params, callbacks) { 630 | call('track.getCorrection', params, callbacks); 631 | }, 632 | 633 | getFingerprintMetadata: function (params, callbacks) { 634 | call('track.getFingerprintMetadata', params, callbacks); 635 | }, 636 | 637 | getInfo: function (params, callbacks) { 638 | call('track.getInfo', params, callbacks); 639 | }, 640 | 641 | getShouts: function (params, callbacks) { 642 | call('track.getShouts', params, callbacks); 643 | }, 644 | 645 | getSimilar: function (params, callbacks) { 646 | call('track.getSimilar', params, callbacks); 647 | }, 648 | 649 | getTags: function (params, session, callbacks) { 650 | signedCall('track.getTags', params, session, callbacks); 651 | }, 652 | 653 | getTopFans: function (params, callbacks) { 654 | call('track.getTopFans', params, callbacks); 655 | }, 656 | 657 | getTopTags: function (params, callbacks) { 658 | call('track.getTopTags', params, callbacks); 659 | }, 660 | 661 | love: function (params, session, callbacks) { 662 | signedCall('track.love', params, session, callbacks, 'POST'); 663 | }, 664 | 665 | removeTag: function (params, session, callbacks) { 666 | signedCall('track.removeTag', params, session, callbacks, 'POST'); 667 | }, 668 | 669 | scrobble: function (params, session, callbacks) { 670 | /* Flatten an array of multiple tracks into an object with "array notation". */ 671 | if (params.constructor.toString().indexOf("Array") != -1) { 672 | var p = {}; 673 | 674 | for (i in params) { 675 | for (j in params[i]) { 676 | p[j + '[' + i + ']'] = params[i][j]; 677 | } 678 | } 679 | 680 | params = p; 681 | } 682 | 683 | signedCall('track.scrobble', params, session, callbacks, 'POST'); 684 | }, 685 | 686 | search: function (params, callbacks) { 687 | call('track.search', params, callbacks); 688 | }, 689 | 690 | share: function (params, session, callbacks) { 691 | /* Build comma separated recipients string. */ 692 | if (typeof (params.recipient) == 'object') { 693 | params.recipient = params.recipient.join(','); 694 | } 695 | 696 | signedCall('track.share', params, session, callbacks, 'POST'); 697 | }, 698 | 699 | unban: function (params, session, callbacks) { 700 | signedCall('track.unban', params, session, callbacks, 'POST'); 701 | }, 702 | 703 | unlove: function (params, session, callbacks) { 704 | signedCall('track.unlove', params, session, callbacks, 'POST'); 705 | }, 706 | 707 | updateNowPlaying: function (params, session, callbacks) { 708 | signedCall('track.updateNowPlaying', params, session, callbacks, 'POST'); 709 | } 710 | }; 711 | 712 | /* User methods. */ 713 | this.user = { 714 | getArtistTracks: function (params, callbacks) { 715 | call('user.getArtistTracks', params, callbacks); 716 | }, 717 | 718 | getBannedTracks: function (params, callbacks) { 719 | call('user.getBannedTracks', params, callbacks); 720 | }, 721 | 722 | getEvents: function (params, callbacks) { 723 | call('user.getEvents', params, callbacks); 724 | }, 725 | 726 | getFriends: function (params, callbacks) { 727 | call('user.getFriends', params, callbacks); 728 | }, 729 | 730 | getInfo: function (params, callbacks) { 731 | call('user.getInfo', params, callbacks); 732 | }, 733 | 734 | getLovedTracks: function (params, callbacks) { 735 | call('user.getLovedTracks', params, callbacks); 736 | }, 737 | 738 | getNeighbours: function (params, callbacks) { 739 | call('user.getNeighbours', params, callbacks); 740 | }, 741 | 742 | getNewReleases: function (params, callbacks) { 743 | call('user.getNewReleases', params, callbacks); 744 | }, 745 | 746 | getPastEvents: function (params, callbacks) { 747 | call('user.getPastEvents', params, callbacks); 748 | }, 749 | 750 | getPersonalTags: function (params, callbacks) { 751 | call('user.getPersonalTags', params, callbacks); 752 | }, 753 | 754 | getPlaylists: function (params, callbacks) { 755 | call('user.getPlaylists', params, callbacks); 756 | }, 757 | 758 | getRecentStations: function (params, session, callbacks) { 759 | signedCall('user.getRecentStations', params, session, callbacks); 760 | }, 761 | 762 | getRecentTracks: function (params, callbacks) { 763 | call('user.getRecentTracks', params, callbacks); 764 | }, 765 | 766 | getRecommendedArtists: function (params, session, callbacks) { 767 | signedCall('user.getRecommendedArtists', params, session, callbacks); 768 | }, 769 | 770 | getRecommendedEvents: function (params, session, callbacks) { 771 | signedCall('user.getRecommendedEvents', params, session, callbacks); 772 | }, 773 | 774 | getShouts: function (params, callbacks) { 775 | call('user.getShouts', params, callbacks); 776 | }, 777 | 778 | getTopAlbums: function (params, callbacks) { 779 | call('user.getTopAlbums', params, callbacks); 780 | }, 781 | 782 | getTopArtists: function (params, callbacks) { 783 | call('user.getTopArtists', params, callbacks); 784 | }, 785 | 786 | getTopTags: function (params, callbacks) { 787 | call('user.getTopTags', params, callbacks); 788 | }, 789 | 790 | getTopTracks: function (params, callbacks) { 791 | call('user.getTopTracks', params, callbacks); 792 | }, 793 | 794 | getWeeklyAlbumChart: function (params, callbacks) { 795 | call('user.getWeeklyAlbumChart', params, callbacks); 796 | }, 797 | 798 | getWeeklyArtistChart: function (params, callbacks) { 799 | call('user.getWeeklyArtistChart', params, callbacks); 800 | }, 801 | 802 | getWeeklyChartList: function (params, callbacks) { 803 | call('user.getWeeklyChartList', params, callbacks); 804 | }, 805 | 806 | getWeeklyTrackChart: function (params, callbacks) { 807 | call('user.getWeeklyTrackChart', params, callbacks); 808 | }, 809 | 810 | shout: function (params, session, callbacks) { 811 | signedCall('user.shout', params, session, callbacks, 'POST'); 812 | } 813 | }; 814 | 815 | /* Venue methods. */ 816 | this.venue = { 817 | getEvents: function (params, callbacks) { 818 | call('venue.getEvents', params, callbacks); 819 | }, 820 | 821 | getPastEvents: function (params, callbacks) { 822 | call('venue.getPastEvents', params, callbacks); 823 | }, 824 | 825 | search: function (params, callbacks) { 826 | call('venue.search', params, callbacks); 827 | } 828 | }; 829 | 830 | /* Private auth methods. */ 831 | var auth = { 832 | getApiSignature: function (params) { 833 | var keys = Object.keys(params); 834 | var string = ''; 835 | 836 | keys.sort(); 837 | keys.forEach(function (key) { 838 | string += key + params[key]; 839 | }); 840 | 841 | string += apiSecret; 842 | 843 | /* Needs lastfm.api.md5.js. */ 844 | return md5(string); 845 | } 846 | }; 847 | } 848 | -------------------------------------------------------------------------------- /static/scripts/lastfm.api.md5.js: -------------------------------------------------------------------------------- 1 | /* 2 | * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message 3 | * Digest Algorithm, as defined in RFC 1321. 4 | * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. 5 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet 6 | * Distributed under the BSD License 7 | * See http://pajhome.org.uk/crypt/md5 for more info. 8 | */ 9 | 10 | /* 11 | * Configurable variables. You may need to tweak these to be compatible with 12 | * the server-side, but the defaults work in most cases. 13 | */ 14 | var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ 15 | var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ 16 | var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ 17 | 18 | /* 19 | * These are the functions you'll usually want to call 20 | * They take string arguments and return either hex or base-64 encoded strings 21 | */ 22 | function md5(s){ return hex_md5(s); } 23 | function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));} 24 | function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));} 25 | function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));} 26 | function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); } 27 | function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); } 28 | function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); } 29 | 30 | /* 31 | * Perform a simple self-test to see if the VM is working 32 | */ 33 | function md5_vm_test() 34 | { 35 | return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; 36 | } 37 | 38 | /* 39 | * Calculate the MD5 of an array of little-endian words, and a bit length 40 | */ 41 | function core_md5(x, len) 42 | { 43 | /* append padding */ 44 | x[len >> 5] |= 0x80 << ((len) % 32); 45 | x[(((len + 64) >>> 9) << 4) + 14] = len; 46 | 47 | var a = 1732584193; 48 | var b = -271733879; 49 | var c = -1732584194; 50 | var d = 271733878; 51 | 52 | for(var i = 0; i < x.length; i += 16) 53 | { 54 | var olda = a; 55 | var oldb = b; 56 | var oldc = c; 57 | var oldd = d; 58 | 59 | a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); 60 | d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); 61 | c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); 62 | b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); 63 | a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); 64 | d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); 65 | c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); 66 | b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); 67 | a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); 68 | d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); 69 | c = md5_ff(c, d, a, b, x[i+10], 17, -42063); 70 | b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); 71 | a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); 72 | d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); 73 | c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); 74 | b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); 75 | 76 | a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); 77 | d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); 78 | c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); 79 | b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); 80 | a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); 81 | d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); 82 | c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); 83 | b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); 84 | a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); 85 | d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); 86 | c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); 87 | b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); 88 | a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); 89 | d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); 90 | c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); 91 | b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); 92 | 93 | a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); 94 | d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); 95 | c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); 96 | b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); 97 | a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); 98 | d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); 99 | c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); 100 | b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); 101 | a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); 102 | d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); 103 | c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); 104 | b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); 105 | a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); 106 | d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); 107 | c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); 108 | b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); 109 | 110 | a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); 111 | d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); 112 | c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); 113 | b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); 114 | a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); 115 | d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); 116 | c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); 117 | b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); 118 | a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); 119 | d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); 120 | c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); 121 | b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); 122 | a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); 123 | d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); 124 | c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); 125 | b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); 126 | 127 | a = safe_add(a, olda); 128 | b = safe_add(b, oldb); 129 | c = safe_add(c, oldc); 130 | d = safe_add(d, oldd); 131 | } 132 | return Array(a, b, c, d); 133 | 134 | } 135 | 136 | /* 137 | * These functions implement the four basic operations the algorithm uses. 138 | */ 139 | function md5_cmn(q, a, b, x, s, t) 140 | { 141 | return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); 142 | } 143 | function md5_ff(a, b, c, d, x, s, t) 144 | { 145 | return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); 146 | } 147 | function md5_gg(a, b, c, d, x, s, t) 148 | { 149 | return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); 150 | } 151 | function md5_hh(a, b, c, d, x, s, t) 152 | { 153 | return md5_cmn(b ^ c ^ d, a, b, x, s, t); 154 | } 155 | function md5_ii(a, b, c, d, x, s, t) 156 | { 157 | return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); 158 | } 159 | 160 | /* 161 | * Calculate the HMAC-MD5, of a key and some data 162 | */ 163 | function core_hmac_md5(key, data) 164 | { 165 | var bkey = str2binl(key); 166 | if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz); 167 | 168 | var ipad = Array(16), opad = Array(16); 169 | for(var i = 0; i < 16; i++) 170 | { 171 | ipad[i] = bkey[i] ^ 0x36363636; 172 | opad[i] = bkey[i] ^ 0x5C5C5C5C; 173 | } 174 | 175 | var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz); 176 | return core_md5(opad.concat(hash), 512 + 128); 177 | } 178 | 179 | /* 180 | * Add integers, wrapping at 2^32. This uses 16-bit operations internally 181 | * to work around bugs in some JS interpreters. 182 | */ 183 | function safe_add(x, y) 184 | { 185 | var lsw = (x & 0xFFFF) + (y & 0xFFFF); 186 | var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 187 | return (msw << 16) | (lsw & 0xFFFF); 188 | } 189 | 190 | /* 191 | * Bitwise rotate a 32-bit number to the left. 192 | */ 193 | function bit_rol(num, cnt) 194 | { 195 | return (num << cnt) | (num >>> (32 - cnt)); 196 | } 197 | 198 | /* 199 | * Convert a string to an array of little-endian words 200 | * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. 201 | */ 202 | function str2binl(str) 203 | { 204 | var bin = Array(); 205 | var mask = (1 << chrsz) - 1; 206 | for(var i = 0; i < str.length * chrsz; i += chrsz) 207 | bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); 208 | return bin; 209 | } 210 | 211 | /* 212 | * Convert an array of little-endian words to a string 213 | */ 214 | function binl2str(bin) 215 | { 216 | var str = ""; 217 | var mask = (1 << chrsz) - 1; 218 | for(var i = 0; i < bin.length * 32; i += chrsz) 219 | str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask); 220 | return str; 221 | } 222 | 223 | /* 224 | * Convert an array of little-endian words to a hex string. 225 | */ 226 | function binl2hex(binarray) 227 | { 228 | var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; 229 | var str = ""; 230 | for(var i = 0; i < binarray.length * 4; i++) 231 | { 232 | str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + 233 | hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); 234 | } 235 | return str; 236 | } 237 | 238 | /* 239 | * Convert an array of little-endian words to a base-64 string 240 | */ 241 | function binl2b64(binarray) 242 | { 243 | var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 244 | var str = ""; 245 | for(var i = 0; i < binarray.length * 4; i += 3) 246 | { 247 | var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16) 248 | | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) 249 | | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF); 250 | for(var j = 0; j < 4; j++) 251 | { 252 | if(i * 8 + j * 6 > binarray.length * 32) str += b64pad; 253 | else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); 254 | } 255 | } 256 | return str; 257 | } 258 | -------------------------------------------------------------------------------- /static/styles/index.css: -------------------------------------------------------------------------------- 1 | @import "https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap"; 2 | 3 | body { 4 | animation-name: onload; 5 | animation-duration: 1.5s; 6 | transition: opacity 1s; 7 | } 8 | 9 | #main { 10 | height: 100vh; 11 | transition: scale 0.5s cubic-bezier(0, 0.5, 0.5, 1), filter 0.3s cubic-bezier(0, 0.5, 0.5, 1); 12 | } 13 | 14 | @keyframes onload { 15 | from { 16 | opacity: 0; 17 | } 18 | 19 | to { 20 | opacity: 1; 21 | } 22 | } 23 | 24 | #player-main { 25 | height: 100%; 26 | display: flex; 27 | justify-content: center; 28 | align-items: center; 29 | } 30 | 31 | .player-container { 32 | width: 100%; 33 | display: flex; 34 | justify-content: center; 35 | align-items: center; 36 | height: 100%; 37 | } 38 | 39 | #song-list { 40 | min-width: 600px; 41 | max-width: 70%; 42 | height: 80%; 43 | min-width: 70%; 44 | max-width: 70%; 45 | overflow: auto; 46 | margin: 0; 47 | } 48 | 49 | @media (min-width:1100px) { 50 | #popup { 51 | font-size: 120px; 52 | } 53 | 54 | .popup-active { 55 | font-size: 128px !important; 56 | } 57 | } 58 | 59 | @media (max-width:1100px) { 60 | #seekbar { 61 | min-height: 30px !important; 62 | } 63 | 64 | #popup { 65 | font-size: 90px; 66 | } 67 | 68 | .popup-active { 69 | font-size: 95px !important; 70 | } 71 | 72 | .player-container { 73 | overflow: hidden; 74 | } 75 | 76 | #song-list { 77 | padding: 0; 78 | height: 90%; 79 | min-width: 90%; 80 | max-width: 90%; 81 | } 82 | 83 | #player-main { 84 | flex-direction: column-reverse; 85 | } 86 | 87 | #image { 88 | max-height: 45% !important; 89 | max-width: auto !important; 90 | z-index: 1; 91 | position: absolute; 92 | } 93 | } 94 | 95 | #image { 96 | cursor: pointer; 97 | border-radius: 10px; 98 | transition: transform 0.5s ease-out, scale 0.5s ease-out, filter 0.2s 0.05s ease-out; 99 | -webkit-user-drag: none; 100 | max-height: 50%; 101 | max-width: 90%; 102 | opacity: 1; 103 | } 104 | 105 | #image:hover { 106 | scale: 1.01 107 | } 108 | 109 | #image:active { 110 | filter: saturate(0.1) brightness(0.9) blur(2px); 111 | scale: 0.99; 112 | } 113 | 114 | #image[src=''] { 115 | display: none; 116 | } 117 | 118 | #search-container { 119 | align-items: center; 120 | display: flex; 121 | flex-direction: column; 122 | height: 60%; 123 | justify-content: flex-start; 124 | width: 80% 125 | } 126 | 127 | .image-paused { 128 | scale: 0.98; 129 | filter: saturate(0.1) brightness(0.5); 130 | } 131 | 132 | #search-input { 133 | background: none; 134 | border-style: none; 135 | color: var(--primary); 136 | font-size: 128px; 137 | font-weight: 700; 138 | outline: none; 139 | width: 100% 140 | } 141 | 142 | .search-result-item { 143 | animation: opacity .5s ease-out; 144 | padding: 0 10px; 145 | cursor: pointer; 146 | transition: color 0.1s, padding 0.1s, letter-spacing 0.1s; 147 | } 148 | 149 | @keyframes opacity { 150 | 0% { 151 | opacity: 0; 152 | } 153 | 154 | 10% { 155 | opacity: 0.9; 156 | } 157 | 158 | 100% { 159 | opacity: 1; 160 | } 161 | } 162 | 163 | .search-result-item-active, 164 | .search-result-item:hover { 165 | letter-spacing: 2px; 166 | } 167 | 168 | .search-result-item:hover { 169 | color: var(--secondary); 170 | } 171 | 172 | .search-result-item-active, 173 | .search-result-item:active { 174 | font-weight: bold; 175 | padding: 0 20px; 176 | color: var(--primary) !important; 177 | } 178 | 179 | .search-result { 180 | white-space: nowrap; 181 | gap: 20px; 182 | display: flex; 183 | align-items: center; 184 | justify-content: space-between; 185 | overflow: hidden; 186 | } 187 | 188 | .search-result-song-image-title-container { 189 | display: flex; 190 | gap: 1rem; 191 | align-items: center; 192 | } 193 | 194 | .search-result-song-image { 195 | border-radius: 2px; 196 | max-height: 2.9rem; 197 | } 198 | 199 | .search-result { 200 | pointer-events: none; 201 | } 202 | 203 | .search-result-song-artist { 204 | font-size: 30px; 205 | overflow: hidden; 206 | } 207 | 208 | #search-main { 209 | align-items: center; 210 | backdrop-filter: blur(10px); 211 | background: var(--background-opaque); 212 | display: flex; 213 | height: 100%; 214 | opacity: 0; 215 | pointer-events: none; 216 | position: absolute; 217 | transition: opacity .2s; 218 | width: 100%; 219 | z-index: 2; 220 | justify-content: center 221 | } 222 | 223 | #search-results { 224 | color: var(--image-shadow); 225 | font-size: 42px; 226 | list-style: none; 227 | margin: 0; 228 | overflow: auto; 229 | padding: 0; 230 | width: 100% 231 | } 232 | 233 | #seekbar { 234 | cursor: pointer; 235 | align-items: flex-end; 236 | bottom: 0; 237 | display: flex; 238 | flex-direction: row; 239 | min-height: 79px; 240 | overflow: hidden; 241 | position: absolute; 242 | width: 100%; 243 | z-index: 3 244 | } 245 | 246 | .seekbar-hidden { 247 | display: none !important; 248 | } 249 | 250 | #seekbar-current-song-duration-text, 251 | .song-artist { 252 | color: var(--secondary) 253 | } 254 | 255 | #seekbar-current-time { 256 | background-color: var(--background-opaque); 257 | display: flex; 258 | opacity: 0; 259 | transition: opacity .1s linear 260 | } 261 | 262 | #seekbar-knob { 263 | align-items: center; 264 | display: flex; 265 | flex-direction: column; 266 | position: relative; 267 | transform: translateX(-50%); 268 | width: 0; 269 | z-index: 3 270 | } 271 | 272 | #seekbar-knob-circle { 273 | background-color: var(--highlight); 274 | border-radius: 50%; 275 | bottom: 50%; 276 | box-shadow: 0 0 30px 0 var(--highlight); 277 | height: 5px; 278 | transition: all .1s linear; 279 | width: 5px 280 | } 281 | 282 | #seekbar-progress { 283 | background-color: var(--highlight); 284 | box-shadow: 0 0 30px 0 var(--highlight); 285 | height: 5px; 286 | border-radius: 10px; 287 | } 288 | 289 | #seekbar-time-separator { 290 | color: var(--secondary); 291 | padding: 0 5px 292 | } 293 | 294 | #popup { 295 | backdrop-filter: blur(10px); 296 | align-items: center; 297 | background-color: var(--background-even-more-opaque); 298 | display: none; 299 | border-radius: 10px; 300 | display: flex !important; 301 | justify-content: center; 302 | left: 50%; 303 | opacity: 0; 304 | padding: 10px; 305 | pointer-events: none; 306 | position: absolute; 307 | top: 50%; 308 | transform: translate(-50%, -50%); 309 | transition: all .05s linear; 310 | z-index: 5 311 | } 312 | 313 | #popup-text { 314 | text-align: center; 315 | background: none; 316 | font-weight: 700 317 | } 318 | 319 | #popup-text { 320 | text-shadow: 0 0 30px rgba(255, 255, 255, 0.414); 321 | } 322 | 323 | .current-time-active { 324 | opacity: 1 !important 325 | } 326 | 327 | .knob-circle-active { 328 | height: 50px !important; 329 | transform: translateY(40%); 330 | width: 50px !important 331 | } 332 | 333 | .marker, 334 | #seekbar-progress { 335 | transition: height .1s ease-out; 336 | } 337 | 338 | .seekbar-smooth { 339 | transition: height .1s ease-out, width .2s ease-out !important 340 | } 341 | 342 | .marker { 343 | background: var(--highlight-yellow); 344 | box-shadow: 0 0 10px 0 var(--highlight-yellow); 345 | height: 5px; 346 | position: absolute; 347 | width: 3px; 348 | z-index: 4 349 | } 350 | 351 | .search-active { 352 | opacity: 1 !important; 353 | pointer-events: initial !important 354 | } 355 | 356 | .seekbar-hover { 357 | height: 15px !important 358 | } 359 | 360 | .song-body { 361 | display: flex; 362 | flex-direction: column; 363 | min-height: 50px; 364 | justify-content: space-around; 365 | pointer-events: none 366 | } 367 | 368 | .song-image { 369 | max-width: 2.5rem; 370 | min-width: 2.5rem; 371 | margin: 0 10px; 372 | pointer-events: none; 373 | border-radius: 2px; 374 | } 375 | 376 | .song-item { 377 | cursor: pointer; 378 | align-items: center; 379 | border-bottom: 1px solid var(--ternary); 380 | display: flex; 381 | padding: 5px; 382 | transition: all .1s ease-out; 383 | } 384 | 385 | .song-item:hover { 386 | background-color: var(--ternary); 387 | border-radius: 0.1rem; 388 | transition: all 0s; 389 | } 390 | 391 | .song-item-active { 392 | background-color: var(--ternary) 393 | } 394 | 395 | .popup-active { 396 | opacity: 1 !important 397 | } 398 | 399 | ::-webkit-scrollbar { 400 | border-radius: 10px; 401 | display: none; 402 | width: 10px; 403 | } 404 | 405 | ::-webkit-scrollbar-thumb { 406 | min-height: 100px; 407 | background: var(--secondary); 408 | border-radius: 10px 409 | } 410 | 411 | ::-webkit-scrollbar-track { 412 | background: var(--ternary) 413 | } 414 | 415 | ::selection { 416 | background-color: var(--highlight) 417 | } 418 | 419 | :hover::-webkit-scrollbar { 420 | display: initial 421 | } 422 | 423 | :root { 424 | --background: #000; 425 | --background-opaque: #000000e2; 426 | --background-even-more-opaque: #000000c2; 427 | 428 | --highlight: #FF003D; 429 | --highlight-yellow: #fbff00; 430 | --image-shadow: #ffffff17; 431 | --primary: #fff; 432 | --secondary: #b8b8b8; 433 | --ternary: #0c0c0c 434 | } 435 | 436 | body { 437 | overflow: hidden; 438 | background: var(--background); 439 | color: var(--primary); 440 | display: flex; 441 | flex-direction: column; 442 | font-family: Inter; 443 | font-size: 18px; 444 | height: 100%; 445 | margin: 0 446 | } 447 | 448 | hr { 449 | border: 2px solid var(--image-shadow); 450 | width: 100% 451 | } 452 | 453 | html { 454 | height: 100%; 455 | user-select: none; 456 | } --------------------------------------------------------------------------------