Repository: nortonandrews/kikoeru Branch: master Commit: 3a190b729ed0 Files: 35 Total size: 121.3 KB Directory structure: gitextract_l9zh3qme/ ├── .babelrc ├── .eslintrc.json ├── .gitignore ├── LICENSE.md ├── README.md ├── config.json ├── nodemon.json ├── package.json ├── src/ │ ├── client/ │ │ ├── components/ │ │ │ ├── AudioElement.jsx │ │ │ ├── ErrorBoundary.jsx │ │ │ ├── InfiniteScroll.jsx │ │ │ ├── NavBar.jsx │ │ │ ├── PlayerBar.jsx │ │ │ ├── WorkDetails.jsx │ │ │ └── WorkQueue.jsx │ │ ├── index.jsx │ │ ├── reducer.js │ │ ├── routes/ │ │ │ ├── List.jsx │ │ │ ├── Player.jsx │ │ │ ├── Work.jsx │ │ │ └── Works.jsx │ │ └── static/ │ │ └── style/ │ │ ├── kikoeru.css │ │ └── uikit.stripped.less │ └── server/ │ ├── auth.js │ ├── database/ │ │ ├── db.js │ │ └── schema.js │ ├── filesystem/ │ │ ├── scanner.js │ │ └── utils.js │ ├── hvdb.js │ ├── index.js │ └── routes.js ├── static/ │ ├── auth.html │ ├── index.html │ └── manifest.json └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ "@babel/preset-env" ], "plugins": [ "@babel/plugin-proposal-class-properties", "@babel/plugin-syntax-jsx", ["babel-plugin-inferno", {"imports": true}] ] } ================================================ FILE: .eslintrc.json ================================================ { "parser": "babel-eslint", "extends": ["airbnb"], "env": { "browser": true, "node": true }, "rules": { "import/no-extraneous-dependencies": [ 2, {"devDependencies": true}], "no-restricted-syntax": [0, "iterators/generators"], "react/react-in-jsx-scope": 0, "react/prop-types": 0 } } ================================================ FILE: .gitignore ================================================ .vscode node_modules dist db.sqlite3 *.log ================================================ FILE: LICENSE.md ================================================ ### GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ### Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. ### TERMS AND CONDITIONS #### 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. #### 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. #### 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. #### 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. #### 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. #### 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. #### 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. #### 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. #### 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. #### 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. #### 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. #### 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. #### 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. #### 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. #### 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. #### 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #### 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS ### How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands \`show w' and \`show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

A self-hosted web media player for listening to your DLsite voice works. ## Features - Automatically scrapes metadata from HVDB - Browse works by circle, tag or VA - Queue functionality: mix and match tracks from many different works, in whichever order you want ## Quick Start Requires both Node.js and npm installed in your system to run. Assuming you've downloaded from the releases page: ```bash # Install dependencies npm install --only=prod # Change `rootDir` in `config.json` to the # directory where you keep your voice works. # Each folder must have an RJ code somewhere # in its name for the scanner to detect it. # Scan works into the database npm run scan # Start the server npm start # App is now available at http://0.0.0.0:8888 ``` If you instead cloned this repository or just want more details, read below: ## Instructions ### Build from source ```bash # Install dependencies npm install # Build app bundle npm run build # Start the production server npm start # App is now available at http://0.0.0.0:8888 ``` ### Configuration #### Media scanner You must change `rootDir` in the `config.json` file to point to the directory where you keep your voice works. Each work must be a folder containing an RJ code anywhere in its name. **NOTE:** Even if you're on Windows, you still need to use forward slashes when specifying `rootDir`. For example: ```json { "rootDir": "D:/Downloads/Voice", "worksPerPage": 12 } ``` After this is done, you may run the initial scan: ```bash npm run scan ``` This will create a file named `db.sqlite3`, containing metadata scraped from HVDB for each work found by the scanner. This file can safely be deleted if you wish to rebuild the database. It will also create a folder called `Images` inside your `rootDir` containing work cover images. Subsequent runs of the scan command will do two things: - Look for new works and add them to the database - Remove works which have been deleted from disk since last scan It is important to note that the scanner has a configurable maximum recursion depth. However, subdirectories *inside* a work do not count towards the maximum. For example, assuming `rootDir` is `/mnt/Voice/`: ```bash # OK - This work will be detected correctly: /mnt/Voice/[Atelier Honey] 雨恋女の子守唄 (RJ136105)/ # OK - All the folders will be detected as part of the same work: /mnt/Voice/RJ130297/mp3/ノイズ有/ /mnt/Voice/RJ130297/mp3/ノイズ無(推奨)/ /mnt/Voice/RJ130297/wav/ノイズ有/ /mnt/Voice/RJ130297/wav/ノイズ無(推奨)/ # OK - As long as `scannerMaxRecursionDepth` is at least 2: /mnt/Voice/Atelier Honey/[RJ136105] 雨恋女の子守唄/ # OK - As long as `scannerMaxRecursionDepth` is at least 3: /mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/1-帰り道mp3/ /mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/2-お風呂場のおはなしmp3/ /mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/3-夕焼け花火と耳掃除mp3/ # FAIL - This work won't be detected because there's no RJ code: /mnt/Voice/雨恋女の子守唄/ ``` #### Password protection If you wish to password protect the web interface, you may change `password` in `config.json`. Be aware that falsy javascript values will turn this feature off (for example, setting `password` to `false` or `0`). ## Disclaimer At the moment, although this works well enough for regular usage, you can expect to find small quirks and bugs. This was developed on macOS and tested on Chrome for Android. It should run on Linux. I have no clue about Windows. ================================================ FILE: config.json ================================================ { "rootDir": "/mnt/Media/Voice", "password": false, "scannerMaxRecursionDepth": 2, "worksPerPage": 12, "maxParallelism": 8 } ================================================ FILE: nodemon.json ================================================ { "watch": ["src/server/"] } ================================================ FILE: package.json ================================================ { "name": "kikoeru", "version": "0.3.0", "description": "Web media player, specifically for voice works.", "main": "src/server/index.jsx", "scripts": { "build": "webpack --mode production", "start": "cross-env NODE_ENV=production node src/server/index.js", "client": "webpack-dev-server --mode development --devtool inline-source-map --hot", "server": "nodemon src/server/index.js", "dev": "concurrently \"npm run server\" \"npm run client\"", "profile": "webpack --mode production --profile --json > webpack-stats.json", "scan": "node ./src/server/filesystem/scanner.js" }, "author": "nortonandrews", "license": "GPL-3.0-or-later", "dependencies": { "cross-env": "^5.2.0", "express": "^4.17.1", "express-session": "^1.16.2", "htmlparser2": "^3.10.1", "knex": "^0.19.5", "memorystore": "^1.6.1", "natural-orderby": "^2.0.3", "node-fetch": "^2.6.0", "recursive-readdir": "^2.2.2", "sqlite3": "^4.0.9" }, "devDependencies": { "history": "^4.9.0", "inferno": "^7", "less": "^3.9.0", "redux": "^4.0.4", "uikit": "^3.1.6", "@babel/core": "^7.5.4", "@babel/plugin-proposal-class-properties": "^7.5.0", "@babel/plugin-syntax-jsx": "^7.2.0", "@babel/preset-env": "^7.5.4", "babel-eslint": "^10.0.2", "babel-loader": "^8.0.6", "babel-plugin-inferno": "^6.0.5", "babel-polyfill": "^6.26.0", "clean-webpack-plugin": "^3.0.0", "concurrently": "^4.1.1", "css-loader": "^3.0.0", "eslint": "^6.0.1", "eslint-config-airbnb": "^17.1.1", "eslint-config-inferno-app": "^7.0.2", "eslint-plugin-import": "^2.18.0", "eslint-plugin-jsx-a11y": "^6.2.3", "eslint-plugin-react": "^7.14.2", "file-loader": "^4.0.0", "html-webpack-plugin": "^3.2.0", "inferno-component": "^7", "inferno-create-element": "^7", "inferno-redux": "^7.1.13", "inferno-router": "^7", "less-loader": "^5.0.0", "mini-css-extract-plugin": "^0.7.0", "nodemon": "^1.19.1", "optimize-css-assets-webpack-plugin": "^5.0.3", "redux-starter-kit": "^0.5.1", "style-loader": "^0.23.1", "url-loader": "^2.0.1", "webpack": "^4.35.3", "webpack-cli": "^3.3.5", "webpack-dev-server": "^3.7.2" } } ================================================ FILE: src/client/components/AudioElement.jsx ================================================ import { Component, createRef } from 'inferno'; import { connect } from 'inferno-redux'; const mapStateToProps = state => ({ playing: state.playing, progress: state.progress, seek: state.seek, source: state.queue[state.queueIndex] ? `/api/stream/${state.queue[state.queueIndex].hash}` : null, queue: state.queue, queueIndex: state.queueIndex, }); class AudioElement extends Component { eventHandlers = { play: () => { const { dispatch } = this.props; dispatch({ type: 'PLAY' }); this.updateMetadata(); }, pause: () => { const { dispatch } = this.props; dispatch({ type: 'PAUSE' }); }, ended: () => { const { dispatch } = this.props; dispatch({ type: 'NEXT_TRACK' }); }, timeUpdate: (evt) => { const { dispatch } = this.props; dispatch({ type: 'TIME_UPDATE', payload: evt.target.currentTime / evt.target.duration * 100, }); }, }; constructor(props) { super(props); this.audioRef = createRef(); } componentDidMount() { // Add event listeners. this.audioRef.current.addEventListener('play', this.eventHandlers.play); this.audioRef.current.addEventListener('pause', this.eventHandlers.pause); this.audioRef.current.addEventListener('ended', this.eventHandlers.ended); this.audioRef.current.addEventListener('timeupdate', this.eventHandlers.timeUpdate); } shouldComponentUpdate(nextProps) { const { playing, seek, source, } = this.props; // Started playing, don't update. if (!playing && nextProps.playing) { this.audioRef.current.play(); } // Paused, don't update. if (playing && !nextProps.playing) { this.audioRef.current.pause(); } // Seeked, don't update. if (seek !== nextProps.seek) { this.audioRef.current.currentTime = nextProps.seek * 0.01 * this.audioRef.current.duration; } // Changed source, update component. if (source !== nextProps.source) { return true; // TODO: maybe just update source property and not re-render? } return false; } componentWillUnmount() { // Remove event listeners. this.audioRef.current.removeEventListener('play', this.eventHandlers.play); this.audioRef.current.removeEventListener('pause', this.eventHandlers.pause); this.audioRef.current.removeEventListener('ended', this.eventHandlers.ended); this.audioRef.current.removeEventListener('timeupdate', this.eventHandlers.timeUpdate); } updateMetadata() { const { dispatch, queue, queueIndex } = this.props; const { hash } = queue[queueIndex]; const id = hash.substring(0, hash.lastIndexOf('/')); // TODO: this fetch causes the notification to show no metadata for a second // while it fetches, consider keeping this saved client-side somewhere fetch(`/api/work/${id}`) .then(res => res.json()) .then((metadata) => { if ('mediaSession' in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: queue[queueIndex].title, artist: metadata.circle.name, album: metadata.title, artwork: [ { src: `/api/cover/${id}`, type: 'image/jpeg' }, ], }); const prev = queueIndex === 0 ? null : () => dispatch({ type: 'PREVIOUS_TRACK' }); const next = queueIndex === queue.length - 1 ? null : () => dispatch({ type: 'NEXT_TRACK' }); navigator.mediaSession.setActionHandler('previoustrack', prev); navigator.mediaSession.setActionHandler('nexttrack', next); } }) .catch((err) => { throw new Error(`Failed to fetch /api/work/${id}: ${err}`); }); } render() { const { playing, source } = this.props; if (this.audioRef.current) { if (source) { this.audioRef.current.src = source; this.audioRef.current.load(); if (playing) { this.audioRef.current.play(); } } } return ( // eslint-disable-next-line jsx-a11y/media-has-caption ); } } export default connect(mapStateToProps)(AudioElement); ================================================ FILE: src/client/components/ErrorBoundary.jsx ================================================ // TODO: this entire thing is not being used at the moment, test later import { Component } from 'inferno'; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI, log error this.setState({ hasError: true, error, info }); // eslint-disable-next-line no-console console.error(error, info); } render() { const { children } = this.props; const { hasError, error, info } = this.state; if (hasError) { return (

