[
  {
    "path": ".babelrc",
    "content": "{\n  \"presets\": [\n    \"@babel/preset-env\"\n  ],\n  \"plugins\": [\n    \"@babel/plugin-proposal-class-properties\",\n    \"@babel/plugin-syntax-jsx\",\n    [\"babel-plugin-inferno\", {\"imports\": true}]\n  ]\n}\n"
  },
  {
    "path": ".eslintrc.json",
    "content": "{\n  \"parser\": \"babel-eslint\",\n  \"extends\": [\"airbnb\"],\n  \"env\": {\n    \"browser\": true,\n    \"node\": true\n  },\n  \"rules\": {\n    \"import/no-extraneous-dependencies\": [ 2, {\"devDependencies\": true}],\n    \"no-restricted-syntax\": [0, \"iterators/generators\"],\n    \"react/react-in-jsx-scope\": 0,\n    \"react/prop-types\": 0\n  }\n}\n"
  },
  {
    "path": ".gitignore",
    "content": ".vscode\nnode_modules\ndist\ndb.sqlite3\n*.log\n\n"
  },
  {
    "path": "LICENSE.md",
    "content": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<https://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this\nlicense document, but changing it is not allowed.\n\n### Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom\nto share and change all versions of a program--to make sure it remains\nfree software for all its users. We, the Free Software Foundation, use\nthe GNU General Public License for most of our software; it applies\nalso to any other work released this way by its authors. You can apply\nit to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you\nhave certain responsibilities if you distribute copies of the\nsoftware, or if you modify it: responsibilities to respect the freedom\nof others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the\nmanufacturer can do so. This is fundamentally incompatible with the\naim of protecting users' freedom to change the software. The\nsystematic pattern of such abuse occurs in the area of products for\nindividuals to use, which is precisely where it is most unacceptable.\nTherefore, we have designed this version of the GPL to prohibit the\npractice for those products. If such problems arise substantially in\nother domains, we stand ready to extend this provision to those\ndomains in future versions of the GPL, as needed to protect the\nfreedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish\nto avoid the special danger that patents applied to a free program\ncould make it effectively proprietary. To prevent this, the GPL\nassures that patents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n### TERMS AND CONDITIONS\n\n#### 0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds\nof works, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of\nan exact copy. The resulting work is called a \"modified version\" of\nthe earlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user\nthrough a computer network, with no transfer of a copy, is not\nconveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\" to\nthe extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n#### 1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work for\nmaking modifications to it. \"Object code\" means any non-source form of\na work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users can\nregenerate automatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same\nwork.\n\n#### 2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not convey,\nwithout conditions so long as your license otherwise remains in force.\nYou may convey covered works to others for the sole purpose of having\nthem make modifications exclusively for you, or provide you with\nfacilities for running those works, provided that you comply with the\nterms of this License in conveying all material for which you do not\ncontrol copyright. Those thus making or running the covered works for\nyou must do so exclusively on your behalf, under your direction and\ncontrol, on terms that prohibit them from making any copies of your\ncopyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the\nconditions stated below. Sublicensing is not allowed; section 10 makes\nit unnecessary.\n\n#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such\ncircumvention is effected by exercising rights under this License with\nrespect to the covered work, and you disclaim any intention to limit\noperation or modification of the work as a means of enforcing, against\nthe work's users, your or third parties' legal rights to forbid\ncircumvention of technological measures.\n\n#### 4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n#### 5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these\nconditions:\n\n-   a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n-   b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under\n    section 7. This requirement modifies the requirement in section 4\n    to \"keep intact all notices\".\n-   c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy. This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged. This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n-   d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n#### 6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms of\nsections 4 and 5, provided that you also convey the machine-readable\nCorresponding Source under the terms of this License, in one of these\nways:\n\n-   a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n-   b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the Corresponding\n    Source from a network server at no charge.\n-   c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source. This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n-   d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge. You need not require recipients to copy the\n    Corresponding Source along with the object code. If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source. Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n-   e) Convey the object code using peer-to-peer transmission,\n    provided you inform other peers where the object code and\n    Corresponding Source of the work are being offered to the general\n    public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal,\nfamily, or household purposes, or (2) anything designed or sold for\nincorporation into a dwelling. In determining whether a product is a\nconsumer product, doubtful cases shall be resolved in favor of\ncoverage. For a particular product received by a particular user,\n\"normally used\" refers to a typical or common use of that class of\nproduct, regardless of the status of the particular user or of the way\nin which the particular user actually uses, or expects or is expected\nto use, the product. A product is a consumer product regardless of\nwhether the product has substantial commercial, industrial or\nnon-consumer uses, unless such uses represent the only significant\nmode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to\ninstall and execute modified versions of a covered work in that User\nProduct from a modified version of its Corresponding Source. The\ninformation must suffice to ensure that the continued functioning of\nthe modified object code is in no case prevented or interfered with\nsolely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or\nupdates for a work that has been modified or installed by the\nrecipient, or for the User Product in which it has been modified or\ninstalled. Access to a network may be denied when the modification\nitself materially and adversely affects the operation of the network\nor violates the rules and protocols for communication across the\nnetwork.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n#### 7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders\nof that material) supplement the terms of this License with terms:\n\n-   a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n-   b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n-   c) Prohibiting misrepresentation of the origin of that material,\n    or requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n-   d) Limiting the use for publicity purposes of names of licensors\n    or authors of the material; or\n-   e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n-   f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions\n    of it) with contractual assumptions of liability to the recipient,\n    for any liability that these contractual assumptions directly\n    impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions; the\nabove requirements apply either way.\n\n#### 8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your license\nfrom a particular copyright holder is reinstated (a) provisionally,\nunless and until the copyright holder explicitly and finally\nterminates your license, and (b) permanently, if the copyright holder\nfails to notify you of the violation by some reasonable means prior to\n60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n#### 9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or run\na copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n#### 10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n#### 11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims owned\nor controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within the\nscope of its coverage, prohibits the exercise of, or is conditioned on\nthe non-exercise of one or more of the rights that are specifically\ngranted under this License. You may not convey a covered work if you\nare a party to an arrangement with a third party that is in the\nbusiness of distributing software, under which you make payment to the\nthird party based on the extent of your activity of conveying the\nwork, and under which the third party grants, to any of the parties\nwho would receive the covered work from you, a discriminatory patent\nlicense (a) in connection with copies of the covered work conveyed by\nyou (or copies made from those copies), or (b) primarily for and in\nconnection with specific products or compilations that contain the\ncovered work, unless you entered into that arrangement, or that patent\nlicense was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n#### 12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under\nthis License and any other pertinent obligations, then as a\nconsequence you may not convey it at all. For example, if you agree to\nterms that obligate you to collect a royalty for further conveying\nfrom those to whom you convey the Program, the only way you could\nsatisfy both those terms and this License would be to refrain entirely\nfrom conveying the Program.\n\n#### 13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n#### 14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions\nof the GNU General Public License from time to time. Such new versions\nwill be similar in spirit to the present version, but may differ in\ndetail to address new problems or concerns.\n\nEach version is given a distinguishing version number. If the Program\nspecifies that a certain numbered version of the GNU General Public\nLicense \"or any later version\" applies to it, you have the option of\nfollowing the terms and conditions either of that numbered version or\nof any later version published by the Free Software Foundation. If the\nProgram does not specify a version number of the GNU General Public\nLicense, you may choose any version ever published by the Free\nSoftware Foundation.\n\nIf the Program specifies that a proxy can decide which future versions\nof the GNU General Public License can be used, that proxy's public\nstatement of acceptance of a version permanently authorizes you to\nchoose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n#### 15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT\nWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND\nPERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE\nDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR\nCORRECTION.\n\n#### 16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR\nCONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES\nARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT\nNOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR\nLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM\nTO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n#### 17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\n### How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these\nterms.\n\nTo do so, attach the following notices to the program. It is safest to\nattach them to the start of each source file to most effectively state\nthe exclusion of warranty; and each file should have at least the\n\"copyright\" line and a pointer to where the full notice is found.\n\n        <one line to give the program's name and a brief idea of what it does.>\n        Copyright (C) <year>  <name of author>\n\n        This program is free software: you can redistribute it and/or modify\n        it under the terms of the GNU General Public License as published by\n        the Free Software Foundation, either version 3 of the License, or\n        (at your option) any later version.\n\n        This program is distributed in the hope that it will be useful,\n        but WITHOUT ANY WARRANTY; without even the implied warranty of\n        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n        GNU General Public License for more details.\n\n        You should have received a copy of the GNU General Public License\n        along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper\nmail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n        <program>  Copyright (C) <year>  <name of author>\n        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n        This is free software, and you are welcome to redistribute it\n        under certain conditions; type `show c' for details.\n\nThe hypothetical commands \\`show w' and \\`show c' should show the\nappropriate parts of the General Public License. Of course, your\nprogram's commands might be different; for a GUI interface, you would\nuse an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary. For more information on this, and how to apply and follow\nthe GNU GPL, see <https://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your\nprogram into proprietary programs. If your program is a subroutine\nlibrary, you may consider it more useful to permit linking proprietary\napplications with the library. If this is what you want to do, use the\nGNU Lesser General Public License instead of this License. But first,\nplease read <https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img width=\"192\" height=\"192\" src=\"static/android-chrome-192x192.png\" style=\"box-shadow: 0px 3px 8px #000\">\n</p>\nA self-hosted web media player for listening to your DLsite voice works.\n\n## Features\n- Automatically scrapes metadata from HVDB\n- Browse works by circle, tag or VA\n- Queue functionality: mix and match tracks from many different works, in whichever order you want\n\n## Quick Start\nRequires both Node.js and npm installed in your system to run. Assuming you've downloaded from the releases page:\n```bash\n# Install dependencies\nnpm install --only=prod\n\n# Change `rootDir` in `config.json` to the\n# directory where you keep your voice works.\n\n# Each folder must have an RJ code somewhere\n# in its name for the scanner to detect it.\n\n# Scan works into the database\nnpm run scan\n\n# Start the server\nnpm start\n\n# App is now available at http://0.0.0.0:8888\n```\n\nIf you instead cloned this repository or just want more details, read below:\n## Instructions\n### Build from source\n```bash\n# Install dependencies\nnpm install\n\n# Build app bundle\nnpm run build\n\n# Start the production server\nnpm start\n\n# App is now available at http://0.0.0.0:8888\n```\n\n### Configuration\n#### Media scanner\nYou 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.\n\n**NOTE:** Even if you're on Windows, you still need to use forward slashes when specifying `rootDir`. For example:\n```json\n{\n  \"rootDir\": \"D:/Downloads/Voice\",\n  \"worksPerPage\": 12\n}\n```\n\nAfter this is done, you may run the initial scan:\n```bash\nnpm run scan\n```\nThis 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.\n\nSubsequent runs of the scan command will do two things:\n- Look for new works and add them to the database\n- Remove works which have been deleted from disk since last scan\n\nIt 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/`:\n```bash\n# OK - This work will be detected correctly:\n/mnt/Voice/[Atelier Honey] 雨恋女の子守唄 (RJ136105)/\n\n# OK - All the folders will be detected as part of the same work:\n/mnt/Voice/RJ130297/mp3/ノイズ有/\n/mnt/Voice/RJ130297/mp3/ノイズ無（推奨）/\n/mnt/Voice/RJ130297/wav/ノイズ有/\n/mnt/Voice/RJ130297/wav/ノイズ無（推奨）/\n\n# OK - As long as `scannerMaxRecursionDepth` is at least 2:\n/mnt/Voice/Atelier Honey/[RJ136105] 雨恋女の子守唄/\n\n# OK - As long as `scannerMaxRecursionDepth` is at least 3:\n/mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/1-帰り道mp3/\n/mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/2-お風呂場のおはなしmp3/\n/mnt/Voice/SFW/桃色CODE/【初夏耳かき】道草屋 芹7 ゆうがた【湯船怪談】(RJ253947)/3-夕焼け花火と耳掃除mp3/\n\n# FAIL - This work won't be detected because there's no RJ code:\n/mnt/Voice/雨恋女の子守唄/\n```\n\n#### Password protection\nIf 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`).\n\n## Disclaimer\nAt the moment, although this works well enough for regular usage, you can expect to find small quirks and bugs.\n\nThis was developed on macOS and tested on Chrome for Android. It should run on Linux. I have no clue about Windows.\n"
  },
  {
    "path": "config.json",
    "content": "{\n  \"rootDir\": \"/mnt/Media/Voice\",\n  \"password\": false,\n  \"scannerMaxRecursionDepth\": 2,\n  \"worksPerPage\": 12,\n  \"maxParallelism\": 8\n}\n"
  },
  {
    "path": "nodemon.json",
    "content": "{\n  \"watch\": [\"src/server/\"]\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"kikoeru\",\n  \"version\": \"0.3.0\",\n  \"description\": \"Web media player, specifically for voice works.\",\n  \"main\": \"src/server/index.jsx\",\n  \"scripts\": {\n    \"build\": \"webpack --mode production\",\n    \"start\": \"cross-env NODE_ENV=production node src/server/index.js\",\n    \"client\": \"webpack-dev-server --mode development --devtool inline-source-map --hot\",\n    \"server\": \"nodemon src/server/index.js\",\n    \"dev\": \"concurrently \\\"npm run server\\\" \\\"npm run client\\\"\",\n    \"profile\": \"webpack --mode production --profile --json > webpack-stats.json\",\n    \"scan\": \"node ./src/server/filesystem/scanner.js\"\n  },\n  \"author\": \"nortonandrews\",\n  \"license\": \"GPL-3.0-or-later\",\n  \"dependencies\": {\n    \"cross-env\": \"^5.2.0\",\n    \"express\": \"^4.17.1\",\n    \"express-session\": \"^1.16.2\",\n    \"htmlparser2\": \"^3.10.1\",\n    \"knex\": \"^0.19.5\",\n    \"memorystore\": \"^1.6.1\",\n    \"natural-orderby\": \"^2.0.3\",\n    \"node-fetch\": \"^2.6.0\",\n    \"recursive-readdir\": \"^2.2.2\",\n    \"sqlite3\": \"^4.0.9\"\n  },\n  \"devDependencies\": {\n    \"history\": \"^4.9.0\",\n    \"inferno\": \"^7\",\n    \"less\": \"^3.9.0\",\n    \"redux\": \"^4.0.4\",\n    \"uikit\": \"^3.1.6\",\n    \"@babel/core\": \"^7.5.4\",\n    \"@babel/plugin-proposal-class-properties\": \"^7.5.0\",\n    \"@babel/plugin-syntax-jsx\": \"^7.2.0\",\n    \"@babel/preset-env\": \"^7.5.4\",\n    \"babel-eslint\": \"^10.0.2\",\n    \"babel-loader\": \"^8.0.6\",\n    \"babel-plugin-inferno\": \"^6.0.5\",\n    \"babel-polyfill\": \"^6.26.0\",\n    \"clean-webpack-plugin\": \"^3.0.0\",\n    \"concurrently\": \"^4.1.1\",\n    \"css-loader\": \"^3.0.0\",\n    \"eslint\": \"^6.0.1\",\n    \"eslint-config-airbnb\": \"^17.1.1\",\n    \"eslint-config-inferno-app\": \"^7.0.2\",\n    \"eslint-plugin-import\": \"^2.18.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.2.3\",\n    \"eslint-plugin-react\": \"^7.14.2\",\n    \"file-loader\": \"^4.0.0\",\n    \"html-webpack-plugin\": \"^3.2.0\",\n    \"inferno-component\": \"^7\",\n    \"inferno-create-element\": \"^7\",\n    \"inferno-redux\": \"^7.1.13\",\n    \"inferno-router\": \"^7\",\n    \"less-loader\": \"^5.0.0\",\n    \"mini-css-extract-plugin\": \"^0.7.0\",\n    \"nodemon\": \"^1.19.1\",\n    \"optimize-css-assets-webpack-plugin\": \"^5.0.3\",\n    \"redux-starter-kit\": \"^0.5.1\",\n    \"style-loader\": \"^0.23.1\",\n    \"url-loader\": \"^2.0.1\",\n    \"webpack\": \"^4.35.3\",\n    \"webpack-cli\": \"^3.3.5\",\n    \"webpack-dev-server\": \"^3.7.2\"\n  }\n}\n"
  },
  {
    "path": "src/client/components/AudioElement.jsx",
    "content": "import { Component, createRef } from 'inferno';\nimport { connect } from 'inferno-redux';\n\nconst mapStateToProps = state => ({\n  playing: state.playing,\n  progress: state.progress,\n  seek: state.seek,\n  source: state.queue[state.queueIndex]\n    ? `/api/stream/${state.queue[state.queueIndex].hash}` : null,\n  queue: state.queue,\n  queueIndex: state.queueIndex,\n});\n\nclass AudioElement extends Component {\n  eventHandlers = {\n    play: () => {\n      const { dispatch } = this.props;\n      dispatch({ type: 'PLAY' });\n\n      this.updateMetadata();\n    },\n    pause: () => {\n      const { dispatch } = this.props;\n      dispatch({ type: 'PAUSE' });\n    },\n    ended: () => {\n      const { dispatch } = this.props;\n      dispatch({ type: 'NEXT_TRACK' });\n    },\n    timeUpdate: (evt) => {\n      const { dispatch } = this.props;\n      dispatch({\n        type: 'TIME_UPDATE',\n        payload: evt.target.currentTime / evt.target.duration * 100,\n      });\n    },\n  };\n\n  constructor(props) {\n    super(props);\n    this.audioRef = createRef();\n  }\n\n  componentDidMount() {\n    // Add event listeners.\n    this.audioRef.current.addEventListener('play', this.eventHandlers.play);\n    this.audioRef.current.addEventListener('pause', this.eventHandlers.pause);\n    this.audioRef.current.addEventListener('ended', this.eventHandlers.ended);\n    this.audioRef.current.addEventListener('timeupdate', this.eventHandlers.timeUpdate);\n  }\n\n  shouldComponentUpdate(nextProps) {\n    const {\n      playing, seek, source,\n    } = this.props;\n\n    // Started playing, don't update.\n    if (!playing && nextProps.playing) {\n      this.audioRef.current.play();\n    }\n\n    // Paused, don't update.\n    if (playing && !nextProps.playing) {\n      this.audioRef.current.pause();\n    }\n\n    // Seeked, don't update.\n    if (seek !== nextProps.seek) {\n      this.audioRef.current.currentTime = nextProps.seek * 0.01 * this.audioRef.current.duration;\n    }\n\n    // Changed source, update component.\n    if (source !== nextProps.source) {\n      return true; // TODO: maybe just update source property and not re-render?\n    }\n\n    return false;\n  }\n\n  componentWillUnmount() {\n    // Remove event listeners.\n    this.audioRef.current.removeEventListener('play', this.eventHandlers.play);\n    this.audioRef.current.removeEventListener('pause', this.eventHandlers.pause);\n    this.audioRef.current.removeEventListener('ended', this.eventHandlers.ended);\n    this.audioRef.current.removeEventListener('timeupdate', this.eventHandlers.timeUpdate);\n  }\n\n  updateMetadata() {\n    const { dispatch, queue, queueIndex } = this.props;\n    const { hash } = queue[queueIndex];\n    const id = hash.substring(0, hash.lastIndexOf('/'));\n\n    // TODO: this fetch causes the notification to show no metadata for a second\n    // while it fetches, consider keeping this saved client-side somewhere\n    fetch(`/api/work/${id}`)\n      .then(res => res.json())\n      .then((metadata) => {\n        if ('mediaSession' in navigator) {\n          navigator.mediaSession.metadata = new MediaMetadata({\n            title: queue[queueIndex].title,\n            artist: metadata.circle.name,\n            album: metadata.title,\n            artwork: [\n              { src: `/api/cover/${id}`, type: 'image/jpeg' },\n            ],\n          });\n\n          const prev = queueIndex === 0 ? null : () => dispatch({ type: 'PREVIOUS_TRACK' });\n          const next = queueIndex === queue.length - 1 ? null : () => dispatch({ type: 'NEXT_TRACK' });\n\n          navigator.mediaSession.setActionHandler('previoustrack', prev);\n          navigator.mediaSession.setActionHandler('nexttrack', next);\n        }\n      })\n      .catch((err) => {\n        throw new Error(`Failed to fetch /api/work/${id}: ${err}`);\n      });\n  }\n\n  render() {\n    const { playing, source } = this.props;\n\n    if (this.audioRef.current) {\n      if (source) {\n        this.audioRef.current.src = source;\n        this.audioRef.current.load();\n\n        if (playing) {\n          this.audioRef.current.play();\n        }\n      }\n    }\n\n    return (\n      // eslint-disable-next-line jsx-a11y/media-has-caption\n      <audio id=\"audio-element\" ref={this.audioRef}>\n        {source ? <source src={source} /> : null}\n      </audio>\n    );\n  }\n}\n\nexport default connect(mapStateToProps)(AudioElement);\n"
  },
  {
    "path": "src/client/components/ErrorBoundary.jsx",
    "content": "// TODO: this entire thing is not being used at the moment, test later\nimport { Component } from 'inferno';\n\nclass ErrorBoundary extends Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  componentDidCatch(error, info) {\n    // Display fallback UI, log error\n    this.setState({ hasError: true, error, info });\n\n    // eslint-disable-next-line no-console\n    console.error(error, info);\n  }\n\n  render() {\n    const { children } = this.props;\n    const { hasError, error, info } = this.state;\n\n    if (hasError) {\n      return (\n        <div className=\"uk-cover-container\" uk-height-viewport>\n          <div className=\"uk-position-center\">\n            <h2>Something went wrong:</h2>\n            <p>{error}</p>\n            <p className=\"uk-text-meta\">{info}</p>\n          </div>\n        </div>\n      );\n    }\n\n    return children;\n  }\n}\n\nexport default ErrorBoundary;\n"
  },
  {
    "path": "src/client/components/InfiniteScroll.jsx",
    "content": "/**\n * Apologies for this trainwreck. Copied and pasted from\n * https://www.npmjs.com/package/react-infinite-scroll-component\n * with a few small changes because I didn't want to install react-compat.\n */\n\nimport { Component } from 'inferno';\n\nconst ThresholdUnits = {\n  Pixel: 'Pixel',\n  Percent: 'Percent',\n};\n\nconst defaultThreshold = {\n  unit: ThresholdUnits.Percent,\n  value: 0.8,\n};\n\nconst parseThreshold = (scrollThreshold) => {\n  if (typeof scrollThreshold === \"number\") {\n    return {\n      unit: ThresholdUnits.Percent,\n      value: scrollThreshold * 100,\n    };\n  }\n\n  if (typeof scrollThreshold === \"string\") {\n    if (scrollThreshold.match(/^(\\d*(\\.\\d+)?)px$/)) {\n      return {\n        unit: ThresholdUnits.Pixel,\n        value: parseFloat(scrollThreshold),\n      };\n    }\n\n    if (scrollThreshold.match(/^(\\d*(\\.\\d+)?)%$/)) {\n      return {\n        unit: ThresholdUnits.Percent,\n        value: parseFloat(scrollThreshold),\n      };\n    }\n\n    console.warn('scrollThreshold format is invalid. Valid formats: \"120px\", \"50%\"...');\n\n    return defaultThreshold;\n  }\n\n  console.warn('scrollThreshold should be string or number');\n\n  return defaultThreshold;\n}\n\n// https://remysharp.com/2010/07/21/throttling-function-calls\nconst throttle = (fn, threshhold, scope) => {\n  threshhold || (threshhold = 250);\n  let last;\n  let deferTimer;\n  return function () {\n    const context = scope || this;\n\n    const now = +new Date();\n    let args = arguments;\n    if (last && now < last + threshhold) {\n      // hold on to it\n      clearTimeout(deferTimer);\n      deferTimer = setTimeout(() => {\n        last = now;\n        fn.apply(context, args);\n      }, threshhold);\n    } else {\n      last = now;\n      fn.apply(context, args);\n    }\n  };\n};\n\nclass InfiniteScroll extends Component {\n  constructor(props) {\n    super();\n    this.state = {\n      showLoader: false,\n      lastScrollTop: 0,\n      actionTriggered: false,\n      pullToRefreshThresholdBreached: false,\n    };\n    // variables to keep track of pull down behaviour\n    this.startY = 0;\n    this.currentY = 0;\n    this.dragging = false;\n    // will be populated in componentDidMount\n    // based on the height of the pull down element\n    this.maxPullDownDistance = 0;\n\n    this.onScrollListener = this.onScrollListener.bind(this);\n    this.throttledOnScrollListener = throttle(this.onScrollListener, 150).bind(\n      this,\n    );\n    this.onStart = this.onStart.bind(this);\n    this.onMove = this.onMove.bind(this);\n    this.onEnd = this.onEnd.bind(this);\n    this.getScrollableTarget = this.getScrollableTarget.bind(this);\n  }\n\n  componentDidMount() {\n    this._scrollableNode = this.getScrollableTarget();\n    this.el = this.props.height\n      ? this._infScroll\n      : this._scrollableNode || window;\n    this.el.addEventListener('scroll', this.throttledOnScrollListener);\n\n    if (\n      typeof this.props.initialScrollY === 'number'\n      && this.el.scrollHeight > this.props.initialScrollY\n    ) {\n      this.el.scrollTo(0, this.props.initialScrollY);\n    }\n\n    if (this.props.pullDownToRefresh) {\n      this.el.addEventListener('touchstart', this.onStart);\n      this.el.addEventListener('touchmove', this.onMove);\n      this.el.addEventListener('touchend', this.onEnd);\n\n      this.el.addEventListener('mousedown', this.onStart);\n      this.el.addEventListener('mousemove', this.onMove);\n      this.el.addEventListener('mouseup', this.onEnd);\n\n      // get BCR of pullDown element to position it above\n      this.maxPullDownDistance = this._pullDown.firstChild.getBoundingClientRect().height;\n      this.forceUpdate();\n\n      if (typeof this.props.refreshFunction !== 'function') {\n        throw new Error(\n          `Mandatory prop \"refreshFunction\" missing.\n          Pull Down To Refresh functionality will not work\n          as expected. Check README.md for usage'`,\n        );\n      }\n    }\n  }\n\n  componentWillUnmount() {\n    this.el.removeEventListener('scroll', this.throttledOnScrollListener);\n\n    if (this.props.pullDownToRefresh) {\n      this.el.removeEventListener('touchstart', this.onStart);\n      this.el.removeEventListener('touchmove', this.onMove);\n      this.el.removeEventListener('touchend', this.onEnd);\n\n      this.el.removeEventListener('mousedown', this.onStart);\n      this.el.removeEventListener('mousemove', this.onMove);\n      this.el.removeEventListener('mouseup', this.onEnd);\n    }\n  }\n\n  componentWillReceiveProps(props) {\n    // do nothing when dataLength and key are unchanged\n    if (this.props.key === props.key && this.props.dataLength === props.dataLength) return;\n\n    // update state when new data was sent in\n    this.setState({\n      showLoader: false,\n      actionTriggered: false,\n      pullToRefreshThresholdBreached: false,\n    });\n  }\n\n  getScrollableTarget() {\n    if (this.props.scrollableTarget instanceof HTMLElement) return this.props.scrollableTarget;\n    if (typeof this.props.scrollableTarget === 'string') {\n      return document.getElementById(this.props.scrollableTarget);\n    }\n    if (this.props.scrollableTarget === null) {\n      console.warn(`You are trying to pass scrollableTarget but it is null. This might\n        happen because the element may not have been added to DOM yet.\n        See https://github.com/ankeetmaini/react-infinite-scroll-component/issues/59 for more info.\n      `);\n    }\n    return null;\n  }\n\n  onStart(evt) {\n    if (this.state.lastScrollTop) return;\n\n    this.dragging = true;\n    this.startY = evt.pageY || evt.touches[0].pageY;\n    this.currentY = this.startY;\n\n    this._infScroll.style.willChange = 'transform';\n    this._infScroll.style.transition = 'transform 0.2s cubic-bezier(0,0,0.31,1)';\n  }\n\n  onMove(evt) {\n    if (!this.dragging) return;\n    this.currentY = evt.pageY || evt.touches[0].pageY;\n\n    // user is scrolling down to up\n    if (this.currentY < this.startY) return;\n\n    if (this.currentY - this.startY >= this.props.pullDownToRefreshThreshold) {\n      this.setState({\n        pullToRefreshThresholdBreached: true,\n      });\n    }\n\n    // so you can drag upto 1.5 times of the maxPullDownDistance\n    if (this.currentY - this.startY > this.maxPullDownDistance * 1.5) return;\n\n    this._infScroll.style.overflow = 'visible';\n    this._infScroll.style.transform = `translate3d(0px, ${this.currentY\n      - this.startY}px, 0px)`;\n  }\n\n  onEnd(evt) {\n    this.startY = 0;\n    this.currentY = 0;\n\n    this.dragging = false;\n\n    if (this.state.pullToRefreshThresholdBreached) {\n      this.props.refreshFunction && this.props.refreshFunction();\n    }\n\n    requestAnimationFrame(() => {\n      // this._infScroll\n      if (this._infScroll) {\n        this._infScroll.style.overflow = 'inherit';\n        this._infScroll.style.transform = 'none';\n        this._infScroll.style.willChange = 'none';\n      }\n    });\n  }\n\n  isElementAtBottom(target, scrollThreshold = 0.8) {\n    const clientHeight = target === document.body || target === document.documentElement\n      ? window.screen.availHeight\n      : target.clientHeight;\n\n    const threshold = parseThreshold(scrollThreshold);\n\n    if (threshold.unit === ThresholdUnits.Pixel) {\n      return (\n        target.scrollTop + clientHeight >= target.scrollHeight - threshold.value\n      );\n    }\n\n    return (\n      target.scrollTop + clientHeight >= threshold.value / 100 * target.scrollHeight\n    );\n  }\n\n  onScrollListener(event) {\n    if (typeof this.props.onScroll === 'function') {\n      // Execute this callback in next tick so that it does not affect the\n      // functionality of the library.\n      setTimeout(() => this.props.onScroll(event), 0);\n    }\n\n    const target = this.props.height || this._scrollableNode\n      ? event.target\n      : document.documentElement.scrollTop\n        ? document.documentElement\n        : document.body;\n\n    // return immediately if the action has already been triggered,\n    // prevents multiple triggers.\n    if (this.state.actionTriggered) return;\n\n    const atBottom = this.isElementAtBottom(target, this.props.scrollThreshold);\n\n    // call the `next` function in the props to trigger the next data fetch\n    if (atBottom && this.props.hasMore) {\n      this.setState({ actionTriggered: true, showLoader: true });\n      this.props.next();\n    }\n    this.setState({ lastScrollTop: target.scrollTop });\n  }\n\n  render() {\n    const style = {\n      height: this.props.height || 'auto',\n      overflow: 'inherit',\n      WebkitOverflowScrolling: 'touch',\n      ...this.props.style,\n    };\n    const hasChildren = this.props.hasChildren\n      || !!(this.props.children && this.props.children.length);\n\n    // because heighted infiniteScroll visualy breaks\n    // on drag down as overflow becomes visible\n    const outerDivStyle = this.props.pullDownToRefresh && this.props.height\n      ? { overflow: 'inherit' }\n      : {};\n    return (\n      <div style={outerDivStyle}>\n        <div\n          className={`infinite-scroll-component ${this.props.className || ''}`}\n          ref={infScroll => (this._infScroll = infScroll)}\n          style={style}\n        >\n          {this.props.pullDownToRefresh && (\n            <div\n              style={{ position: 'relative' }}\n              ref={pullDown => (this._pullDown = pullDown)}\n            >\n              <div\n                style={{\n                  position: 'absolute',\n                  left: 0,\n                  right: 0,\n                  top: -1 * this.maxPullDownDistance,\n                }}\n              >\n                {!this.state.pullToRefreshThresholdBreached\n                  && this.props.pullDownToRefreshContent}\n                {this.state.pullToRefreshThresholdBreached\n                  && this.props.releaseToRefreshContent}\n              </div>\n            </div>\n          )}\n          {this.props.children}\n          {!this.state.showLoader\n            && !hasChildren\n            && this.props.hasMore\n            && this.props.loader}\n          {this.state.showLoader && this.props.hasMore && this.props.loader}\n          {!this.props.hasMore && this.props.endMessage}\n        </div>\n      </div>\n    );\n  }\n}\n\nexport default InfiniteScroll;\n"
  },
  {
    "path": "src/client/components/NavBar.jsx",
    "content": "import { Link, withRouter } from 'inferno-router';\nimport UIkit from 'uikit';\n\nconst closeOffCanvasNav = () => {\n  const element = document.getElementById('offcanvas-nav');\n  UIkit.offcanvas(element).hide();\n};\n\nconst OffCanvasNav = (props) => {\n  const { location } = props;\n  const path = location.pathname;\n\n  return (\n    <div id=\"offcanvas-nav\" uk-offcanvas=\"mode: reveal; overlay: true; flip: true\">\n      <div className=\"uk-offcanvas-bar uk-flex uk-flex-column\">\n        <ul className=\"uk-nav uk-nav-primary uk-nav-center uk-margin-auto-vertical\">\n          <li className=\"k-logo k-logo-muted\" />\n          <li className=\"uk-nav-header\">Browse</li>\n          <li className={path === '/' ? 'uk-active' : 'uk-parent'}>\n            <Link to=\"/\" onClick={closeOffCanvasNav}>\n              <span className=\"uk-margin-small-right\" uk-icon=\"icon: thumbnails\" />\n              Works\n            </Link>\n          </li>\n\n          <li className={path === '/circles/' ? 'uk-active' : 'uk-parent'}>\n            <Link to=\"/circles/\" onClick={closeOffCanvasNav}>\n              <span className=\"uk-margin-small-right\" uk-icon=\"icon: users\" />\n              Circles\n            </Link>\n          </li>\n\n          <li className={path === '/tags/' ? 'uk-active' : 'uk-parent'}>\n            <Link to=\"/tags/\" onClick={closeOffCanvasNav}>\n              <span className=\"uk-margin-small-right\" uk-icon=\"icon: tag\" />\n              Tags\n            </Link>\n          </li>\n\n          <li className={path === '/vas/' ? 'uk-active' : 'uk-parent'}>\n            <Link to=\"/vas/\" onClick={closeOffCanvasNav}>\n              <span className=\"uk-margin-small-right\" uk-icon=\"icon: microphone\" />\n              VAs\n            </Link>\n          </li>\n        </ul>\n      </div>\n    </div>\n  );\n};\nconst OffCanvasNavWithRouter = withRouter(OffCanvasNav);\n\nconst NavBar = (props) => {\n  const { location } = props;\n  const transparent = location.pathname === '/player/';\n\n  return (\n    <>\n      <div className={`uk-navbar uk-navbar-container uk-navbar-transparent ${transparent ? '' : 'uk-background-secondary'}`} uk-navbar>\n        <div className=\"uk-navbar-left uk-dark\">\n          <div className=\"uk-navbar-item uk-logo\">\n            <span className=\"k-logo\" />\n          </div>\n        </div>\n\n        <div className=\"uk-navbar-right\">\n          <button type=\"button\" className=\"uk-navbar-toggle\" uk-toggle=\"target: #offcanvas-nav\" uk-navbar-toggle-icon />\n          <OffCanvasNavWithRouter />\n        </div>\n      </div>\n    </>\n  );\n};\n\nexport default withRouter(NavBar);\n"
  },
  {
    "path": "src/client/components/PlayerBar.jsx",
    "content": "import { connect } from 'inferno-redux';\nimport { Link } from 'inferno-router';\n\nimport playIcon from '../static/svg/play.svg';\nimport pauseIcon from '../static/svg/pause.svg';\n\nconst mapStateToProps = state => ({\n  playing: state.playing,\n  queue: state.queue,\n  currentlyPlaying: state.queue[state.queueIndex],\n});\n\nconst PlayerBar = (props) => {\n  const {\n    dispatch, playing, queue, currentlyPlaying,\n  } = props;\n\n  // Queue is empty, don't render the player bar.\n  if (queue.length === 0) {\n    return null;\n  }\n\n  return (\n    <>\n      <div style={{ height: '32px' }} />\n      <div className=\"k-player-bar uk-grid-small uk-flex-middle\" uk-grid>\n\n        <div className=\"uk-width-auto\">\n          <img className=\"uk-border-circle\" src={`/api/cover/${currentlyPlaying.id}`} alt=\"Cover\" style={{ 'object-fit': 'cover', width: '40px', height: '40px' }} />\n        </div>\n\n        <div className=\"uk-width-expand\">\n          <Link to=\"/player/\" className=\"uk-link-text uk-link-reset\">\n            <p className=\"uk-margin-remove-bottom uk-text-truncate\">{currentlyPlaying.title}</p>\n            <p className=\"uk-text-meta uk-text-truncate uk-margin-remove-top uk-margin-remove-bottom\">{currentlyPlaying.subtitle}</p>\n          </Link>\n        </div>\n        <div className=\"uk-width-auto\">\n          <button className=\"k-player-button k-button-icon\" type=\"button\" id=\"middle-button\" onClick={() => dispatch({ type: 'TOGGLE_PLAYING' })}>\n            <img src={playing ? pauseIcon : playIcon} width=\"16px\" height=\"16px\" alt=\"Play/pause\" />\n          </button>\n        </div>\n      </div>\n    </>\n  );\n};\n\nexport default connect(mapStateToProps)(PlayerBar);\n"
  },
  {
    "path": "src/client/components/WorkDetails.jsx",
    "content": "import { Link } from 'inferno-router';\n\n// Renders the tag links.\nconst Tags = props => props.tags.map(\n  (tag, index, tags) => (\n    <>\n      <Link to={`/tag/${tag.id}`} className=\"uk-link-muted\">{tag.name}</Link>\n      {index !== tags.length - 1 ? ', ' : ''}\n    </>\n  ),\n);\n\n// Renders the VA badges.\nconst VAs = props => props.vas.map(\n  va => (\n    <Link\n      to={`/va/${va.id}`}\n      className=\"uk-label uk-label-success k-label-link\"\n    >\n      {va.name}\n    </Link>\n  ),\n);\n\n// Renders the work metadata.\nexport default ({ metadata }) => (\n  <div>\n    <div className=\"uk-cover-container\">\n      <Link to={`/work/${metadata.id}`}>\n        <img src={`/api/cover/${metadata.id}`} alt=\"Cover\" />\n      </Link>\n    </div>\n\n    <div className=\"uk-padding-small uk-margin-remove-bottom\">\n      <h3 className=\"uk-margin-remove-bottom\">\n        <Link\n          to={`/work/${metadata.id}`}\n          className=\"uk-link-heading\"\n        >\n          {metadata.title}\n        </Link>\n      </h3>\n\n      <Link\n        to={`/circle/${metadata.circle.id}`}\n        className=\"uk-link uk-link-muted uk-margin-remove-top\"\n      >\n        {metadata.circle.name}\n      </Link>\n\n      <div className=\"uk-margin-top\">\n        <p><Tags tags={metadata.tags} /></p>\n      </div>\n\n      <div className=\"uk-margin-top\">\n        <VAs vas={metadata.vas} />\n      </div>\n    </div>\n  </div>\n);\n"
  },
  {
    "path": "src/client/components/WorkQueue.jsx",
    "content": "import { Component } from 'inferno';\nimport { connect } from 'inferno-redux';\n\nimport UIkit from 'uikit';\n\nconst mapStateToProps = state => ({\n  // Track hash if currently playing a track, else null.\n  currentlyPlayingHash: (state.playing && state.queue[state.queueIndex])\n    ? state.queue[state.queueIndex].hash : null,\n});\n\n// Renders a single row (track) inside the list.\nconst FileTableRow = ({\n  clickHandler, file, index, fileOptions, usePauseIcon,\n}) => (\n  <tr>\n    <td><button type=\"button\" uk-icon={`icon: ${usePauseIcon ? 'refresh' : 'play-circle'}`} className={`uk-button k-button-icon ${usePauseIcon ? 'k-button-active' : ''}`} onClick={evt => clickHandler(evt, index)} /></td>\n    <td>\n      {file.title}\n      <p className=\"uk-text-meta uk-margin-remove-top\">{file.subtitle}</p>\n    </td>\n    <td>\n      <button type=\"button\" uk-icon=\"icon: more-vertical\" className=\"uk-button k-button-icon\" />\n      <div uk-dropdown=\"delay-hide: 0, animation: uk-animation-slide-top-small; pos: bottom-left; mode: click; boundary: #root\">\n        <ul className=\"uk-list uk-list-divider  uk-margin-remove-bottom\">\n          {fileOptions.map(option => <li><button type=\"button\" className=\"uk-button uk-button-text\" onClick={(evt) => { clickHandler(evt, { type: option.type, index }); }}>{option.text}</button></li>)}\n        </ul>\n      </div>\n    </td>\n  </tr>\n);\n\n// Card containing the track list.\nclass WorkQueue extends Component {\n  constructor(props) {\n    super(props);\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick(evt, payload) {\n    const { dispatch, queue } = this.props;\n\n    if (typeof payload === 'number') {\n      // Clicked play on a single track. Add all files to queue and play the one\n      // we clicked on.\n      dispatch({\n        type: 'SET_QUEUE',\n        payload: { queue, index: payload },\n      });\n    } else {\n      if (payload.type === 'EMPTY_QUEUE') {\n        // Clicked on trash icon at top of card (empty queue).\n        dispatch(payload);\n      } else {\n        // Clicked one of the other options (move in queue, delete from queue).\n        dispatch({\n          type: payload.type,\n          payload: { index: payload.index, file: queue[payload.index] },\n        });\n      }\n\n      // Close dropdown.\n      const dropdownElement = evt.srcElement.parentElement.parentElement.parentElement;\n      UIkit.dropdown(dropdownElement).hide();\n    }\n  }\n\n  render() {\n    const {\n      currentlyPlayingHash, queue, fileOptions, showTrashButton,\n    } = this.props;\n\n    if (!queue || queue.length === 0) {\n      // TODO: center this. actually, does this ever get rendered?\n      return (<p>Queue is empty.</p>);\n    }\n\n    const TrashButton = (\n      <button\n        className=\"k-button-icon\"\n        type=\"button\"\n        onClick={evt => this.handleClick(evt, { type: 'EMPTY_QUEUE' })}\n        uk-icon=\"icon: trash\"\n      />\n    );\n\n    return (\n      <div className=\"uk-card uk-card-default uk-card-body uk-margin-small-left uk-margin-small-right\">\n        <table className=\"uk-table uk-table-divider uk-table-middle\">\n          <thead>\n            <tr>\n              <th className=\"uk-table-shrink\" />\n              <th className=\"uk-table-expand\">Filename</th>\n              <th className=\"uk-table-shrink\">\n                {showTrashButton ? TrashButton : null}\n              </th>\n            </tr>\n          </thead>\n          <tbody>\n            {queue.map((file, index) => (<FileTableRow usePauseIcon={file.hash === currentlyPlayingHash} clickHandler={this.handleClick} file={file} index={index} fileOptions={fileOptions} />))}\n          </tbody>\n        </table>\n      </div>\n    );\n  }\n}\n\nexport default connect(mapStateToProps)(WorkQueue);\n"
  },
  {
    "path": "src/client/index.jsx",
    "content": "import { render } from 'inferno';\nimport { Provider } from 'inferno-redux';\nimport { BrowserRouter, Route, Switch } from 'inferno-router';\nimport { createBrowserHistory } from 'history';\nimport { createStore } from 'redux';\n\nimport UIkit from 'uikit';\nimport Icons from 'uikit/dist/js/uikit-icons';\n\nimport AudioElement from './components/AudioElement';\nimport PlayerBar from './components/PlayerBar';\nimport Player from './routes/Player';\nimport Work from './routes/Work';\nimport Works from './routes/Works';\nimport List from './routes/List';\nimport Reducer from './reducer';\n\nimport './static/style/uikit.stripped.less';\nimport './static/style/kikoeru.css';\nimport ErrorBoundary from './components/ErrorBoundary';\nimport NavBar from './components/NavBar';\n\n// Enable UIkit icon plugin\nUIkit.use(Icons);\n\nconst browserHistory = createBrowserHistory();\nconst store = createStore(Reducer);\n\nconst App = () => (\n  <Provider store={store}>\n    <ErrorBoundary>\n      <BrowserRouter history={browserHistory}>\n        <NavBar />\n        <Switch>\n          <Route exact path=\"/\" component={Works} />\n          <Route path=\"/player/\" component={Player} />\n          <Route path=\"/work/:rjcode\" component={Work} />\n\n          <Route path=\"/circle/:id\" component={p => <Works restrict=\"circle\" {...p} />} />\n          <Route path=\"/tag/:id\" component={p => <Works restrict=\"tag\" {...p} />} />\n          <Route path=\"/va/:id\" component={p => <Works restrict=\"va\" {...p} />} />\n\n          <Route path=\"/circles/\" component={p => <List restrict=\"circle\" {...p} />} />\n          <Route path=\"/tags/\" component={p => <List restrict=\"tag\" {...p} />} />\n          <Route path=\"/vas/\" component={p => <List restrict=\"va\" {...p} />} />\n        </Switch>\n        <PlayerBar />\n      </BrowserRouter>\n    </ErrorBoundary>\n    <AudioElement />\n  </Provider>\n);\n\nrender(<App />, document.getElementById('root'));\n"
  },
  {
    "path": "src/client/reducer.js",
    "content": "/* eslint-disable no-param-reassign */\nimport { createReducer } from 'redux-starter-kit';\n\nconst initialState = {\n  playing: false, // playing or paused\n  progress: 0, // track progress (0-100)\n  seek: false, // where to seek to (0-100)\n  queueIndex: 0, // which track in the queue is currently selected\n  queue: [\n    // list of tracks. object format:\n    /*\n      title: null, // title to show in UI\n      subtitle: null, // subtitle to show in UI\n      hash: null, // unique identifier for the file\n     */\n  ],\n};\n\nexport default createReducer(initialState, {\n  PLAY: (state) => { state.playing = true; },\n  PAUSE: (state) => { state.playing = false; },\n  TOGGLE_PLAYING: (state) => {\n    state.playing = !state.playing;\n  },\n\n  // Play a specific file from the queue.\n  SET_TRACK: (state, action) => {\n    if (action.payload >= state.queue.length || action.payload < 0) {\n      return; // Invalid index, bail.\n    }\n\n    state.queueIndex = action.payload;\n    state.progress = 0;\n    state.playing = true;\n  },\n  NEXT_TRACK: (state) => {\n    if (state.queueIndex < state.queue.length - 1) {\n      // Go to next track only if it exists.\n      state.queueIndex += 1;\n      state.progress = 0;\n      state.playing = true;\n    }\n  },\n  PREVIOUS_TRACK: (state) => {\n    if (state.queueIndex > 0) {\n      // Go to previous track only if it exists.\n      state.queueIndex -= 1;\n      state.progress = 0;\n      state.playing = true;\n    }\n  },\n\n  // Seek audio element to desired value (from 0 to 100).\n  SEEK: (state, action) => {\n    state.seek = action.payload;\n  },\n\n  // Update UI progress bars.\n  TIME_UPDATE: (state, action) => {\n    state.progress = action.payload;\n  },\n\n  // Replace entire queue and play specified file.\n  SET_QUEUE: (state, action) => {\n    state.queue = action.payload.queue;\n    state.queueIndex = action.payload.index;\n    state.progress = 0;\n    state.playing = true;\n  },\n  EMPTY_QUEUE: (state) => {\n    state.playing = false;\n    state.queue = [];\n    state.queueIndex = 0;\n  },\n\n  ADD_TO_QUEUE: (state, action) => {\n    state.queue.push(action.payload.file);\n  },\n  REMOVE_FROM_QUEUE: (state, action) => {\n    state.queue.splice(action.payload.index, 1);\n\n    if (action.payload.index === state.queueIndex) {\n      state.playing = false;\n      state.queueIndex = 0;\n      state.progress = 0;\n    }\n  },\n\n  // TODO: refactor move up/down in queue to reuse code\n  MOVE_UP_IN_QUEUE: (state, action) => {\n    if (action.payload.index - 1 < 0) {\n      return; // Invalid index, bail\n    }\n\n    const aux = state.queue[action.payload.index - 1];\n    state.queue[action.payload.index - 1] = state.queue[action.payload.index];\n    state.queue[action.payload.index] = aux;\n\n    if (action.payload.index === state.queueIndex) {\n      state.queueIndex -= 1;\n    } else if (action.payload.index === state.queueIndex + 1) {\n      state.queueIndex += 1;\n    }\n  },\n  MOVE_DOWN_IN_QUEUE: (state, action) => {\n    if (action.payload.index + 1 >= state.queue.length) {\n      return; // Invalid index, bail\n    }\n\n    const aux = state.queue[action.payload.index + 1];\n    state.queue[action.payload.index + 1] = state.queue[action.payload.index];\n    state.queue[action.payload.index] = aux;\n\n    if (action.payload.index === state.queueIndex) {\n      state.queueIndex += 1;\n    } else if (action.payload.index === state.queueIndex - 1) {\n      state.queueIndex -= 1;\n    }\n  },\n\n  // Add a file after the currently playing item in the queue.\n  PLAY_NEXT: (state, action) => {\n    state.queue.splice(state.queueIndex + 1, 0, action.payload.file);\n  },\n});\n"
  },
  {
    "path": "src/client/routes/List.jsx",
    "content": "import { Component } from 'inferno';\nimport { Link } from 'inferno-router';\n\n/**\n * Generic link list (used for circles, tags and VAs).\n */\nclass List extends Component {\n  constructor(props) {\n    super(props);\n\n    this.onFilter = this.onFilter.bind(this);\n    this.state = {\n      items: null,\n      filteredItems: null,\n    };\n  }\n\n  componentDidMount() {\n    const { restrict } = this.props;\n\n    fetch(`/api/${restrict}s/`)\n      .then(res => res.json())\n      .then(res => this.setState({\n        items: res,\n      }))\n      .catch((err) => {\n        throw new Error(`Failed to fetch /api/${restrict}s/: ${err}`);\n      });\n  }\n\n  onFilter(evt) {\n    evt.preventDefault();\n    const data = new FormData(evt.target);\n    const { items } = this.state;\n\n    this.setState({\n      items,\n      filteredItems: items.filter(x => x.name.toLowerCase().indexOf(data.get('filter_str').toLowerCase()) !== -1),\n    });\n  }\n\n  render() {\n    const { restrict } = this.props;\n    const { items, filteredItems } = this.state;\n\n    if (!items) {\n      return (\n        <div className=\"uk-cover-container\" uk-height-viewport>\n          <div className=\"uk-position-center\" uk-spinner=\"ratio: 2\" />\n        </div>\n      );\n    }\n\n    const visibleItems = filteredItems || items;\n    const elementList = visibleItems.map(item => (\n      <Link\n        to={`/${restrict}/${item.id}`}\n        className=\"uk-button uk-button-default uk-width-1 uk-margin-small-bottom\"\n      >\n        {item.name}\n      </Link>\n    ));\n\n    return (\n      <div className=\"uk-container\">\n        <h2 className=\"uk-margin-top\">All {restrict}s</h2>\n        <form onSubmit={this.onFilter}>\n          <input name=\"filter_str\" className=\"uk-input uk-width-1\" type=\"text\" placeholder={`Search for a ${restrict}...`} />\n        </form>\n        <div className=\"uk-align-center\">\n          {elementList}\n        </div>\n      </div>\n    );\n  }\n}\n\nexport default List;\n"
  },
  {
    "path": "src/client/routes/Player.jsx",
    "content": "import { Component } from 'inferno';\nimport { connect } from 'inferno-redux';\nimport { Redirect } from 'inferno-router';\n\nimport WorkQueue from '../components/WorkQueue';\n\nimport playIcon from '../static/svg/play.svg';\nimport pauseIcon from '../static/svg/pause.svg';\nimport previousIcon from '../static/svg/previous.svg';\nimport nextIcon from '../static/svg/next.svg';\n\nconst mapStateToProps = state => ({\n  playing: state.playing,\n  progress: state.progress,\n  queue: state.queue,\n  queueIndex: state.queueIndex,\n});\n\n/**\n * Player page. Contains player controls and the queue.\n */\nclass Player extends Component {\n  constructor(props) {\n    super(props);\n\n    this.handleSeek = this.handleSeek.bind(this);\n    this.handleClick = this.handleClick.bind(this);\n\n    this.fileOptions = [\n      { text: 'Remove from queue', type: 'REMOVE_FROM_QUEUE' },\n      { text: 'Move up', type: 'MOVE_UP_IN_QUEUE' },\n      { text: 'Move down', type: 'MOVE_DOWN_IN_QUEUE' },\n    ];\n  }\n\n  componentDidMount() {\n    window.scrollTo(0, 0);\n  }\n\n  handleSeek(evt) {\n    const { dispatch } = this.props;\n\n    dispatch({\n      type: 'SEEK',\n      payload: evt.currentTarget.valueAsNumber,\n    });\n  }\n\n  handleClick(evt, which) {\n    const { dispatch } = this.props;\n\n    switch (which) {\n      case 'previous-button':\n        dispatch({ type: 'PREVIOUS_TRACK' });\n        break;\n      case 'middle-button':\n        dispatch({ type: 'TOGGLE_PLAYING' });\n        break;\n      case 'next-button':\n        dispatch({ type: 'NEXT_TRACK' });\n        break;\n      default:\n        throw new Error(`Clicked on unknown element: ${which}`);\n    }\n  }\n\n  // TODO: refactor into smaller components (controls, seekbar)?\n  render() {\n    const {\n      playing, progress, queue, queueIndex,\n    } = this.props;\n    const currentlyPlaying = queue[queueIndex];\n\n    if (!currentlyPlaying) {\n      return (<Redirect to=\"/\" />);\n    }\n\n    return (\n      <>\n        <div className=\"uk-background-cover uk-height-medium uk-panel uk-flex uk-flex-center uk-flex-middle\" style={{ 'background-image': `linear-gradient(#0008, #0008), url(\"/api/cover/${currentlyPlaying.id}\")` }}>\n          <button className=\"k-player-button k-invert\" type=\"button\" id=\"previous-button\" onClick={evt => this.handleClick(evt, 'previous-button')}>\n            <img src={previousIcon} alt=\"Previous Track\" />\n          </button>\n\n          <button className=\"k-player-button k-invert\" type=\"button\" id=\"middle-button\" onClick={evt => this.handleClick(evt, 'middle-button')}>\n            <img src={playing ? pauseIcon : playIcon} alt=\"Play\" />\n          </button>\n\n          <button className=\"k-player-button k-invert\" type=\"button\" id=\"next-button\" onClick={evt => this.handleClick(evt, 'next-button')}>\n            <img src={nextIcon} alt=\"Next Track\" />\n          </button>\n\n          <div className=\"uk-position-bottom k-player-seekbar\">\n            <input type=\"range\" step=\"any\" min=\"0\" max=\"100\" defaultValue={progress} onInput={this.handleSeek} />\n            <div className=\"k-player-seekbar-progress\">\n              <div\n                className=\"k-progress-bar\"\n                role=\"progressbar\"\n                style={{ width: `${progress}%` }}\n              />\n            </div>\n          </div>\n        </div>\n\n        <WorkQueue queue={queue} fileOptions={this.fileOptions} showTrashButton />\n      </>\n    );\n  }\n}\n\nexport default connect(mapStateToProps)(Player);\n"
  },
  {
    "path": "src/client/routes/Work.jsx",
    "content": "import { Component } from 'inferno';\n\nimport WorkDetails from '../components/WorkDetails';\nimport WorkQueue from '../components/WorkQueue';\n\n/**\n * Work page. Shows metadata and files for a specific work.\n */\nclass Work extends Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      metadata: null,\n      tracks: null,\n    };\n\n    this.fileOptions = [\n      { text: 'Add to queue', type: 'ADD_TO_QUEUE' },\n      { text: 'Play next', type: 'PLAY_NEXT' },\n    ];\n  }\n\n  componentDidMount() {\n    const { match } = this.props;\n\n    // TODO: test if status code is 200, show error UI otherwise\n    const metadataPromise = fetch(`/api/work/${match.params.rjcode}`).then(res => res.json());\n    const tracksPromise = fetch(`/api/tracks/${match.params.rjcode}`).then(res => res.json());\n\n    Promise.all([metadataPromise, tracksPromise])\n      .then(res => this.setState({\n        metadata: res[0],\n        tracks: res[1].map((track) => {\n          // TODO: mixing id with rjcode smells fishy . test if breaks anything on < 6 digit ids\n          // eslint-disable-next-line no-param-reassign\n          track.id = match.params.rjcode;\n          return track;\n        }),\n      }))\n      .catch((err) => {\n        throw new Error(`Failed to fetch work from backend: ${err}`);\n      });\n  }\n\n  render() {\n    const { metadata, tracks } = this.state;\n\n    // Metadata still loading, render spinner.\n    // TODO: fix positioning and overflow on this spinner\n    if (!metadata || !tracks) {\n      return (\n        <div className=\"uk-cover-container\" uk-height-viewport>\n          <div className=\"uk-position-center\" uk-spinner=\"ratio: 2\" />\n        </div>\n      );\n    }\n\n    // Metadata ready, render the work page.\n    return (\n      <>\n        <WorkDetails metadata={metadata} />\n        <div\n          className=\"uk-margin-remove-top\"\n          style={{\n            'background-size': 'cover',\n            'background-image': `linear-gradient(#fff, #fff5), url(\"/api/cover/${metadata.id}\")`,\n          }}\n        >\n          <WorkQueue queue={tracks} fileOptions={this.fileOptions} />\n        </div>\n      </>\n    );\n  }\n}\n\nexport default Work;\n"
  },
  {
    "path": "src/client/routes/Works.jsx",
    "content": "import { Component } from 'inferno';\n\nimport InfiniteScroll from '../components/InfiniteScroll';\nimport WorkDetails from '../components/WorkDetails';\n\n/**\n * Card component for a single work.\n */\nclass WorkCard extends Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      metadata: null,\n    };\n  }\n\n  componentDidMount() {\n    const { id } = this.props;\n\n    fetch(`/api/work/${id}`)\n      .then(res => res.json())\n      .then((res) => {\n        this.setState({ metadata: res });\n      })\n      .catch((err) => {\n        throw new Error(`Failed to fetch /api/work/${id}: ${err}`);\n      });\n  }\n\n  render() {\n    const { metadata } = this.state;\n\n    // If metadata is still loading, render spinner.\n    let innerElement = (<div className=\"uk-position-center\" uk-spinner=\"ratio: 2\" />);\n\n    // Otherwise, render WorkDetails component with the fetched metadata.\n    if (metadata) {\n      innerElement = (<WorkDetails metadata={metadata} />);\n    }\n\n    return (\n      <div\n        className=\"uk-card uk-card-default uk-margin-bottom uk-width-1-2-margin@s uk-width-1-3-margin@m\"\n        style={{ 'max-width': '550px', margin: '8px' }}\n      >\n        {innerElement}\n      </div>\n    );\n  }\n}\n\n/**\n * Work list component.\n */\nclass Works extends Component {\n  constructor(props) {\n    super(props);\n\n    this.state = {\n      works: null,\n      oldestId: null,\n      hasMore: true,\n      pageTitle: null,\n    };\n\n    this.loadMore = this.loadMore.bind(this);\n  }\n\n  // TODO: componentDidMount and loadMore have a lot of common code. refactor?\n  componentDidMount() {\n    const { match, restrict } = this.props;\n\n    const url = match.params.id\n      ? `/api/${restrict || 'works'}/${match.params.id}` : '/api/works/';\n\n    fetch(url)\n      .then(res => res.json())\n      .then((res) => {\n        fetch(`/api/get-name/${restrict}/${match.params.id}`)\n          .then(nameRes => nameRes.text())\n          .then((name) => {\n            let pageTitle;\n\n            switch (restrict) {\n              case 'tag':\n                pageTitle = 'Works tagged with ';\n                break;\n              case 'va':\n                pageTitle = 'Works voiced by ';\n                break;\n              case 'circle':\n                pageTitle = 'Works by ';\n                break;\n              default:\n                pageTitle = 'All works';\n            } pageTitle += name || '';\n\n            this.setState({\n              works: res,\n              oldestId: res[res.length - 1].id,\n              pageTitle,\n            });\n          });\n      })\n      .catch((err) => {\n        throw new Error(`Failed to fetch ${url}: ${err}`);\n      });\n  }\n\n  componentDidUpdate(prevProps) {\n    const { match } = this.props;\n    const { match: prevMatch } = prevProps;\n\n    if (match.params.id !== prevMatch.params.id) {\n      this.componentDidMount();\n    }\n  }\n\n  loadMore() {\n    const { match, restrict } = this.props;\n    const { works, oldestId } = this.state;\n\n    const url = match.params.id\n      ? `/api/${restrict || 'works'}/${match.params.id}/${oldestId}` : `/api/works/${oldestId}`;\n\n    fetch(url)\n      .then(res => res.json())\n      .then((res) => {\n        if (!res.length) {\n          this.setState({\n            hasMore: false,\n          });\n        } else {\n          this.setState({\n            works: works.concat(res),\n            oldestId: res[res.length - 1].id,\n          });\n        }\n      })\n      .catch((err) => {\n        throw new Error(`Failed to fetch ${url}: ${err}`);\n      });\n  }\n\n  render() {\n    const { works, pageTitle, hasMore } = this.state;\n\n    if (!works) {\n      return (\n        <div className=\"uk-cover-container\" uk-height-viewport>\n          <div className=\"uk-position-center\" uk-spinner=\"ratio: 2\" />\n        </div>\n      );\n    }\n\n    return (\n      <div className=\"uk-container uk-margin-top\">\n        <h2>{pageTitle}</h2>\n        <InfiniteScroll\n          className=\"uk-flex uk-flex-center uk-flex-wrap\"\n          style={{ margin: '-12px -12px' }}\n          dataLength={works.length}\n          next={this.loadMore}\n          hasMore={hasMore}\n          loader={<div className=\"uk-align-center uk-margin-top uk-margin\" uk-spinner=\"ratio: 1\" />}\n          endMessage={<p className=\"uk-text-center uk-text-meta\" style={{ 'padding-bottom': '24px' }}>No more works.</p>}\n        >\n          {works.map(work => <WorkCard id={work.id} key={work.id} />)}\n        </InfiniteScroll>\n      </div>\n    );\n  }\n}\n\nexport default Works;\n"
  },
  {
    "path": "src/client/static/style/kikoeru.css",
    "content": "/**\n * Logo for the navbars.\n */\n\n.k-logo {\n    font-size: 1.5em;\n    font-family: 'Big Caslon', 'Times New Roman', Times, serif;\n}\n\n.k-logo-muted {\n    font-size: 4em !important;\n    opacity: 0.3;\n}\n\n.k-logo::after {\n    content: 'K';\n}\n\n/**\n * Badge/label links (VAs)\n */\n\n.k-label-link {\n    color: #fff !important;\n    text-decoration: none !important;\n    margin-right: 3px;\n}\n\n.k-label-link:clicked {\n    background-color: #5dd7a9;\n}\n\n.k-label-link:hover {\n    background-color: #32bc88;\n}\n\n/**\n * Play/menu icons in the queue card.\n */\n\n.k-button-icon {\n    padding: 0;\n    width: 20px;\n    transition-property: color, transform, -webkit-transform;\n    transition-duration: 0.3s;\n    -webkit-tap-highlight-color: transparent;\n}\n\n.k-button-icon:hover, .k-button-active {\n    color: #1e87f0;\n    -webkit-transform: scale(1.15);\n    transform: scale(1.15);\n}\n\n/**\n * Bottom player bar.\n */\n\n.k-player-bar {\n    position: fixed;\n    width: 100%;\n    bottom: 0;\n    padding: 8px 8px 8px 14px;\n    background-color: #fff;\n    box-shadow: 0 0 12px rgba(0, 0, 0, 0.2);\n    border-top: 1px solid rgba(0, 0, 0, 0.15);\n}\n\n@keyframes button-touch-animation {\n    0% {\n        transform: scale(0, 0);\n        opacity: 1;\n    }\n    20% {\n        transform: scale(25, 25);\n        opacity: 1;\n    }\n    100% {\n        opacity: 0;\n        transform: scale(40, 40);\n    }\n}\n\n.k-player-button {\n    background-color: transparent;\n    background-repeat: no-repeat;\n    border: none;\n    cursor: pointer;\n    overflow: hidden;\n    outline: none;\n    margin-left: 12px;\n    margin-right: 12px;\n    -webkit-tap-highlight-color: transparent;\n}\n\n.k-player-button:after {\n    content: '';\n    overflow: visible !important;\n    position: absolute;\n    top: 50%;\n    left: 50%;\n    width: 2px;\n    height: 2px;\n    background: rgba(255, 255, 255, 0.5);\n    opacity: 0;\n    border-radius: 100%;\n    transform: scale(1, 1) translate(-50%);\n    transform-origin: 50% 50%;\n}\n\n.k-player-button:hover:not(:active)::after {\n    animation: button-touch-animation 0.5s ease-out;\n}\n\n.k-invert {\n    filter: invert(100%);\n}\n\n.k-player-seekbar {\n    margin-bottom: 0px;\n    position: relative;\n}\n\n.k-player-seekbar-progress {\n    height: 5px;\n    background: #0000;\n}\n\n.k-progress-bar {\n    height: 100%;\n    position: relative;\n    background-color: #5dd7a9;\n}\n\n.k-progress-bar::after {\n    overflow: hidden;\n    content: \" \";\n    display: block;\n    position: absolute;\n    width: 14px;\n    height: 14px;\n    background-color: #5dd7a9;\n    border-radius: 8px;\n    top: -4px;\n    right: -6px;\n    z-index: 50;\n}\n\n/**\n * Hide original range input elements.\n */\n\n.k-player-seekbar input[type=\"range\"] {\n    -webkit-appearance: none;\n    width: calc(100% + 0px);\n    overflow-x: hidden;\n    height: 32px;\n    margin: 0;\n    padding: 0;\n    position: absolute;\n    top: -14px;\n    left: -8px;\n    z-index: 2;\n    background: transparent;\n    outline: 0;\n    border: 0;\n}\n\n.k-player-seekbar input[type=\"range\"]::-webkit-slider-thumb {\n    -webkit-appearance: none;\n    display: block;\n    width: 48px;\n    height: 48px;\n    background-color: transparent;\n}\n\n/* Mozilla: https://developer.mozilla.org/en-US/docs/User:Jonathan_Watt/range */\n.k-player-seekbar input[type=\"range\"]::-moz-range-thumb {\n    background: transparent;\n    border: 0;\n    width: 48px;\n    height: 48px;\n}\n\n.k-player-seekbar input[type=\"range\"]::-moz-range-track {\n    background: transparent;\n    border: 0;\n}\n\n.k-player-seekbar input[type=\"range\"]::-moz-focus-outer {\n    border: 0;\n}\n"
  },
  {
    "path": "src/client/static/style/uikit.stripped.less",
    "content": "@path: \"../../../../node_modules/uikit/src\";\n\n/*\n  Components\n */\n\n// Base\n@import \"@{path}/less/components/variables.less\";\n@import \"@{path}/less/components/mixin.less\";\n@import \"@{path}/less/components/base.less\";\n\n// Elements\n@import \"@{path}/less/components/link.less\";\n@import \"@{path}/less/components/heading.less\";\n@import \"@{path}/less/components/divider.less\";\n@import \"@{path}/less/components/list.less\";\n// @import \"@{path}/less/components/description-list.less\";\n@import \"@{path}/less/components/table.less\";\n@import \"@{path}/less/components/icon.less\";\n// @import \"@{path}/less/components/form-range.less\";\n@import \"@{path}/less/components/form.less\"; // After: Icon, Form Range\n@import \"@{path}/less/components/button.less\";\n\n// Layout\n// @import \"@{path}/less/components/section.less\";\n@import \"@{path}/less/components/container.less\";\n@import \"@{path}/less/components/grid.less\";\n// @import \"@{path}/less/components/tile.less\";\n@import \"@{path}/less/components/card.less\";\n\n// Common\n@import \"@{path}/less/components/close.less\"; // After: Icon\n@import \"@{path}/less/components/spinner.less\"; // After: Icon\n// @import \"@{path}/less/components/totop.less\"; // After: Icon\n// @import \"@{path}/less/components/marker.less\"; // After: Icon\n// @import \"@{path}/less/components/alert.less\"; // After: Close\n// @import \"@{path}/less/components/badge.less\";\n@import \"@{path}/less/components/label.less\";\n@import \"@{path}/less/components/overlay.less\"; // After: Icon\n// @import \"@{path}/less/components/article.less\"; // After: Subnav\n// @import \"@{path}/less/components/comment.less\"; // After: Subnav\n// @import \"@{path}/less/components/search.less\"; // After: Icon\n\n// Navs\n@import \"@{path}/less/components/nav.less\";\n@import \"@{path}/less/components/navbar.less\"; // After: Card, Grid, Nav, Icon, Search\n// @import \"@{path}/less/components/subnav.less\";\n// @import \"@{path}/less/components/breadcrumb.less\";\n// @import \"@{path}/less/components/pagination.less\";\n// @import \"@{path}/less/components/tab.less\";\n// @import \"@{path}/less/components/slidenav.less\"; // After: Icon\n// @import \"@{path}/less/components/dotnav.less\";\n// @import \"@{path}/less/components/thumbnav.less\";\n\n// JavaScript\n// @import \"@{path}/less/components/accordion.less\";\n@import \"@{path}/less/components/drop.less\"; // After: Card\n@import \"@{path}/less/components/dropdown.less\"; // After: Card\n// @import \"@{path}/less/components/modal.less\"; // After: Close\n// @import \"@{path}/less/components/lightbox.less\"; // After: Close\n// @import \"@{path}/less/components/slideshow.less\";\n// @import \"@{path}/less/components/slider.less\";\n// @import \"@{path}/less/components/sticky.less\";\n@import \"@{path}/less/components/offcanvas.less\";\n// @import \"@{path}/less/components/switcher.less\";\n// @import \"@{path}/less/components/leader.less\";\n// Scrollspy\n// Toggle\n// Scroll\n\n// Additional\n@import \"@{path}/less/components/iconnav.less\";\n// @import \"@{path}/less/components/notification.less\";\n// @import \"@{path}/less/components/tooltip.less\";\n// @import \"@{path}/less/components/placeholder.less\";\n// @import \"@{path}/less/components/progress.less\";\n// @import \"@{path}/less/components/sortable.less\";\n// @import \"@{path}/less/components/countdown.less\";\n\n// Utilities\n@import \"@{path}/less/components/animation.less\";\n@import \"@{path}/less/components/width.less\";\n@import \"@{path}/less/components/height.less\";\n@import \"@{path}/less/components/text.less\";\n@import \"@{path}/less/components/column.less\";\n@import \"@{path}/less/components/cover.less\";\n@import \"@{path}/less/components/background.less\";\n@import \"@{path}/less/components/align.less\";\n@import \"@{path}/less/components/svg.less\";\n@import \"@{path}/less/components/utility.less\";\n@import \"@{path}/less/components/flex.less\"; // After: Utility\n@import \"@{path}/less/components/margin.less\";\n@import \"@{path}/less/components/padding.less\";\n@import \"@{path}/less/components/position.less\";\n@import \"@{path}/less/components/transition.less\";\n@import \"@{path}/less/components/visibility.less\";\n@import \"@{path}/less/components/inverse.less\";\n\n// Need to be loaded last\n@import \"@{path}/less/components/print.less\";\n\n/*\n  Theme\n */\n\n// Base\n@import \"@{path}/less/theme/variables.less\";\n@import \"@{path}/less/theme/base.less\";\n\n// Elements\n@import \"@{path}/less/theme/link.less\";\n@import \"@{path}/less/theme/heading.less\";\n@import \"@{path}/less/theme/divider.less\";\n@import \"@{path}/less/theme/list.less\";\n// @import \"@{path}/less/theme/description-list.less\";\n@import \"@{path}/less/theme/table.less\";\n@import \"@{path}/less/theme/icon.less\";\n// @import \"@{path}/less/theme/form-range.less\";\n@import \"@{path}/less/theme/form.less\";\n@import \"@{path}/less/theme/button.less\";\n\n// Layout\n// @import \"@{path}/less/theme/section.less\";\n@import \"@{path}/less/theme/container.less\";\n@import \"@{path}/less/theme/grid.less\";\n// @import \"@{path}/less/theme/tile.less\";\n@import \"@{path}/less/theme/card.less\";\n\n// Common\n@import \"@{path}/less/theme/close.less\";\n@import \"@{path}/less/theme/spinner.less\";\n// @import \"@{path}/less/theme/marker.less\";\n// @import \"@{path}/less/theme/totop.less\";\n// @import \"@{path}/less/theme/alert.less\";\n// @import \"@{path}/less/theme/badge.less\";\n@import \"@{path}/less/theme/label.less\";\n@import \"@{path}/less/theme/overlay.less\";\n// @import \"@{path}/less/theme/article.less\";\n// @import \"@{path}/less/theme/comment.less\";\n// @import \"@{path}/less/theme/search.less\";\n\n// Navs\n@import \"@{path}/less/theme/nav.less\";\n@import \"@{path}/less/theme/navbar.less\";\n// @import \"@{path}/less/theme/subnav.less\";\n// @import \"@{path}/less/theme/breadcrumb.less\";\n// @import \"@{path}/less/theme/pagination.less\";\n// @import \"@{path}/less/theme/tab.less\";\n// @import \"@{path}/less/theme/slidenav.less\";\n// @import \"@{path}/less/theme/dotnav.less\";\n// @import \"@{path}/less/theme/thumbnav.less\";\n\n// JavaScript\n// @import \"@{path}/less/theme/accordion.less\";\n@import \"@{path}/less/theme/drop.less\";\n@import \"@{path}/less/theme/dropdown.less\";\n// @import \"@{path}/less/theme/modal.less\";\n// @import \"@{path}/less/theme/lightbox.less\";\n// @import \"@{path}/less/theme/sticky.less\";\n@import \"@{path}/less/theme/offcanvas.less\";\n// @import \"@{path}/less/theme/leader.less\";\n\n// Additional\n@import \"@{path}/less/theme/iconnav.less\";\n// @import \"@{path}/less/theme/notification.less\";\n// @import \"@{path}/less/theme/tooltip.less\";\n// @import \"@{path}/less/theme/placeholder.less\";\n// @import \"@{path}/less/theme/progress.less\";\n// @import \"@{path}/less/theme/sortable.less\";\n// @import \"@{path}/less/theme/countdown.less\";\n\n// Utilities\n@import \"@{path}/less/theme/animation.less\";\n@import \"@{path}/less/theme/width.less\";\n@import \"@{path}/less/theme/height.less\";\n@import \"@{path}/less/theme/text.less\";\n@import \"@{path}/less/theme/column.less\";\n@import \"@{path}/less/theme/background.less\";\n@import \"@{path}/less/theme/align.less\";\n@import \"@{path}/less/theme/utility.less\";\n@import \"@{path}/less/theme/margin.less\";\n@import \"@{path}/less/theme/padding.less\";\n@import \"@{path}/less/theme/position.less\";\n@import \"@{path}/less/theme/transition.less\";\n@import \"@{path}/less/theme/inverse.less\";\n\n\n/*\n  Extra\n */\n@media (min-width: @breakpoint-small) and (max-width: @breakpoint-medium - 1) {\n  .uk-width-1-2-margin\\@s { width: ~'calc(100% * 1 / 2.3)' !important; }\n}\n\n@media (min-width: @breakpoint-medium) {\n  .uk-width-1-3-margin\\@m { width: ~'calc(100% * 1 / 3.5)'; }\n}\n\n"
  },
  {
    "path": "src/server/auth.js",
    "content": "const path = require('path');\nconst express = require('express');\n\nconst config = require('../../config.json');\n\nconst router = express.Router();\n\nrouter.get('/', (req, res, next) => {\n  res.sendFile(path.join(__dirname, '..', '..', 'static', 'auth.html'));\n});\n\nrouter.post('/', (req, res, next) => {\n  if (req.body.password === config.password) {\n    req.session.auth = true;\n  }\n\n  res.redirect('/');\n});\n\nconst authenticator = (req, res, next) => {\n  if (req.path === '/auth/'\n    || req.path === '/main.css'\n    || req.path.indexOf('/static/') === 0\n    || req.session.auth\n    || !config.password\n  ) {\n    next();\n  } else {\n    res.redirect('/auth/');\n  }\n};\n\nmodule.exports = { router, authenticator };\n"
  },
  {
    "path": "src/server/database/db.js",
    "content": "const knex = require('knex')({\n  client: 'sqlite3',\n  useNullAsDefault: true,\n  connection: {\n    filename: './db.sqlite3',\n  },\n  acquireConnectionTimeout: 5000,\n});\n\n/**\n * Takes a work metadata object and inserts it into the database.\n * @param {Object} work Work object.\n */\nconst insertWorkMetadata = work => knex.transaction(trx => trx.raw(\n  trx('t_circle')\n    .insert({\n      id: work.circle.id,\n      name: work.circle.name,\n    }).toString().replace('insert', 'insert or ignore'),\n)\n  .then(() => trx('t_work')\n    .insert({\n      id: work.id,\n      dir: work.dir,\n      title: work.title,\n      circle_id: work.circle.id,\n      nsfw: work.nsfw,\n    }))\n  .then(() => {\n    // Now that work is in the database, insert relationships\n    const promises = [];\n\n    for (let i = 0; i < work.tags.length; i += 1) {\n      promises.push(trx.raw(\n        trx('t_tag')\n          .insert({\n            id: work.tags[i].id,\n            name: work.tags[i].name,\n          }).toString().replace('insert', 'insert or ignore'),\n      )\n        .then(() => trx('r_tag_work')\n          .insert({\n            tag_id: work.tags[i].id,\n            work_id: work.id,\n          })));\n    }\n\n    for (let i = 0; i < work.vas.length; i += 1) {\n      promises.push(trx.raw(\n        trx('t_va')\n          .insert({\n            id: work.vas[i].id,\n            name: work.vas[i].name,\n          }).toString().replace('insert', 'insert or ignore'),\n      )\n        .then(() => trx('r_va_work')\n          .insert({\n            va_id: work.vas[i].id,\n            work_id: work.id,\n          })));\n    }\n\n    return Promise.all(promises)\n      .then(() => trx);\n  }));\n\n/**\n * Fetches metadata for a specific work id.\n * @param {Number} id Work identifier.\n */\nconst getWorkMetadata = id => new Promise((resolve, reject) => {\n  // TODO: do this all in a single transaction?\n  knex('t_work')\n    .select('*')\n    .where('id', '=', id)\n    .first()\n    .then((workRes) => {\n      if (!workRes) {\n        throw new Error(`There is no work with id ${id} in the database.`);\n      }\n\n      knex('t_circle')\n        .select('name')\n        .where('t_circle.id', '=', workRes.circle_id)\n        .first()\n        .then((circleRes) => {\n          const work = {\n            id: workRes.id,\n            title: workRes.title,\n            circle: { id: workRes.circle_id, name: circleRes.name },\n          };\n\n          knex('r_tag_work')\n            .select('tag_id', 'name')\n            .where('r_tag_work.work_id', '=', id)\n            .join('t_tag', 't_tag.id', '=', 'r_tag_work.tag_id')\n            .then((tagsRes) => {\n              work.tags = tagsRes.map(tag => ({ id: tag.tag_id, name: tag.name }));\n\n              knex('r_va_work')\n                .select('va_id', 'name')\n                .where('r_va_work.work_id', '=', id)\n                .join('t_va', 't_va.id', '=', 'r_va_work.va_id')\n                .then((vaRes) => {\n                  work.vas = vaRes.map(va => ({ id: va.va_id, name: va.name }));\n                  resolve(work);\n                });\n            });\n        });\n    })\n    .catch(err => reject(err));\n});\n\n/**\n * Tests if the given circle, tags and VAs are orphans and if so, removes them.\n * @param {*} trx Knex transaction object.\n * @param {*} circle Circle id to check.\n * @param {*} tags Array of tag ids to check.\n * @param {*} vas Array of VA ids to check.\n */\nconst cleanupOrphans = (trx, circle, tags, vas) => new Promise(async (resolve, reject) => {\n  const getCount = (tableName, colName, colValue) => new Promise((resolveCount, rejectCount) => {\n    trx(tableName)\n      .select(colName)\n      .where(colName, '=', colValue)\n      .count()\n      .first()\n      .then(res => res['count(*)'])\n      .then(count => resolveCount(count))\n      .catch(err => rejectCount(err));\n  });\n\n  const promises = [];\n  promises.push(new Promise((resolveCircle, rejectCircle) => {\n    getCount('t_work', 'circle_id', circle)\n      .then((count) => {\n        if (count === 0) {\n          trx('t_circle')\n            .del()\n            .where('id', '=', circle)\n            .then(() => resolveCircle())\n            .catch(err => rejectCircle(err));\n        } else {\n          resolveCircle();\n        }\n      });\n  }));\n\n  for (let i = 0; i < tags.length; i += 1) {\n    const tag = tags[i];\n\n    // eslint-disable-next-line no-await-in-loop\n    const count = await getCount('r_tag_work', 'tag_id', tag);\n\n    if (count === 0) {\n      promises.push(\n        trx('t_tag')\n          .delete()\n          .where('id', '=', tag),\n      );\n    }\n  }\n\n  for (let i = 0; i < vas.length; i += 1) {\n    const va = vas[i];\n\n    // eslint-disable-next-line no-await-in-loop\n    const count = await getCount('r_va_work', 'va_id', va);\n\n    if (count === 0) {\n      promises.push(\n        trx('t_va')\n          .delete()\n          .where('id', '=', va),\n      );\n    }\n  }\n\n  Promise.all(promises)\n    .then((results) => {\n      resolve(results);\n    })\n    .catch(err => reject(err));\n});\n\n/**\n * Removes a work and then its orphaned circles, tags & VAs from the database.\n * @param {Integer} id Work id.\n */\nconst removeWork = id => new Promise(async (resolve, reject) => {\n  const trx = await knex.transaction();\n\n  // Save circle, tags and VAs to array for later testing\n  const circle = await trx('t_work').select('circle_id').where('id', '=', id).first();\n  const tags = await trx('r_tag_work').select('tag_id').where('work_id', '=', id);\n  const vas = await trx('r_va_work').select('va_id').where('work_id', '=', id);\n\n  // Remove work and its relationships\n  trx('t_work')\n    .del()\n    .where('id', '=', id)\n    .then(trx('r_tag_work')\n      .del()\n      .where('work_id', '=', id)\n      .then(trx('r_va_work')\n        .del()\n        .where('work_id', '=', id)\n        .then(() => cleanupOrphans(\n          trx,\n          circle.circle_id,\n          tags.map(tag => tag.tag_id),\n          vas.map(va => va.va_id),\n        ))\n        .then(trx.commit)\n        .then(() => resolve())))\n    .catch(err => reject(err));\n});\n\n/**\n * Returns list of work ids by circle, tag or VA.\n * @param {Number} id Which id to filter by.\n * @param {String} field Which field to filter by.\n */\nconst getUnsortedWorksBy = (id, field) => {\n  switch (field) {\n    case 'circle':\n      return knex('t_work')\n        .select('id')\n        .where('circle_id', '=', id);\n\n    case 'tag':\n      return knex('r_tag_work')\n        .select('work_id as id')\n        .where('tag_id', '=', id);\n\n    case 'va':\n      return knex('r_va_work')\n        .select('work_id as id')\n        .where('va_id', '=', id);\n\n    default:\n      return knex('t_work')\n        .select('id');\n  }\n};\nconst getWorksBy = (id, field) => getUnsortedWorksBy(id, field).orderBy('id', 'desc');\n\nconst paginateResults = (query, startFrom, howMany, tableName) => query\n  .where(tableName ? `${tableName}_id` : 'id', '<', startFrom)\n  .limit(howMany);\n\nmodule.exports = {\n  knex, insertWorkMetadata, getWorkMetadata, removeWork, getWorksBy, paginateResults,\n};\n"
  },
  {
    "path": "src/server/database/schema.js",
    "content": "/* eslint-disable no-console */\nconst { knex } = require('./db');\n\nconst createSchema = () => knex.schema\n  .createTable('t_circle', (table) => {\n    table.increments();\n    table.string('name').notNullable();\n  })\n  .createTable('t_work', (table) => {\n    table.increments();\n    table.string('dir').notNullable();\n    table.string('title').notNullable();\n    table.integer('circle_id').notNullable();\n    table.boolean('nsfw').notNullable();\n    table.foreign('circle_id').references('id').inTable('t_circle');\n  })\n  .createTable('t_tag', (table) => {\n    table.increments();\n    table.string('name').notNullable();\n  })\n  .createTable('t_va', (table) => {\n    table.increments();\n    table.string('name').notNullable();\n  })\n\n  .createTable('r_tag_work', (table) => {\n    table.integer('tag_id');\n    table.integer('work_id');\n    table.foreign('tag_id').references('id').inTable('t_tag');\n    table.foreign('work_id').references('id').inTable('t_work');\n    table.primary(['tag_id', 'work_id']);\n  })\n  .createTable('r_va_work', (table) => {\n    table.integer('va_id');\n    table.integer('work_id');\n    table.foreign('va_id').references('id').inTable('t_va');\n    table.foreign('work_id').references('id').inTable('t_work');\n    table.primary(['va_id', 'work_id']);\n  })\n  .then(() => {\n    console.log(' * Schema created.');\n  })\n  .catch((err) => {\n    // ew\n    if (err.toString().indexOf('table `t_circle` already exists') !== -1) {\n      console.log(' * Schema already exists.');\n    } else {\n      throw new Error(` ! ERROR while creating schema: ${err}`);\n    }\n  });\n\nmodule.exports = { createSchema };\n"
  },
  {
    "path": "src/server/filesystem/scanner.js",
    "content": "/* eslint-disable no-console */\nconst fs = require('fs');\nconst path = require('path');\nconst fetch = require('node-fetch');\nconst db = require('../database/db');\nconst { getFolderList, deleteCoverImageFromDisk, saveCoverImageToDisk, throttlePromises } = require('./utils');\nconst { createSchema } = require('../database/schema');\nconst scrapeWorkMetadata = require('../hvdb');\n\nconst config = require('../../../config.json');\n\n/**\n * Takes a single folder, fetches metadata and adds it to the database.\n * @param {*} id Work id.\n * @param {*} folder Directory name (relative).\n */\nconst processFolder = (id, folder) => db.knex('t_work')\n  .where('id', '=', id)\n  .count()\n  .first()\n  .then((res) => {\n    const count = res['count(*)'];\n\n    if (count) {\n      // Already in database.\n      // console.log(` * ${folder} already in database, skipping.`);\n      return 'skipped';\n    }\n\n    // New folder.\n    console.log(` * Found new folder: ${folder}`);\n    const rjcode = (`000000${id}`).slice(-6); // zero-pad to 6 digits\n\n    console.log(` -> [RJ${rjcode}] Fetching metadata from HVDB...`);\n    return scrapeWorkMetadata(id)\n      .then((metadata) => {\n        console.log(` -> [RJ${rjcode}] Fetched metadata! Adding to database...`);\n\n        // TODO: cover download could be in parallel with metadata fetch. Haven't\n        // done it because if metadata fails, cover is useless. Consider for later.\n        console.log(` -> [RJ${rjcode}] Downloading cover image...`);\n        fetch(`https://hvdb.me/WorkImages/RJ${rjcode}.jpg`)\n          .then((imageRes) => {\n            if (!imageRes.ok) {\n              throw new Error(imageRes.statusText);\n            }\n\n            return imageRes;\n          })\n          .then((imageRes) => {\n            saveCoverImageToDisk(imageRes.body, rjcode)\n              .then(() => console.log(` -> [RJ${rjcode}] Cover image downloaded!`));\n          })\n          .catch((err) => {\n            console.log(`  ! [RJ${rjcode}] Failed to download cover image: ${err.message}`);\n          });\n\n        // eslint-disable-next-line no-param-reassign\n        metadata.dir = folder;\n        return db.insertWorkMetadata(metadata)\n          .then(console.log(` -> [RJ${rjcode}] Finished adding to the database!`))\n          .then(() => 'added');\n      })\n      .catch((err) => {\n        console.log(`  ! [RJ${rjcode}] Failed to fetch metadata from HVDB: ${err.message}`);\n        return 'failed';\n      });\n  });\n\nconst performCleanup = () => {\n  console.log(' * Looking for folders to clean up...');\n  return db.knex('t_work')\n    .select('id', 'dir')\n    .then((works) => {\n      const promises = works.map(work => new Promise((resolve, reject) => {\n        if (!fs.existsSync(path.join(config.rootDir, work.dir))) {\n          console.warn(` ! ${work.dir} is missing from filesystem. Removing from database...`);\n          db.removeWork(work.id)\n            .then((result) => {\n              const rjcode = (`000000${work.id}`).slice(-6); // zero-pad to 6 digits\n              deleteCoverImageFromDisk(rjcode)\n                .catch(() => console.log(` -> [RJ${rjcode}] Failed to delete cover image.`))\n                .then(() => resolve(result));\n            })\n            .catch(err => reject(err));\n        } else {\n          resolve();\n        }\n      }));\n\n      return Promise.all(promises);\n    });\n};\n\nconst performScan = () => {\n  fs.mkdir(path.join(config.rootDir, 'Images'), (direrr) => {\n    if (direrr && direrr.code !== 'EEXIST') {\n      console.error(` ! ERROR while trying to create Images folder: ${direrr.code}`);\n      process.exit(1);\n    }\n\n    createSchema()\n      .then(() => performCleanup())\n      .catch((err) => {\n        console.error(` ! ERROR while performing cleanup: ${err.message}`);\n        process.exit(1);\n      })\n      .then(async () => {\n        console.log(' * Finished cleanup. Starting scan...');\n        const promises = [];\n\n        try {\n          for await (const folder of getFolderList()) {\n            const id = folder.match(/RJ(\\d{6})/)[1];\n            promises.push(() => processFolder(id, folder));\n            \n          }\n        } catch (err) {\n          console.error(` ! ERROR while trying to get folder list: ${err.message}`);\n          process.exit(1);\n        }\n\n        throttlePromises(config.maxParallelism, promises)\n          .then((results) => {\n            const counts = {\n              added: 0,\n              failed: 0,\n              skipped: 0,\n            };\n\n            // eslint-disable-next-line no-return-assign\n            results.forEach(x => counts[x] += 1);\n\n            console.log(` * Finished scan. Added ${counts.added}, skipped ${counts.skipped} and failed to add ${counts.failed} works.`);\n            db.knex.destroy();\n          })\n          .catch((err) => {\n            console.error(` ! ERROR while performing scan: ${err.message}`);\n            process.exit(1);\n          });\n      })\n      .catch((err) => {\n        console.error(` ! ERROR while creating database schema: ${err.message}`);\n        process.exit(1);\n      });\n  });\n};\n\nperformScan();\n"
  },
  {
    "path": "src/server/filesystem/utils.js",
    "content": "const fs = require('fs');\nconst path = require('path');\nconst recursiveReaddir = require('recursive-readdir');\nconst { orderBy } = require('natural-orderby');\n\nconst config = require('../../../config.json');\n\n/**\n * Returns list of playable tracks in a given folder. Track is an object\n * containing 'title', 'subtitle' and 'hash'.\n * @param {Number} id Work identifier. Currently, RJ/RE code.\n * @param {String} dir Work directory (relative).\n */\nconst getTrackList = (id, dir) => recursiveReaddir(\n  path.join(config.rootDir, dir),\n)\n  .then((files) => {\n    // Filter out any files not matching these extensions\n    const filteredFiles = files.filter((file) => {\n      const ext = path.extname(file);\n\n      return (ext === '.mp3' || ext === '.ogg' || ext === '.opus' || ext === '.wav' || ext === '.flac' || ext === '.webm' || ext === '.mp4');\n    });\n\n    // Sort by folder and title\n    const sortedFiles = orderBy(filteredFiles.map((file) => {\n      const shortFilePath = file.replace(path.join(config.rootDir, dir, '/'), '');\n      const dirName = path.dirname(shortFilePath);\n\n      return {\n        title: path.basename(file),\n        subtitle: dirName === '.' ? null : dirName,\n      };\n    }), [v => v.subtitle, v => v.title]);\n\n    // Add hash to each file\n    const sortedHashedFiles = sortedFiles.map(\n      (file, index) => ({\n        title: file.title,\n        subtitle: file.subtitle,\n        hash: `${id}/${index}`,\n      }),\n    );\n\n    return sortedHashedFiles;\n  })\n  .catch((err) => { throw new Error(`Failed to get tracklist from disk: ${err}`); });\n\n/**\n * Returns list of directory names (relative) that contain an RJ code.\n */\nasync function* getFolderList(current = '', depth = 0) {\n  const folders = await fs.promises.readdir(path.join(config.rootDir, current));\n\n  for (const folder of folders) {\n    const absolutePath = path.resolve(config.rootDir, current, folder);\n    const relativePath = path.join(current, folder);\n\n    // eslint-disable-next-line no-await-in-loop\n    if ((await fs.promises.stat(absolutePath)).isDirectory()) {\n      if (folder.match(/RJ\\d{6}/)) {\n        // Found a work folder, don't go any deeper.\n        yield relativePath;\n      } else if (depth + 1 < config.scannerMaxRecursionDepth) {\n        // Found a folder that's not a work folder, go inside if allowed.\n        yield* getFolderList(relativePath, depth + 1);\n      }\n    }\n  }\n}\n\n/**\n * Deletes a work's cover image from disk.\n * @param {String} rjcode Work RJ code (only the 6 digits, zero-padded).\n */\nconst deleteCoverImageFromDisk = rjcode => new Promise((resolve, reject) => {\n  fs.unlink(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`), (err) => {\n    if (err) {\n      reject(err);\n    } else {\n      resolve();\n    }\n  });\n});\n\n/**\n * Saves cover image to disk.\n * @param {ReadableStream} stream Image data stream.\n * @param {String} rjcode Work RJ code (only the 6 digits, zero-padded).\n */\nconst saveCoverImageToDisk = (stream, rjcode) => new Promise((resolve, reject) => {\n  // TODO: don't assume image is a jpg?\n  try {\n    stream.pipe(\n      fs.createWriteStream(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`))\n        .on('close', () => resolve()),\n    );\n  } catch (err) {\n    reject(err);\n  }\n});\n\n/**\n * Runs an array of Promise returning functions at a specified rate\n * @param {Number} the maximum number of unresolved promises that may exist at a given time\n * @param {Array<Function>} an array of promise-creating functions \n*/\nconst throttlePromises = (maxPending, asyncFuncs) => {\n  return new Promise((resolve, reject) => {\n      let numPending = 0;\n      let nextFuncId = 0;\n      const promisedValues = [];\n      (function check() {\n          if (nextFuncId >= asyncFuncs.length) { // All promises created\n              if (numPending == 0) resolve(promisedValues); // All promises fulfilled\n              return;\n          }\n          while (numPending < maxPending) { // Room for creating promise(s)\n              numPending++;\n              const thisFuncId = nextFuncId++;\n              asyncFuncs[thisFuncId]().then(value => {\n                  promisedValues[thisFuncId] = value;\n                  numPending--;\n                  check();\n              }).catch(reject);\n          }\n      })();\n  });\n};\n\n\nmodule.exports = {\n  getTrackList,\n  getFolderList,\n  deleteCoverImageFromDisk,\n  saveCoverImageToDisk,\n  throttlePromises\n};\n"
  },
  {
    "path": "src/server/hvdb.js",
    "content": "const fetch = require('node-fetch');\nconst htmlparser = require('htmlparser2');\n\n/**\n * Generates a hash integer from a given string. Hopefully only temporary until\n * reshnix exposes VA ids for scraping.\n * @param {String} name\n */\nconst hashNameIntoInt = (name) => {\n  let hash = '';\n\n  for (let i = 0; i < name.length; i += 1) {\n    const char = name.charCodeAt(i);\n    // eslint-disable-next-line no-bitwise\n    hash = ((hash << 5) - hash) + char;\n  }\n\n  // eslint-disable-next-line no-bitwise\n  hash |= 0;\n  hash = Math.abs(Math.round(hash / 1000));\n  return hash;\n};\n\n/**\n * Scrapes work metadata from public HVDB page HTML.\n * @param {Integer} id Work id.\n */\nconst scrapeWorkMetadata = id => new Promise((resolve, reject) => {\n  const url = `https://hvdb.me/Dashboard/WorkDetails/${id}`;\n\n  fetch(url)\n    .then((res) => {\n      if (!res.ok) {\n        reject(new Error(`Couldn't fetch work page HTML, received ${res.statusText}`));\n      }\n\n      return res;\n    })\n    .then(res => res.text())\n    .then((res) => {\n      const work = { id, tags: [], vas: [] };\n      let writeTo;\n\n      const parser = new htmlparser.Parser({\n        onopentag: (name, attrs) => {\n          if (name === 'input') {\n            if (attrs.id === 'Name') {\n              work.title = attrs.value;\n            } else if (attrs.name === 'SFW') {\n              work.nsfw = attrs.value === 'false';\n            }\n          }\n\n          if (name === 'a') {\n            if (attrs.href.indexOf('CircleWorks') !== -1) {\n              work.circle = {\n                id: attrs.href.substring(attrs.href.lastIndexOf('/') + 1),\n              };\n              writeTo = 'circle.name';\n            } else if (attrs.href.indexOf('TagWorks') !== -1) {\n              work.tags.push({\n                id: attrs.href.substring(attrs.href.lastIndexOf('/') + 1),\n              });\n              writeTo = 'tag.name';\n            } else if (attrs.href.indexOf('CVWorks') !== -1) {\n              work.vas.push({\n                id: hashNameIntoInt(attrs.href), // TODO: RESHNIX!!!\n              });\n              writeTo = 'va.name';\n            }\n          }\n        },\n        onclosetag: () => { writeTo = null; },\n\n        ontext: (text) => {\n          switch (writeTo) {\n            case 'circle.name':\n              work.circle.name = text;\n              break;\n            case 'tag.name':\n              work.tags[work.tags.length - 1].name = text;\n              break;\n            case 'va.name':\n              work.vas[work.vas.length - 1].name = text;\n              break;\n            default:\n          }\n        },\n      }, { decodeEntities: true });\n      parser.write(res);\n      parser.end();\n\n      if (work.tags.length === 0 && work.vas.length === 0) {\n        reject(new Error('Couldn\\'t parse data from HVDB work page.'));\n      } else {\n        resolve(work);\n      }\n    });\n});\n\nmodule.exports = scrapeWorkMetadata;\n"
  },
  {
    "path": "src/server/index.js",
    "content": "const crypto = require('crypto');\nconst path = require('path');\nconst express = require('express');\nconst session = require('express-session');\nconst memorystore = require('memorystore');\n\nconst routes = require('./routes');\nconst { router: authRoutes, authenticator } = require('./auth');\n\nconst app = express();\nconst MemoryStore = memorystore(session);\n\n// For handling authentication POST\napp.use(express.urlencoded({ extended: false }));\n\n// Use session middleware\napp.use(session({\n  cookie: { maxAge: 24 * 60 * 60 * 1000 },\n  resave: false,\n  saveUninitialized: false,\n  secret: process.env.SECRET || crypto.randomBytes(32).toString('hex'),\n  store: new MemoryStore({ checkPeriod: 24 * 60 * 60 * 1000 }),\n}));\n\n// Use authenticator middleware\napp.use(authenticator);\n\n// Serve webapp routes\napp.get(/^\\/(player|work|circle|tag|va)s?\\/(\\d+)?$/, (req, res, next) => {\n  res.sendFile(path.join(__dirname, '../../dist', 'index.html'));\n});\n\n// Serve static files from 'dist' folder\napp.use(express.static('dist'));\n\n// If 404'd, serve from 'static' folder\napp.use('/static', express.static('static'));\n\n// Expose API routes\napp.use('/api', routes);\n\n// Expose authentication route\napp.use('/auth', authRoutes);\n\n// Start server\napp.listen(process.env.PORT || 8888, () => {\n  // eslint-disable-next-line no-console\n  console.log(`Express listening on http://localhost:${process.env.PORT || 8888}`);\n});\n"
  },
  {
    "path": "src/server/routes.js",
    "content": "const path = require('path');\nconst express = require('express');\n\nconst db = require('./database/db');\nconst { getTrackList } = require('./filesystem/utils');\n\nconst config = require('../../config.json');\n\nconst router = express.Router();\n\n// GET work cover image\nrouter.get('/cover/:id', (req, res, next) => {\n  const rjcode = (`000000${req.params.id}`).slice(-6);\n  res.sendFile(path.join(config.rootDir, 'Images', `RJ${rjcode}.jpg`), (err) => {\n    if (err) {\n      res.sendFile(path.join(__dirname, '..', '..', 'static', 'no-image.jpg'), (err2) => {\n        if (err2) {\n          next(err2);\n        }\n      });\n    }\n  });\n});\n\n// GET work metadata\nrouter.get('/work/:id', (req, res, next) => {\n  db.getWorkMetadata(req.params.id)\n    .then(work => res.send(work))\n    .catch(err => next(err));\n});\n\n// GET track list in work folder\nrouter.get('/tracks/:id', (req, res, next) => {\n  db.knex('t_work')\n    .select('dir')\n    .where('id', '=', req.params.id)\n    .first()\n    .then((dir) => {\n      getTrackList(req.params.id, dir.dir)\n        .then(tracks => res.send(tracks));\n    })\n    .catch(err => next(err));\n});\n\n// GET (stream) a specific track from work folder\nrouter.get('/stream/:id/:index', (req, res, next) => {\n  db.knex('t_work')\n    .select('dir')\n    .where('id', '=', req.params.id)\n    .first()\n    .then((dir) => {\n      getTrackList(req.params.id, dir.dir)\n        .then((tracks) => {\n          const track = tracks[req.params.index];\n          res.sendFile(path.join(config.rootDir, dir.dir, track.subtitle || '', track.title));\n        })\n        .catch(err => next(err));\n    });\n});\n\n// GET list of work ids\nrouter.get('/works/:fromId?', (req, res, next) => {\n  db.paginateResults(db.getWorksBy(), req.params.fromId || 999999, config.worksPerPage)\n    .then(results => res.send(results))\n    .catch(err => next(err));\n});\n\n// GET name of a circle/tag/VA\nrouter.get('/get-name/:field/:id', (req, res, next) => {\n  if (req.params.field === 'undefined') {\n    return res.send(null);\n  }\n\n  return db.knex(`t_${req.params.field}`)\n    .select('name')\n    .where('id', '=', req.params.id)\n    .first()\n    .then(name => res.send(name.name))\n    .catch(err => next(err));\n});\n\n// GET list of work ids, restricted by circle/tag/VA\nrouter.get('/:field/:id/:fromId?', (req, res, next) => {\n  db.paginateResults(\n    db.getWorksBy(req.params.id, req.params.field),\n    req.params.fromId || 999999, config.worksPerPage,\n  )\n    .then(results => res.send(results))\n    .catch(err => next(err));\n});\n\n// GET list of circles/tags/VAs\nrouter.get('/(:field)s/', (req, res, next) => {\n  db.knex(`t_${req.params.field}`)\n    .select('id', 'name')\n    .orderBy('name', 'asc')\n    .then(list => res.send(list))\n    .catch(err => next(err));\n});\n\nmodule.exports = router;\n"
  },
  {
    "path": "static/auth.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n\n  <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/static/apple-touch-icon.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/static/favicon-32x32.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/static/favicon-16x16.png\">\n  <link rel=\"manifest\" href=\"/static/manifest.json\">\n  <link rel=\"stylesheet\" href=\"/main.css\">\n\n  <title>Kikoeru</title>\n</head>\n\n<body>\n  <div class=\"uk-container uk-container-small\">\n    <div class=\"uk-position-center\">\n      <p class=\"k-logo uk-text-center\" style=\"font-size: 8em !important;\"></p>\n      <p class=\"uk-text-muted uk-text-center\">Please authenticate.</p>\n\n      <form action=\"/auth/\" method=\"POST\">\n        <fieldset class=\"uk-fieldset\">\n          <div class=\"uk-margin\">\n            <input class=\"uk-input\" type=\"password\" name=\"password\">\n          </div>\n\n          <button class=\"uk-button uk-button-primary uk-width-1\">Authenticate</button>\n        </fieldset>\n      </form>\n    </div>\n  </div>\n</body>\n\n</html>\n"
  },
  {
    "path": "static/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n\n  <link rel=\"apple-touch-icon\" sizes=\"180x180\" href=\"/static/apple-touch-icon.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"/static/favicon-32x32.png\">\n  <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"/static/favicon-16x16.png\">\n  <link rel=\"manifest\" href=\"/static/manifest.json\">\n\n  <title>Kikoeru</title>\n</head>\n\n<body>\n  <div id=\"root\"></div>\n</body>\n\n</html>\n"
  },
  {
    "path": "static/manifest.json",
    "content": "{\n  \"name\": \"Kikoeru\",\n  \"icons\": [\n    {\n      \"src\": \"/android-chrome-192x192.png\",\n      \"sizes\": \"192x192\",\n      \"type\": \"image/png\"\n    },\n    {\n      \"src\": \"/android-chrome-512x512.png\",\n      \"sizes\": \"512x512\",\n      \"type\": \"image/png\"\n    }\n  ],\n  \"theme_color\": \"#ffffff\",\n  \"background_color\": \"#ffffff\",\n  \"display\": \"standalone\",\n  \"start_url\": \"/\",\n  \"orientation\": \"portrait-primary\"\n}\n"
  },
  {
    "path": "webpack.config.js",
    "content": "const path = require('path');\nconst OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');\nconst MiniCssExtractPlugin = require('mini-css-extract-plugin');\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\nconst { CleanWebpackPlugin } = require('clean-webpack-plugin');\n\nconst production = process.argv[process.argv.indexOf('--mode') + 1] === 'production';\n\nmodule.exports = {\n  entry: ['babel-polyfill', './src/client/index.jsx'],\n  output: {\n    path: path.join(__dirname, 'dist'),\n    publicPath: '/',\n    filename: 'bundle.js',\n  },\n  module: {\n    rules: [{\n      test: /\\.(js|jsx)$/,\n      exclude: /node_modules/,\n      use: {\n        loader: 'babel-loader',\n      },\n    },\n    {\n      test: /\\.(css|less)$/,\n      use: [\n        {\n          loader: MiniCssExtractPlugin.loader,\n          options: { hmr: !production },\n        },\n        'css-loader',\n        'less-loader',\n      ],\n    },\n    {\n      test: /\\.(png|woff|woff2|eot|ttf|svg)$/,\n      loader: 'url-loader?limit=100000',\n    },\n    ],\n  },\n  resolve: {\n    extensions: ['*', '.js', '.jsx'],\n    alias: {\n      inferno: production ? 'inferno' : 'inferno/dist/index.dev.esm.js',\n      // 'uikit-util': 'uikit/src/js/util/index',\n      // uikit: 'uikit/src/js/uikit',\n    },\n  },\n  devServer: {\n    host: '0.0.0.0',\n    port: 3000,\n    open: true,\n    historyApiFallback: true,\n    proxy: {\n      '/api': 'http://localhost:8888',\n    },\n  },\n  plugins: [\n    new OptimizeCssAssetsPlugin(),\n    new MiniCssExtractPlugin(),\n    new CleanWebpackPlugin(),\n    new HtmlWebpackPlugin({\n      template: './static/index.html',\n    }),\n  ],\n  optimization: {\n    mangleWasmImports: true,\n    splitChunks: {\n      chunks: 'async',\n    },\n  },\n};\n"
  }
]