Something went wrong:

{error}

{info}

); } return children; } } export default ErrorBoundary; ================================================ FILE: src/client/components/InfiniteScroll.jsx ================================================ /** * Apologies for this trainwreck. Copied and pasted from * https://www.npmjs.com/package/react-infinite-scroll-component * with a few small changes because I didn't want to install react-compat. */ import { Component } from 'inferno'; const ThresholdUnits = { Pixel: 'Pixel', Percent: 'Percent', }; const defaultThreshold = { unit: ThresholdUnits.Percent, value: 0.8, }; const parseThreshold = (scrollThreshold) => { if (typeof scrollThreshold === "number") { return { unit: ThresholdUnits.Percent, value: scrollThreshold * 100, }; } if (typeof scrollThreshold === "string") { if (scrollThreshold.match(/^(\d*(\.\d+)?)px$/)) { return { unit: ThresholdUnits.Pixel, value: parseFloat(scrollThreshold), }; } if (scrollThreshold.match(/^(\d*(\.\d+)?)%$/)) { return { unit: ThresholdUnits.Percent, value: parseFloat(scrollThreshold), }; } console.warn('scrollThreshold format is invalid. Valid formats: "120px", "50%"...'); return defaultThreshold; } console.warn('scrollThreshold should be string or number'); return defaultThreshold; } // https://remysharp.com/2010/07/21/throttling-function-calls const throttle = (fn, threshhold, scope) => { threshhold || (threshhold = 250); let last; let deferTimer; return function () { const context = scope || this; const now = +new Date(); let args = arguments; if (last && now < last + threshhold) { // hold on to it clearTimeout(deferTimer); deferTimer = setTimeout(() => { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; }; class InfiniteScroll extends Component { constructor(props) { super(); this.state = { showLoader: false, lastScrollTop: 0, actionTriggered: false, pullToRefreshThresholdBreached: false, }; // variables to keep track of pull down behaviour this.startY = 0; this.currentY = 0; this.dragging = false; // will be populated in componentDidMount // based on the height of the pull down element this.maxPullDownDistance = 0; this.onScrollListener = this.onScrollListener.bind(this); this.throttledOnScrollListener = throttle(this.onScrollListener, 150).bind( this, ); this.onStart = this.onStart.bind(this); this.onMove = this.onMove.bind(this); this.onEnd = this.onEnd.bind(this); this.getScrollableTarget = this.getScrollableTarget.bind(this); } componentDidMount() { this._scrollableNode = this.getScrollableTarget(); this.el = this.props.height ? this._infScroll : this._scrollableNode || window; this.el.addEventListener('scroll', this.throttledOnScrollListener); if ( typeof this.props.initialScrollY === 'number' && this.el.scrollHeight > this.props.initialScrollY ) { this.el.scrollTo(0, this.props.initialScrollY); } if (this.props.pullDownToRefresh) { this.el.addEventListener('touchstart', this.onStart); this.el.addEventListener('touchmove', this.onMove); this.el.addEventListener('touchend', this.onEnd); this.el.addEventListener('mousedown', this.onStart); this.el.addEventListener('mousemove', this.onMove); this.el.addEventListener('mouseup', this.onEnd); // get BCR of pullDown element to position it above this.maxPullDownDistance = this._pullDown.firstChild.getBoundingClientRect().height; this.forceUpdate(); if (typeof this.props.refreshFunction !== 'function') { throw new Error( `Mandatory prop "refreshFunction" missing. Pull Down To Refresh functionality will not work as expected. Check README.md for usage'`, ); } } } componentWillUnmount() { this.el.removeEventListener('scroll', this.throttledOnScrollListener); if (this.props.pullDownToRefresh) { this.el.removeEventListener('touchstart', this.onStart); this.el.removeEventListener('touchmove', this.onMove); this.el.removeEventListener('touchend', this.onEnd); this.el.removeEventListener('mousedown', this.onStart); this.el.removeEventListener('mousemove', this.onMove); this.el.removeEventListener('mouseup', this.onEnd); } } componentWillReceiveProps(props) { // do nothing when dataLength and key are unchanged if (this.props.key === props.key && this.props.dataLength === props.dataLength) return; // update state when new data was sent in this.setState({ showLoader: false, actionTriggered: false, pullToRefreshThresholdBreached: false, }); } getScrollableTarget() { if (this.props.scrollableTarget instanceof HTMLElement) return this.props.scrollableTarget; if (typeof this.props.scrollableTarget === 'string') { return document.getElementById(this.props.scrollableTarget); } if (this.props.scrollableTarget === null) { console.warn(`You are trying to pass scrollableTarget but it is null. This might happen because the element may not have been added to DOM yet. See https://github.com/ankeetmaini/react-infinite-scroll-component/issues/59 for more info. `); } return null; } onStart(evt) { if (this.state.lastScrollTop) return; this.dragging = true; this.startY = evt.pageY || evt.touches[0].pageY; this.currentY = this.startY; this._infScroll.style.willChange = 'transform'; this._infScroll.style.transition = 'transform 0.2s cubic-bezier(0,0,0.31,1)'; } onMove(evt) { if (!this.dragging) return; this.currentY = evt.pageY || evt.touches[0].pageY; // user is scrolling down to up if (this.currentY < this.startY) return; if (this.currentY - this.startY >= this.props.pullDownToRefreshThreshold) { this.setState({ pullToRefreshThresholdBreached: true, }); } // so you can drag upto 1.5 times of the maxPullDownDistance if (this.currentY - this.startY > this.maxPullDownDistance * 1.5) return; this._infScroll.style.overflow = 'visible'; this._infScroll.style.transform = `translate3d(0px, ${this.currentY - this.startY}px, 0px)`; } onEnd(evt) { this.startY = 0; this.currentY = 0; this.dragging = false; if (this.state.pullToRefreshThresholdBreached) { this.props.refreshFunction && this.props.refreshFunction(); } requestAnimationFrame(() => { // this._infScroll if (this._infScroll) { this._infScroll.style.overflow = 'inherit'; this._infScroll.style.transform = 'none'; this._infScroll.style.willChange = 'none'; } }); } isElementAtBottom(target, scrollThreshold = 0.8) { const clientHeight = target === document.body || target === document.documentElement ? window.screen.availHeight : target.clientHeight; const threshold = parseThreshold(scrollThreshold); if (threshold.unit === ThresholdUnits.Pixel) { return ( target.scrollTop + clientHeight >= target.scrollHeight - threshold.value ); } return ( target.scrollTop + clientHeight >= threshold.value / 100 * target.scrollHeight ); } onScrollListener(event) { if (typeof this.props.onScroll === 'function') { // Execute this callback in next tick so that it does not affect the // functionality of the library. setTimeout(() => this.props.onScroll(event), 0); } const target = this.props.height || this._scrollableNode ? event.target : document.documentElement.scrollTop ? document.documentElement : document.body; // return immediately if the action has already been triggered, // prevents multiple triggers. if (this.state.actionTriggered) return; const atBottom = this.isElementAtBottom(target, this.props.scrollThreshold); // call the `next` function in the props to trigger the next data fetch if (atBottom && this.props.hasMore) { this.setState({ actionTriggered: true, showLoader: true }); this.props.next(); } this.setState({ lastScrollTop: target.scrollTop }); } render() { const style = { height: this.props.height || 'auto', overflow: 'inherit', WebkitOverflowScrolling: 'touch', ...this.props.style, }; const hasChildren = this.props.hasChildren || !!(this.props.children && this.props.children.length); // because heighted infiniteScroll visualy breaks // on drag down as overflow becomes visible const outerDivStyle = this.props.pullDownToRefresh && this.props.height ? { overflow: 'inherit' } : {}; return (
(this._infScroll = infScroll)} style={style} > {this.props.pullDownToRefresh && (
(this._pullDown = pullDown)} >
{!this.state.pullToRefreshThresholdBreached && this.props.pullDownToRefreshContent} {this.state.pullToRefreshThresholdBreached && this.props.releaseToRefreshContent}
)} {this.props.children} {!this.state.showLoader && !hasChildren && this.props.hasMore && this.props.loader} {this.state.showLoader && this.props.hasMore && this.props.loader} {!this.props.hasMore && this.props.endMessage}
); } } export default InfiniteScroll; ================================================ FILE: src/client/components/NavBar.jsx ================================================ import { Link, withRouter } from 'inferno-router'; import UIkit from 'uikit'; const closeOffCanvasNav = () => { const element = document.getElementById('offcanvas-nav'); UIkit.offcanvas(element).hide(); }; const OffCanvasNav = (props) => { const { location } = props; const path = location.pathname; return (
  • Browse
  • Works
  • Circles
  • Tags
  • VAs
); }; const OffCanvasNavWithRouter = withRouter(OffCanvasNav); const NavBar = (props) => { const { location } = props; const transparent = location.pathname === '/player/'; return ( <>
); }; export default withRouter(NavBar); ================================================ FILE: src/client/components/PlayerBar.jsx ================================================ import { connect } from 'inferno-redux'; import { Link } from 'inferno-router'; import playIcon from '../static/svg/play.svg'; import pauseIcon from '../static/svg/pause.svg'; const mapStateToProps = state => ({ playing: state.playing, queue: state.queue, currentlyPlaying: state.queue[state.queueIndex], }); const PlayerBar = (props) => { const { dispatch, playing, queue, currentlyPlaying, } = props; // Queue is empty, don't render the player bar. if (queue.length === 0) { return null; } return ( <>
Cover

{currentlyPlaying.title}

{currentlyPlaying.subtitle}

); }; export default connect(mapStateToProps)(PlayerBar); ================================================ FILE: src/client/components/WorkDetails.jsx ================================================ import { Link } from 'inferno-router'; // Renders the tag links. const Tags = props => props.tags.map( (tag, index, tags) => ( <> {tag.name} {index !== tags.length - 1 ? ', ' : ''} ), ); // Renders the VA badges. const VAs = props => props.vas.map( va => ( {va.name} ), ); // Renders the work metadata. export default ({ metadata }) => (
Cover

{metadata.title}

{metadata.circle.name}

); ================================================ FILE: src/client/components/WorkQueue.jsx ================================================ import { Component } from 'inferno'; import { connect } from 'inferno-redux'; import UIkit from 'uikit'; const mapStateToProps = state => ({ // Track hash if currently playing a track, else null. currentlyPlayingHash: (state.playing && state.queue[state.queueIndex]) ? state.queue[state.queueIndex].hash : null, }); // Renders a single row (track) inside the list. const FileTableRow = ({ clickHandler, file, index, fileOptions, usePauseIcon, }) => ( )}
); // Card containing the track list. class WorkQueue extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(evt, payload) { const { dispatch, queue } = this.props; if (typeof payload === 'number') { // Clicked play on a single track. Add all files to queue and play the one // we clicked on. dispatch({ type: 'SET_QUEUE', payload: { queue, index: payload }, }); } else { if (payload.type === 'EMPTY_QUEUE') { // Clicked on trash icon at top of card (empty queue). dispatch(payload); } else { // Clicked one of the other options (move in queue, delete from queue). dispatch({ type: payload.type, payload: { index: payload.index, file: queue[payload.index] }, }); } // Close dropdown. const dropdownElement = evt.srcElement.parentElement.parentElement.parentElement; UIkit.dropdown(dropdownElement).hide(); } } render() { const { currentlyPlayingHash, queue, fileOptions, showTrashButton, } = this.props; if (!queue || queue.length === 0) { // TODO: center this. actually, does this ever get rendered? return (

Queue is empty.

); } const TrashButton = (
); } } export default connect(mapStateToProps)(Player); ================================================ FILE: src/client/routes/Work.jsx ================================================ import { Component } from 'inferno'; import WorkDetails from '../components/WorkDetails'; import WorkQueue from '../components/WorkQueue'; /** * Work page. Shows metadata and files for a specific work. */ class Work extends Component { constructor(props) { super(props); this.state = { metadata: null, tracks: null, }; this.fileOptions = [ { text: 'Add to queue', type: 'ADD_TO_QUEUE' }, { text: 'Play next', type: 'PLAY_NEXT' }, ]; } componentDidMount() { const { match } = this.props; // TODO: test if status code is 200, show error UI otherwise const metadataPromise = fetch(`/api/work/${match.params.rjcode}`).then(res => res.json()); const tracksPromise = fetch(`/api/tracks/${match.params.rjcode}`).then(res => res.json()); Promise.all([metadataPromise, tracksPromise]) .then(res => this.setState({ metadata: res[0], tracks: res[1].map((track) => { // TODO: mixing id with rjcode smells fishy . test if breaks anything on < 6 digit ids // eslint-disable-next-line no-param-reassign track.id = match.params.rjcode; return track; }), })) .catch((err) => { throw new Error(`Failed to fetch work from backend: ${err}`); }); } render() { const { metadata, tracks } = this.state; // Metadata still loading, render spinner. // TODO: fix positioning and overflow on this spinner if (!metadata || !tracks) { return (
); } // Metadata ready, render the work page. return ( <>
); } } export default Work; ================================================ FILE: src/client/routes/Works.jsx ================================================ import { Component } from 'inferno'; import InfiniteScroll from '../components/InfiniteScroll'; import WorkDetails from '../components/WorkDetails'; /** * Card component for a single work. */ class WorkCard extends Component { constructor(props) { super(props); this.state = { metadata: null, }; } componentDidMount() { const { id } = this.props; fetch(`/api/work/${id}`) .then(res => res.json()) .then((res) => { this.setState({ metadata: res }); }) .catch((err) => { throw new Error(`Failed to fetch /api/work/${id}: ${err}`); }); } render() { const { metadata } = this.state; // If metadata is still loading, render spinner. let innerElement = (
); // Otherwise, render WorkDetails component with the fetched metadata. if (metadata) { innerElement = (); } return (
{innerElement}
); } } /** * Work list component. */ class Works extends Component { constructor(props) { super(props); this.state = { works: null, oldestId: null, hasMore: true, pageTitle: null, }; this.loadMore = this.loadMore.bind(this); } // TODO: componentDidMount and loadMore have a lot of common code. refactor? componentDidMount() { const { match, restrict } = this.props; const url = match.params.id ? `/api/${restrict || 'works'}/${match.params.id}` : '/api/works/'; fetch(url) .then(res => res.json()) .then((res) => { fetch(`/api/get-name/${restrict}/${match.params.id}`) .then(nameRes => nameRes.text()) .then((name) => { let pageTitle; switch (restrict) { case 'tag': pageTitle = 'Works tagged with '; break; case 'va': pageTitle = 'Works voiced by '; break; case 'circle': pageTitle = 'Works by '; break; default: pageTitle = 'All works'; } pageTitle += name || ''; this.setState({ works: res, oldestId: res[res.length - 1].id, pageTitle, }); }); }) .catch((err) => { throw new Error(`Failed to fetch ${url}: ${err}`); }); } componentDidUpdate(prevProps) { const { match } = this.props; const { match: prevMatch } = prevProps; if (match.params.id !== prevMatch.params.id) { this.componentDidMount(); } } loadMore() { const { match, restrict } = this.props; const { works, oldestId } = this.state; const url = match.params.id ? `/api/${restrict || 'works'}/${match.params.id}/${oldestId}` : `/api/works/${oldestId}`; fetch(url) .then(res => res.json()) .then((res) => { if (!res.length) { this.setState({ hasMore: false, }); } else { this.setState({ works: works.concat(res), oldestId: res[res.length - 1].id, }); } }) .catch((err) => { throw new Error(`Failed to fetch ${url}: ${err}`); }); } render() { const { works, pageTitle, hasMore } = this.state; if (!works) { return (
); } return (

{pageTitle}

} endMessage={

No more works.

} > {works.map(work => )}
); } } export default Works; ================================================ FILE: src/client/static/style/kikoeru.css ================================================ /** * Logo for the navbars. */ .k-logo { font-size: 1.5em; font-family: 'Big Caslon', 'Times New Roman', Times, serif; } .k-logo-muted { font-size: 4em !important; opacity: 0.3; } .k-logo::after { content: 'K'; } /** * Badge/label links (VAs) */ .k-label-link { color: #fff !important; text-decoration: none !important; margin-right: 3px; } .k-label-link:clicked { background-color: #5dd7a9; } .k-label-link:hover { background-color: #32bc88; } /** * Play/menu icons in the queue card. */ .k-button-icon { padding: 0; width: 20px; transition-property: color, transform, -webkit-transform; transition-duration: 0.3s; -webkit-tap-highlight-color: transparent; } .k-button-icon:hover, .k-button-active { color: #1e87f0; -webkit-transform: scale(1.15); transform: scale(1.15); } /** * Bottom player bar. */ .k-player-bar { position: fixed; width: 100%; bottom: 0; padding: 8px 8px 8px 14px; background-color: #fff; box-shadow: 0 0 12px rgba(0, 0, 0, 0.2); border-top: 1px solid rgba(0, 0, 0, 0.15); } @keyframes button-touch-animation { 0% { transform: scale(0, 0); opacity: 1; } 20% { transform: scale(25, 25); opacity: 1; } 100% { opacity: 0; transform: scale(40, 40); } } .k-player-button { background-color: transparent; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; margin-left: 12px; margin-right: 12px; -webkit-tap-highlight-color: transparent; } .k-player-button:after { content: ''; overflow: visible !important; position: absolute; top: 50%; left: 50%; width: 2px; height: 2px; background: rgba(255, 255, 255, 0.5); opacity: 0; border-radius: 100%; transform: scale(1, 1) translate(-50%); transform-origin: 50% 50%; } .k-player-button:hover:not(:active)::after { animation: button-touch-animation 0.5s ease-out; } .k-invert { filter: invert(100%); } .k-player-seekbar { margin-bottom: 0px; position: relative; } .k-player-seekbar-progress { height: 5px; background: #0000; } .k-progress-bar { height: 100%; position: relative; background-color: #5dd7a9; } .k-progress-bar::after { overflow: hidden; content: " "; display: block; position: absolute; width: 14px; height: 14px; background-color: #5dd7a9; border-radius: 8px; top: -4px; right: -6px; z-index: 50; } /** * Hide original range input elements. */ .k-player-seekbar input[type="range"] { -webkit-appearance: none; width: calc(100% + 0px); overflow-x: hidden; height: 32px; margin: 0; padding: 0; position: absolute; top: -14px; left: -8px; z-index: 2; background: transparent; outline: 0; border: 0; } .k-player-seekbar input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; display: block; width: 48px; height: 48px; background-color: transparent; } /* Mozilla: https://developer.mozilla.org/en-US/docs/User:Jonathan_Watt/range */ .k-player-seekbar input[type="range"]::-moz-range-thumb { background: transparent; border: 0; width: 48px; height: 48px; } .k-player-seekbar input[type="range"]::-moz-range-track { background: transparent; border: 0; } .k-player-seekbar input[type="range"]::-moz-focus-outer { border: 0; } ================================================ FILE: src/client/static/style/uikit.stripped.less ================================================ @path: "../../../../node_modules/uikit/src"; /* Components */ // Base @import "@{path}/less/components/variables.less"; @import "@{path}/less/components/mixin.less"; @import "@{path}/less/components/base.less"; // Elements @import "@{path}/less/components/link.less"; @import "@{path}/less/components/heading.less"; @import "@{path}/less/components/divider.less"; @import "@{path}/less/components/list.less"; // @import "@{path}/less/components/description-list.less"; @import "@{path}/less/components/table.less"; @import "@{path}/less/components/icon.less"; // @import "@{path}/less/components/form-range.less"; @import "@{path}/less/components/form.less"; // After: Icon, Form Range @import "@{path}/less/components/button.less"; // Layout // @import "@{path}/less/components/section.less"; @import "@{path}/less/components/container.less"; @import "@{path}/less/components/grid.less"; // @import "@{path}/less/components/tile.less"; @import "@{path}/less/components/card.less"; // Common @import "@{path}/less/components/close.less"; // After: Icon @import "@{path}/less/components/spinner.less"; // After: Icon // @import "@{path}/less/components/totop.less"; // After: Icon // @import "@{path}/less/components/marker.less"; // After: Icon // @import "@{path}/less/components/alert.less"; // After: Close // @import "@{path}/less/components/badge.less"; @import "@{path}/less/components/label.less"; @import "@{path}/less/components/overlay.less"; // After: Icon // @import "@{path}/less/components/article.less"; // After: Subnav // @import "@{path}/less/components/comment.less"; // After: Subnav // @import "@{path}/less/components/search.less"; // After: Icon // Navs @import "@{path}/less/components/nav.less"; @import "@{path}/less/components/navbar.less"; // After: Card, Grid, Nav, Icon, Search // @import "@{path}/less/components/subnav.less"; // @import "@{path}/less/components/breadcrumb.less"; // @import "@{path}/less/components/pagination.less"; // @import "@{path}/less/components/tab.less"; // @import "@{path}/less/components/slidenav.less"; // After: Icon // @import "@{path}/less/components/dotnav.less"; // @import "@{path}/less/components/thumbnav.less"; // JavaScript // @import "@{path}/less/components/accordion.less"; @import "@{path}/less/components/drop.less"; // After: Card @import "@{path}/less/components/dropdown.less"; // After: Card // @import "@{path}/less/components/modal.less"; // After: Close // @import "@{path}/less/components/lightbox.less"; // After: Close // @import "@{path}/less/components/slideshow.less"; // @import "@{path}/less/components/slider.less"; // @import "@{path}/less/components/sticky.less"; @import "@{path}/less/components/offcanvas.less"; // @import "@{path}/less/components/switcher.less"; // @import "@{path}/less/components/leader.less"; // Scrollspy // Toggle // Scroll // Additional @import "@{path}/less/components/iconnav.less"; // @import "@{path}/less/components/notification.less"; // @import "@{path}/less/components/tooltip.less"; // @import "@{path}/less/components/placeholder.less"; // @import "@{path}/less/components/progress.less"; // @import "@{path}/less/components/sortable.less"; // @import "@{path}/less/components/countdown.less"; // Utilities @import "@{path}/less/components/animation.less"; @import "@{path}/less/components/width.less"; @import "@{path}/less/components/height.less"; @import "@{path}/less/components/text.less"; @import "@{path}/less/components/column.less"; @import "@{path}/less/components/cover.less"; @import "@{path}/less/components/background.less"; @import "@{path}/less/components/align.less"; @import "@{path}/less/components/svg.less"; @import "@{path}/less/components/utility.less"; @import "@{path}/less/components/flex.less"; // After: Utility @import "@{path}/less/components/margin.less"; @import "@{path}/less/components/padding.less"; @import "@{path}/less/components/position.less"; @import "@{path}/less/components/transition.less"; @import "@{path}/less/components/visibility.less"; @import "@{path}/less/components/inverse.less"; // Need to be loaded last @import "@{path}/less/components/print.less"; /* Theme */ // Base @import "@{path}/less/theme/variables.less"; @import "@{path}/less/theme/base.less"; // Elements @import "@{path}/less/theme/link.less"; @import "@{path}/less/theme/heading.less"; @import "@{path}/less/theme/divider.less"; @import "@{path}/less/theme/list.less"; // @import "@{path}/less/theme/description-list.less"; @import "@{path}/less/theme/table.less"; @import "@{path}/less/theme/icon.less"; // @import "@{path}/less/theme/form-range.less"; @import "@{path}/less/theme/form.less"; @import "@{path}/less/theme/button.less"; // Layout // @import "@{path}/less/theme/section.less"; @import "@{path}/less/theme/container.less"; @import "@{path}/less/theme/grid.less"; // @import "@{path}/less/theme/tile.less"; @import "@{path}/less/theme/card.less"; // Common @import "@{path}/less/theme/close.less"; @import "@{path}/less/theme/spinner.less"; // @import "@{path}/less/theme/marker.less"; // @import "@{path}/less/theme/totop.less"; // @import "@{path}/less/theme/alert.less"; // @import "@{path}/less/theme/badge.less"; @import "@{path}/less/theme/label.less"; @import "@{path}/less/theme/overlay.less"; // @import "@{path}/less/theme/article.less"; // @import "@{path}/less/theme/comment.less"; // @import "@{path}/less/theme/search.less"; // Navs @import "@{path}/less/theme/nav.less"; @import "@{path}/less/theme/navbar.less"; // @import "@{path}/less/theme/subnav.less"; // @import "@{path}/less/theme/breadcrumb.less"; // @import "@{path}/less/theme/pagination.less"; // @import "@{path}/less/theme/tab.less"; // @import "@{path}/less/theme/slidenav.less"; // @import "@{path}/less/theme/dotnav.less"; // @import "@{path}/less/theme/thumbnav.less"; // JavaScript // @import "@{path}/less/theme/accordion.less"; @import "@{path}/less/theme/drop.less"; @import "@{path}/less/theme/dropdown.less"; // @import "@{path}/less/theme/modal.less"; // @import "@{path}/less/theme/lightbox.less"; // @import "@{path}/less/theme/sticky.less"; @import "@{path}/less/theme/offcanvas.less"; // @import "@{path}/less/theme/leader.less"; // Additional @import "@{path}/less/theme/iconnav.less"; // @import "@{path}/less/theme/notification.less"; // @import "@{path}/less/theme/tooltip.less"; // @import "@{path}/less/theme/placeholder.less"; // @import "@{path}/less/theme/progress.less"; // @import "@{path}/less/theme/sortable.less"; // @import "@{path}/less/theme/countdown.less"; // Utilities @import "@{path}/less/theme/animation.less"; @import "@{path}/less/theme/width.less"; @import "@{path}/less/theme/height.less"; @import "@{path}/less/theme/text.less"; @import "@{path}/less/theme/column.less"; @import "@{path}/less/theme/background.less"; @import "@{path}/less/theme/align.less"; @import "@{path}/less/theme/utility.less"; @import "@{path}/less/theme/margin.less"; @import "@{path}/less/theme/padding.less"; @import "@{path}/less/theme/position.less"; @import "@{path}/less/theme/transition.less"; @import "@{path}/less/theme/inverse.less"; /* Extra */ @media (min-width: @breakpoint-small) and (max-width: @breakpoint-medium - 1) { .uk-width-1-2-margin\@s { width: ~'calc(100% * 1 / 2.3)' !important; } } @media (min-width: @breakpoint-medium) { .uk-width-1-3-margin\@m { width: ~'calc(100% * 1 / 3.5)'; } } ================================================ FILE: src/server/auth.js ================================================ const path = require('path'); const express = require('express'); const config = require('../../config.json'); const router = express.Router(); router.get('/', (req, res, next) => { res.sendFile(path.join(__dirname, '..', '..', 'static', 'auth.html')); }); router.post('/', (req, res, next) => { if (req.body.password === config.password) { req.session.auth = true; } res.redirect('/'); }); const authenticator = (req, res, next) => { if (req.path === '/auth/' || req.path === '/main.css' || req.path.indexOf('/static/') === 0 || req.session.auth || !config.password ) { next(); } else { res.redirect('/auth/'); } }; module.exports = { router, authenticator }; ================================================ FILE: src/server/database/db.js ================================================ const knex = require('knex')({ client: 'sqlite3', useNullAsDefault: true, connection: { filename: './db.sqlite3', }, acquireConnectionTimeout: 5000, }); /** * Takes a work metadata object and inserts it into the database. * @param {Object} work Work object. */ const insertWorkMetadata = work => knex.transaction(trx => trx.raw( trx('t_circle') .insert({ id: work.circle.id, name: work.circle.name, }).toString().replace('insert', 'insert or ignore'), ) .then(() => trx('t_work') .insert({ id: work.id, dir: work.dir, title: work.title, circle_id: work.circle.id, nsfw: work.nsfw, })) .then(() => { // Now that work is in the database, insert relationships const promises = []; for (let i = 0; i < work.tags.length; i += 1) { promises.push(trx.raw( trx('t_tag') .insert({ id: work.tags[i].id, name: work.tags[i].name, }).toString().replace('insert', 'insert or ignore'), ) .then(() => trx('r_tag_work') .insert({ tag_id: work.tags[i].id, work_id: work.id, }))); } for (let i = 0; i < work.vas.length; i += 1) { promises.push(trx.raw( trx('t_va') .insert({ id: work.vas[i].id, name: work.vas[i].name, }).toString().replace('insert', 'insert or ignore'), ) .then(() => trx('r_va_work') .insert({ va_id: work.vas[i].id, work_id: work.id, }))); } return Promise.all(promises) .then(() => trx); })); /** * Fetches metadata for a specific work id. * @param {Number} id Work identifier. */ const getWorkMetadata = id => new Promise((resolve, reject) => { // TODO: do this all in a single transaction? knex('t_work') .select('*') .where('id', '=', id) .first() .then((workRes) => { if (!workRes) { throw new Error(`There is no work with id ${id} in the database.`); } knex('t_circle') .select('name') .where('t_circle.id', '=', workRes.circle_id) .first() .then((circleRes) => { const work = { id: workRes.id, title: workRes.title, circle: { id: workRes.circle_id, name: circleRes.name }, }; knex('r_tag_work') .select('tag_id', 'name') .where('r_tag_work.work_id', '=', id) .join('t_tag', 't_tag.id', '=', 'r_tag_work.tag_id') .then((tagsRes) => { work.tags = tagsRes.map(tag => ({ id: tag.tag_id, name: tag.name })); knex('r_va_work') .select('va_id', 'name') .where('r_va_work.work_id', '=', id) .join('t_va', 't_va.id', '=', 'r_va_work.va_id') .then((vaRes) => { work.vas = vaRes.map(va => ({ id: va.va_id, name: va.name })); resolve(work); }); }); }); }) .catch(err => reject(err)); }); /** * Tests if the given circle, tags and VAs are orphans and if so, removes them. * @param {*} trx Knex transaction object. * @param {*} circle Circle id to check. * @param {*} tags Array of tag ids to check. * @param {*} vas Array of VA ids to check. */ const cleanupOrphans = (trx, circle, tags, vas) => new Promise(async (resolve, reject) => { const getCount = (tableName, colName, colValue) => new Promise((resolveCount, rejectCount) => { trx(tableName) .select(colName) .where(colName, '=', colValue) .count() .first() .then(res => res['count(*)']) .then(count => resolveCount(count)) .catch(err => rejectCount(err)); }); const promises = []; promises.push(new Promise((resolveCircle, rejectCircle) => { getCount('t_work', 'circle_id', circle) .then((count) => { if (count === 0) { trx('t_circle') .del() .where('id', '=', circle) .then(() => resolveCircle()) .catch(err => rejectCircle(err)); } else { resolveCircle(); } }); })); for (let i = 0; i < tags.length; i += 1) { const tag = tags[i]; // eslint-disable-next-line no-await-in-loop const count = await getCount('r_tag_work', 'tag_id', tag); if (count === 0) { promises.push( trx('t_tag') .delete() .where('id', '=', tag), ); } } for (let i = 0; i < vas.length; i += 1) { const va = vas[i]; // eslint-disable-next-line no-await-in-loop const count = await getCount('r_va_work', 'va_id', va); if (count === 0) { promises.push( trx('t_va') .delete() .where('id', '=', va), ); } } Promise.all(promises) .then((results) => { resolve(results); }) .catch(err => reject(err)); }); /** * Removes a work and then its orphaned circles, tags & VAs from the database. * @param {Integer} id Work id. */ const removeWork = id => new Promise(async (resolve, reject) => { const trx = await knex.transaction(); // Save circle, tags and VAs to array for later testing const circle = await trx('t_work').select('circle_id').where('id', '=', id).first(); const tags = await trx('r_tag_work').select('tag_id').where('work_id', '=', id); const vas = await trx('r_va_work').select('va_id').where('work_id', '=', id); // Remove work and its relationships trx('t_work') .del() .where('id', '=', id) .then(trx('r_tag_work') .del() .where('work_id', '=', id) .then(trx('r_va_work') .del() .where('work_id', '=', id) .then(() => cleanupOrphans( trx, circle.circle_id, tags.map(tag => tag.tag_id), vas.map(va => va.va_id), )) .then(trx.commit) .then(() => resolve()))) .catch(err => reject(err)); }); /** * Returns list of work ids by circle, tag or VA. * @param {Number} id Which id to filter by. * @param {String} field Which field to filter by. */ const getUnsortedWorksBy = (id, field) => { switch (field) { case 'circle': return knex('t_work') .select('id') .where('circle_id', '=', id); case 'tag': return knex('r_tag_work') .select('work_id as id') .where('tag_id', '=', id); case 'va': return knex('r_va_work') .select('work_id as id') .where('va_id', '=', id); default: return knex('t_work') .select('id'); } }; const getWorksBy = (id, field) => getUnsortedWorksBy(id, field).orderBy('id', 'desc'); const paginateResults = (query, startFrom, howMany, tableName) => query .where(tableName ? `${tableName}_id` : 'id', '<', startFrom) .limit(howMany); module.exports = { knex, insertWorkMetadata, getWorkMetadata, removeWork, getWorksBy, paginateResults, }; ================================================ FILE: src/server/database/schema.js ================================================ /* eslint-disable no-console */ const { knex } = require('./db'); const createSchema = () => knex.schema .createTable('t_circle', (table) => { table.increments(); table.string('name').notNullable(); }) .createTable('t_work', (table) => { table.increments(); table.string('dir').notNullable(); table.string('title').notNullable(); table.integer('circle_id').notNullable(); table.boolean('nsfw').notNullable(); table.foreign('circle_id').references('id').inTable('t_circle'); }) .createTable('t_tag', (table) => { table.increments(); table.string('name').notNullable(); }) .createTable('t_va', (table) => { table.increments(); table.string('name').notNullable(); }) .createTable('r_tag_work', (table) => { table.integer('tag_id'); table.integer('work_id'); table.foreign('tag_id').references('id').inTable('t_tag'); table.foreign('work_id').references('id').inTable('t_work'); table.primary(['tag_id', 'work_id']); }) .createTable('r_va_work', (table) => { table.integer('va_id'); table.integer('work_id'); table.foreign('va_id').references('id').inTable('t_va'); table.foreign('work_id').references('id').inTable('t_work'); table.primary(['va_id', 'work_id']); }) .then(() => { console.log(' * Schema created.'); }) .catch((err) => { // ew if (err.toString().indexOf('table `t_circle` already exists') !== -1) { console.log(' * Schema already exists.'); } else { throw new Error(` ! ERROR while creating schema: ${err}`); } }); module.exports = { createSchema }; ================================================ FILE: src/server/filesystem/scanner.js ================================================ /* eslint-disable no-console */ const fs = require('fs'); const path = require('path'); const fetch = require('node-fetch'); const db = require('../database/db'); const { getFolderList, deleteCoverImageFromDisk, saveCoverImageToDisk, throttlePromises } = require('./utils'); const { createSchema } = require('../database/schema'); const scrapeWorkMetadata = require('../hvdb'); const config = require('../../../config.json'); /** * Takes a single folder, fetches metadata and adds it to the database. * @param {*} id Work id. * @param {*} folder Directory name (relative). */ const processFolder = (id, folder) => db.knex('t_work') .where('id', '=', id) .count() .first() .then((res) => { const count = res['count(*)']; if (count) { // Already in database. // console.log(` * ${folder} already in database, skipping.`); return 'skipped'; } // New folder. console.log(` * Found new folder: ${folder}`); const rjcode = (`000000${id}`).slice(-6); // zero-pad to 6 digits console.log(` -> [RJ${rjcode}] Fetching metadata from HVDB...`); return scrapeWorkMetadata(id) .then((metadata) => { console.log(` -> [RJ${rjcode}] Fetched metadata! Adding to database...`); // TODO: cover download could be in parallel with metadata fetch. Haven't // done it because if metadata fails, cover is useless. Consider for later. console.log(` -> [RJ${rjcode}] Downloading cover image...`); fetch(`https://hvdb.me/WorkImages/RJ${rjcode}.jpg`) .then((imageRes) => { if (!imageRes.ok) { throw new Error(imageRes.statusText); } return imageRes; }) .then((imageRes) => { saveCoverImageToDisk(imageRes.body, rjcode) .then(() => console.log(` -> [RJ${rjcode}] Cover image downloaded!`)); }) .catch((err) => { console.log(` ! [RJ${rjcode}] Failed to download cover image: ${err.message}`); }); // eslint-disable-next-line no-param-reassign metadata.dir = folder; return db.insertWorkMetadata(metadata) .then(console.log(` -> [RJ${rjcode}] Finished adding to the database!`)) .then(() => 'added'); }) .catch((err) => { console.log(` ! [RJ${rjcode}] Failed to fetch metadata from HVDB: ${err.message}`); return 'failed'; }); }); const performCleanup = () => { console.log(' * Looking for folders to clean up...'); return db.knex('t_work') .select('id', 'dir') .then((works) => { const promises = works.map(work => new Promise((resolve, reject) => { if (!fs.existsSync(path.join(config.rootDir, work.dir))) { console.warn(` ! ${work.dir} is missing from filesystem. Removing from database...`); db.removeWork(work.id) .then((result) => { const rjcode = (`000000${work.id}`).slice(-6); // zero-pad to 6 digits deleteCoverImageFromDisk(rjcode) .catch(() => console.log(` -> [RJ${rjcode}] Failed to delete cover image.`)) .then(() => resolve(result)); }) .catch(err => reject(err)); } else { resolve(); } })); return Promise.all(promises); }); }; const performScan = () => { fs.mkdir(path.join(config.rootDir, 'Images'), (direrr) => { if (direrr && direrr.code !== 'EEXIST') { console.error(` ! ERROR while trying to create Images folder: ${direrr.code}`); process.exit(1); } createSchema() .then(() => performCleanup()) .catch((err) => { console.error(` ! ERROR while performing cleanup: ${err.message}`); process.exit(1); }) .then(async () => { console.log(' * Finished cleanup. Starting scan...'); const promises = []; try { for await (const folder of getFolderList()) { const id = folder.match(/RJ(\d{6})/)[1]; promises.push(() => processFolder(id, folder)); } } catch (err) { console.error(` ! ERROR while trying to get folder list: ${err.message}`); process.exit(1); } throttlePromises(config.maxParallelism, promises) .then((results) => { const counts = { added: 0, failed: 0, skipped: 0, }; // eslint-disable-next-line no-return-assign results.forEach(x => counts[x] += 1); console.log(` * Finished scan. Added ${counts.added}, skipped ${counts.skipped} and failed to add ${counts.failed} works.`); db.knex.destroy(); }) .catch((err) => { console.error(` ! ERROR while performing scan: ${err.message}`); process.exit(1); }); }) .catch((err) => { console.error(` ! ERROR while creating database schema: ${err.message}`); process.exit(1); }); }); }; performScan(); ================================================ FILE: src/server/filesystem/utils.js ================================================ const fs = require('fs'); const path = require('path'); const recursiveReaddir = require('recursive-readdir'); const { orderBy } = require('natural-orderby'); const config = require('../../../config.json'); /** * Returns list of playable tracks in a given folder. Track is an object * containing 'title', 'subtitle' and 'hash'. * @param {Number} id Work identifier. Currently, RJ/RE code. * @param {String} dir Work directory (relative). */ const getTrackList = (id, dir) => recursiveReaddir( path.join(config.rootDir, dir), ) .then((files) => { // Filter out any files not matching these extensions const filteredFiles = files.filter((file) => { const ext = path.extname(file); return (ext === '.mp3' || ext === '.ogg' || ext === '.opus' || ext === '.wav' || ext === '.flac' || ext === '.webm' || ext === '.mp4'); }); // Sort by folder and title const sortedFiles = orderBy(filteredFiles.map((file) => { const shortFilePath = file.replace(path.join(config.rootDir, dir, '/'), ''); const dirName = path.dirname(shortFilePath); return { title: path.basename(file), subtitle: dirName === '.' ? null : dirName, }; }), [v => v.subtitle, v => v.title]); // Add hash to each file const sortedHashedFiles = sortedFiles.map( (file, index) => ({ title: file.title, subtitle: file.subtitle, hash: `${id}/${index}`, }), ); return sortedHashedFiles; }) .catch((err) => { throw new Error(`Failed to get tracklist from disk: ${err}`); }); /** * Returns list of directory names (relative) that contain an RJ code. */ async function* getFolderList(current = '', depth = 0) { const folders = await fs.promises.readdir(path.join(config.rootDir, current)); for (const folder of folders) { const absolutePath = path.resolve(config.rootDir, current, folder); const relativePath = path.join(current, folder); // eslint-disable-next-line no-await-in-loop if ((await fs.promises.stat(absolutePath)).isDirectory()) { if (folder.match(/RJ\d{6}/)) { // Found a work folder, don't go any deeper. yield relativePath; } else if (depth + 1 < config.scannerMaxRecursionDepth) { // Found a folder that's not a work folder, go inside if allowed. yield* getFolderList(relativePath, depth + 1); } } } } /** * Deletes a work's cover image from disk. * @param {String} rjcode Work RJ code (only the 6 digits, zero-padded). */ const deleteCoverImageFromDisk = rjcode => new Promise((resolve, reject) => { fs.unlink(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`), (err) => { if (err) { reject(err); } else { resolve(); } }); }); /** * Saves cover image to disk. * @param {ReadableStream} stream Image data stream. * @param {String} rjcode Work RJ code (only the 6 digits, zero-padded). */ const saveCoverImageToDisk = (stream, rjcode) => new Promise((resolve, reject) => { // TODO: don't assume image is a jpg? try { stream.pipe( fs.createWriteStream(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`)) .on('close', () => resolve()), ); } catch (err) { reject(err); } }); /** * Runs an array of Promise returning functions at a specified rate * @param {Number} the maximum number of unresolved promises that may exist at a given time * @param {Array} an array of promise-creating functions */ const throttlePromises = (maxPending, asyncFuncs) => { return new Promise((resolve, reject) => { let numPending = 0; let nextFuncId = 0; const promisedValues = []; (function check() { if (nextFuncId >= asyncFuncs.length) { // All promises created if (numPending == 0) resolve(promisedValues); // All promises fulfilled return; } while (numPending < maxPending) { // Room for creating promise(s) numPending++; const thisFuncId = nextFuncId++; asyncFuncs[thisFuncId]().then(value => { promisedValues[thisFuncId] = value; numPending--; check(); }).catch(reject); } })(); }); }; module.exports = { getTrackList, getFolderList, deleteCoverImageFromDisk, saveCoverImageToDisk, throttlePromises }; ================================================ FILE: src/server/hvdb.js ================================================ const fetch = require('node-fetch'); const htmlparser = require('htmlparser2'); /** * Generates a hash integer from a given string. Hopefully only temporary until * reshnix exposes VA ids for scraping. * @param {String} name */ const hashNameIntoInt = (name) => { let hash = ''; for (let i = 0; i < name.length; i += 1) { const char = name.charCodeAt(i); // eslint-disable-next-line no-bitwise hash = ((hash << 5) - hash) + char; } // eslint-disable-next-line no-bitwise hash |= 0; hash = Math.abs(Math.round(hash / 1000)); return hash; }; /** * Scrapes work metadata from public HVDB page HTML. * @param {Integer} id Work id. */ const scrapeWorkMetadata = id => new Promise((resolve, reject) => { const url = `https://hvdb.me/Dashboard/WorkDetails/${id}`; fetch(url) .then((res) => { if (!res.ok) { reject(new Error(`Couldn't fetch work page HTML, received ${res.statusText}`)); } return res; }) .then(res => res.text()) .then((res) => { const work = { id, tags: [], vas: [] }; let writeTo; const parser = new htmlparser.Parser({ onopentag: (name, attrs) => { if (name === 'input') { if (attrs.id === 'Name') { work.title = attrs.value; } else if (attrs.name === 'SFW') { work.nsfw = attrs.value === 'false'; } } if (name === 'a') { if (attrs.href.indexOf('CircleWorks') !== -1) { work.circle = { id: attrs.href.substring(attrs.href.lastIndexOf('/') + 1), }; writeTo = 'circle.name'; } else if (attrs.href.indexOf('TagWorks') !== -1) { work.tags.push({ id: attrs.href.substring(attrs.href.lastIndexOf('/') + 1), }); writeTo = 'tag.name'; } else if (attrs.href.indexOf('CVWorks') !== -1) { work.vas.push({ id: hashNameIntoInt(attrs.href), // TODO: RESHNIX!!! }); writeTo = 'va.name'; } } }, onclosetag: () => { writeTo = null; }, ontext: (text) => { switch (writeTo) { case 'circle.name': work.circle.name = text; break; case 'tag.name': work.tags[work.tags.length - 1].name = text; break; case 'va.name': work.vas[work.vas.length - 1].name = text; break; default: } }, }, { decodeEntities: true }); parser.write(res); parser.end(); if (work.tags.length === 0 && work.vas.length === 0) { reject(new Error('Couldn\'t parse data from HVDB work page.')); } else { resolve(work); } }); }); module.exports = scrapeWorkMetadata; ================================================ FILE: src/server/index.js ================================================ const crypto = require('crypto'); const path = require('path'); const express = require('express'); const session = require('express-session'); const memorystore = require('memorystore'); const routes = require('./routes'); const { router: authRoutes, authenticator } = require('./auth'); const app = express(); const MemoryStore = memorystore(session); // For handling authentication POST app.use(express.urlencoded({ extended: false })); // Use session middleware app.use(session({ cookie: { maxAge: 24 * 60 * 60 * 1000 }, resave: false, saveUninitialized: false, secret: process.env.SECRET || crypto.randomBytes(32).toString('hex'), store: new MemoryStore({ checkPeriod: 24 * 60 * 60 * 1000 }), })); // Use authenticator middleware app.use(authenticator); // Serve webapp routes app.get(/^\/(player|work|circle|tag|va)s?\/(\d+)?$/, (req, res, next) => { res.sendFile(path.join(__dirname, '../../dist', 'index.html')); }); // Serve static files from 'dist' folder app.use(express.static('dist')); // If 404'd, serve from 'static' folder app.use('/static', express.static('static')); // Expose API routes app.use('/api', routes); // Expose authentication route app.use('/auth', authRoutes); // Start server app.listen(process.env.PORT || 8888, () => { // eslint-disable-next-line no-console console.log(`Express listening on http://localhost:${process.env.PORT || 8888}`); }); ================================================ FILE: src/server/routes.js ================================================ const path = require('path'); const express = require('express'); const db = require('./database/db'); const { getTrackList } = require('./filesystem/utils'); const config = require('../../config.json'); const router = express.Router(); // GET work cover image router.get('/cover/:id', (req, res, next) => { const rjcode = (`000000${req.params.id}`).slice(-6); res.sendFile(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`), (err) => { if (err) { res.sendFile(path.join(__dirname, '..', '..', 'static', 'no-image.jpg'), (err2) => { if (err2) { next(err2); } }); } }); }); // GET work metadata router.get('/work/:id', (req, res, next) => { db.getWorkMetadata(req.params.id) .then(work => res.send(work)) .catch(err => next(err)); }); // GET track list in work folder router.get('/tracks/:id', (req, res, next) => { db.knex('t_work') .select('dir') .where('id', '=', req.params.id) .first() .then((dir) => { getTrackList(req.params.id, dir.dir) .then(tracks => res.send(tracks)); }) .catch(err => next(err)); }); // GET (stream) a specific track from work folder router.get('/stream/:id/:index', (req, res, next) => { db.knex('t_work') .select('dir') .where('id', '=', req.params.id) .first() .then((dir) => { getTrackList(req.params.id, dir.dir) .then((tracks) => { const track = tracks[req.params.index]; res.sendFile(path.join(config.rootDir, dir.dir, track.subtitle || '', track.title)); }) .catch(err => next(err)); }); }); // GET list of work ids router.get('/works/:fromId?', (req, res, next) => { db.paginateResults(db.getWorksBy(), req.params.fromId || 999999, config.worksPerPage) .then(results => res.send(results)) .catch(err => next(err)); }); // GET name of a circle/tag/VA router.get('/get-name/:field/:id', (req, res, next) => { if (req.params.field === 'undefined') { return res.send(null); } return db.knex(`t_${req.params.field}`) .select('name') .where('id', '=', req.params.id) .first() .then(name => res.send(name.name)) .catch(err => next(err)); }); // GET list of work ids, restricted by circle/tag/VA router.get('/:field/:id/:fromId?', (req, res, next) => { db.paginateResults( db.getWorksBy(req.params.id, req.params.field), req.params.fromId || 999999, config.worksPerPage, ) .then(results => res.send(results)) .catch(err => next(err)); }); // GET list of circles/tags/VAs router.get('/(:field)s/', (req, res, next) => { db.knex(`t_${req.params.field}`) .select('id', 'name') .orderBy('name', 'asc') .then(list => res.send(list)) .catch(err => next(err)); }); module.exports = router; ================================================ FILE: static/auth.html ================================================ Kikoeru

Please authenticate.

================================================ FILE: static/index.html ================================================ Kikoeru
================================================ FILE: static/manifest.json ================================================ { "name": "Kikoeru", "icons": [ { "src": "/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/android-chrome-512x512.png", "sizes": "512x512", "type": "image/png" } ], "theme_color": "#ffffff", "background_color": "#ffffff", "display": "standalone", "start_url": "/", "orientation": "portrait-primary" } ================================================ FILE: webpack.config.js ================================================ const path = require('path'); const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const production = process.argv[process.argv.indexOf('--mode') + 1] === 'production'; module.exports = { entry: ['babel-polyfill', './src/client/index.jsx'], output: { path: path.join(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js', }, module: { rules: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\.(css|less)$/, use: [ { loader: MiniCssExtractPlugin.loader, options: { hmr: !production }, }, 'css-loader', 'less-loader', ], }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000', }, ], }, resolve: { extensions: ['*', '.js', '.jsx'], alias: { inferno: production ? 'inferno' : 'inferno/dist/index.dev.esm.js', // 'uikit-util': 'uikit/src/js/util/index', // uikit: 'uikit/src/js/uikit', }, }, devServer: { host: '0.0.0.0', port: 3000, open: true, historyApiFallback: true, proxy: { '/api': 'http://localhost:8888', }, }, plugins: [ new OptimizeCssAssetsPlugin(), new MiniCssExtractPlugin(), new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './static/index.html', }), ], optimization: { mangleWasmImports: true, splitChunks: { chunks: 'async', }, }, };