[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n\n# C extensions\n*.so\n\n# Distribution / packaging\nbin/\nbuild/\ndevelop-eggs/\neggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\n.tox/\n.coverage\n.cache\nnosetests.xml\ncoverage.xml\n\n# Translations\n*.mo\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The 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 to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When 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\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For 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\n  Developers 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\n  For 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\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, 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 to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The 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 of\nworks, 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\n  To \"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 an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"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\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the 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\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"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\n  The \"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\n  The \"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\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All 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\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No 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\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You 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\n  You 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\n  You 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 conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\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\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\n  A 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\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\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\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\n    Corresponding Source from a network server at no charge.\n\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\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\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A 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\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If 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\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding 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\n  When 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\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat 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\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\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All 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\n  If 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\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You 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\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, 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\n  Termination 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\n  You are not required to accept this License in order to receive or\nrun a 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\n  Each 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\n  An \"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\n  You 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\n  A \"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\n  A contributor's \"essential patent claims\" are all patent claims\nowned or 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\n  Each 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\n  In 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\n  If 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\n  If, 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\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing 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\n  If 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 this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding 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\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later 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\n  THERE 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 WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If 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\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If 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 terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"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 mail.\n\n  If 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 appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# _Spodcast_\n\n_Spodcast_ is a caching _Spotify_ podcast to RSS proxy. Using _Spodcast_ you can follow _Spotify_-hosted netcasts/podcasts using any player which supports RSS, thus enabling the use of older hardware which is not compatible with the _Spotify_ (web) app. _Spodcast_ consists of the main _Spodcast_ application - a Python 3 command line tool - and a PHP-based RSS feed generator. It uses the _librespot-python_ library to access the Spotift API. To use _Spodcast_ you need a (free) _Spotify_ account.\n_Spodcast_ only supports the _Spotify_ podcast service, it does not interface with the music streaming service.\n\n## How does it work\n\n_Spotify_ hosts podcasts through their proprietary API and does not offer an RSS feed, making it mandatory to use the _Spotify_ (web) app to follow these shows. This makes it impossible to follow _Spotify_-hosted shows on any device which does not support the _Spotify_ (web) app. *_Spodcast_* solves this problem by creating an RSS feed out of data returned through the _Spotify_ podcast API. This feed can be served by any web server which supports PHP. By running *_Spodcast_* through a task scheduler (*cron* on \\*nix, *Task Scheduler* on Windows) the feed will be kept up to date without the need for intervention. Have a look at these glorious *ASCIIGraphs™* which should answer all unasked questions:\n\n### _Spodcast_ regularly queries _Spotify_ for new episodes...\n```\n                  --------------\n                 |task scheduler|\n                  --------------\n                        |             ___________\n  -------   APIv1   ----V---         /           \\\n |Spotify|- - - - >|Spodcast|------>| File system |\n  -------           --------         \\___________/\n```\n### You want to listen to an episode using your old, unsupported but still functional phone...\n```\n                                           _____         ............\n   ___________          ----------        |     | . o O |bla bla bla.|\n  /           \\        |Web server|  RSS  | YOUR|        ````````````\n | File system |------>|  + PHP   |------>| OLD |\n  \\___________/         ----------        |PHONE|\n                                          |_____|\n\n```\nThus, by the simple expedient of using a piece of code which produces another piece of code which is used by yet another piece of code to speak to that old, creaky but still functional phone the latter is saved from early forced retirement. You can both feel virtuous for not adding another piece of waste to the pile, provident for not spending funds on a new device which does the same as the old one, smart for escaping the trap of planned obsolescence and whatever other emotion you prefer, including none whatsover.\n\n## Installation\n\n_Spodcast_ is available as an installable package on PyPi, just run:\n```\n$ pip install spodcast\n```\n...and you're set in case you only want to use _Spodcast_ from your own account. Run this command as root to install it globally which makes it available to e.g. the web server user (`www-data` on Debian and derived distributions), this is necessary if you want to make use of the RSS feed service.\n\n_Spodcast_ can be installed from  source by running `pip install .` (or `pip install -e .` if you want to be able to hack the code without needing to re-install after every change) from within the package root directory:\n```shell\n$ git clone https://github.com/Yetangitu/spodcast.git\n$ cd spodcast\n$ pip install .\n```\n\nOnce installed this way it can be uninstalled using `pip uninstall spodcast` if so required. If you're planning to use the RSS proxy and web UI you need to make sure the `spodcast` command is available to the web server user.\n\n## Usage with Docker: \n\nPre-built images are [available at Docker Hub](https://hub.docker.com/r/heywoodlh/spodcast). Refer to documentation below on how to build the image locally if that is desired.\n\n### A Note on Environment Variables:\n\nThe Spodcast images are built to either be configured exclusively through environment variables OR by passing arguments to the image -- if arguments are passed to the container any environment variables will be ignored.\n\nHere is the list of permitted environment variables with a brief description:\n\n| Variable | Default Value | Description | \n|----------|---------------|-------------|\n| SPOTIFY_PASSWORD | None | Spotify password |\n| SPOTIFY_USERNAME | None | Spotify username |\n| SPOTIFY_PODCAST_URLS | None | URLs of podcasts to download from spotify (separated by space) |\n| CRON_SCHEDULE | `0 0 * * Sun` | Cron schedule for how often [heywoodlh/spodcast-cron](https://hub.docker.com/r/heywoodlh/spodcast-cron) will attempt to download content from Spotify | \n| SPODCAST_ROOT | `/data` | Where all assets will go in the container filesystem | \n| SPODCAST_HTML | `${SPODCAST_ROOT}/html` | Where HTML content will be places in container filesystem |\n| SPODCAST_CONFIG_JSON | `${SPODCAST_ROOT}/spodcast.json` | Location of the spodcast config file | \n| SPOTIFY_CREDS_JSON | `${SPODCAST_ROOT}/creds.json` | Location of the file containing Spotify credentials that Spodcast will use to continue logging in |\n| SPOTIFY_RC_PATH | `${SPODCAST_ROOT}/spotify.rc` | Location of file containing creds to initially login | \n| MAX_EPISODES | `10` | Max amount of episodes to download per podcast | \n| LOG_LEVEL | `info` | Log level of Spodcast |\n| CHUNK_SIZE | `50000` | Download chunk size |\n| RSS_FEED | `yes` | Create an RSS feed for a web server | \n| TRANSCODE | `no` | Transcode to MP3 format (i.e. so iOS devices can play the audio files) | \n| LANGUAGE | `en` | Language of the content | \n| SKIP_EXISTING | `yes` | Do not re-download episodes that already exist on filesystem |\n\n`SPOTIFY_PASSWORD`, `SPOTIFY_USERNAME`, and `SPOTIFY_PODCAST_URLS` are the only ones that are absolutely required -- everything else has a default value that is considered sane that it will fall back to if left undefined.\n\n\n### Usage with Docker-Compose and environment variables:\n\nThe following `docker-compose.yml` (also available at [docker/docker-compose.yml](docker/docker-compose.yml)) should work to easily deploy Spodcast, a web server and PHP server:\n\n```\nservices:\n  spodcast-cron:\n    image: heywoodlh/spodcast-cron:latest\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    environment:\n      - CRON_SCHEDULE=0 * * * *\n      - SPOTIFY_PODCAST_URLS=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk\n      - SPOTIFY_PASSWORD=myawesomepassword\n      - SPOTIFY_USERNAME=email@awesome.com\n      - MAX_EPISODES=1\n      \n  spodcast-php:\n    image: php:7-fpm\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    user: \"101:101\"\n    networks:\n    - spodcast\n\n  spodcast-web:\n    image: heywoodlh/spodcast-web:latest\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    networks:\n    - spodcast\n    ports:\n      - 8080:80\n\nnetworks:\n  spodcast:\nvolumes:\n  spodcast_data:\n```\n\n*Note: if this is the first time running Spodcast, the web server will error out with a 404. That is due to no HTML content having been setup by Spodcast yet. When running this the first time, it would be recommended to set `CRON_SCHEDULE` to something a bit more aggressive like `* * * * *` so that way episodes will be downloaded every minute and then once the initial HTML content has been populated change the `CRON_SCHEDULE` to something less aggressive. \n\n### Using the Docker CLI and supplying arguments:\n\nPrepare `spodcast` directory (this example assumes you will store Spodcast's data in `/tmp/spodcast`):\n\n```\nmkdir -p /tmp/spodcast\n\necho 'spotify_username spotify_password' > /tmp/spodcast/spotify.rc\n```\n\nLogin to Spotify and configure `spodcast` initially:\n\n```\ndocker run -it -v /tmp/spodcast:/data heywoodlh/spodcast -c /data/spodcast.json --root-path /data/html --log-level info --credentials-location /data/creds.json -p -l /data/spotify.rc\n```\n\nNow run `spodcast` (this example will download The Joe Rogan Experience to `/tmp/spodcast/html` on the Docker host):\n\n```\ndocker run -it -v /tmp/spodcast:/data heywoodlh/spodcast -c /data/spodcast.json --log-level info --max-episodes 10 'https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk'\n```\n\n#### Build the image locally:\n\nIf you would prefer to build the image locally: \n\n```\ngit clone https://github.com/Yetangitu/Spodcast && cd Spodcast\n\ndocker build -t spodcast -f docker/Dockerfile .\n```\n\nDocker usage will be exactly the same as the examples above with the exception that you will want to replace the `heywoodlh/spodcast` image with `spodcast`.\n\n## Usage\nTo use _Spodcast_ you need a (free) _Spotify_ account, if you don't have one yet you'll need to take care of that first at https://www.spotify.com/signup/ . If you plan to use the RSS proxy feature you'll also need a web server to serve the RSS feed(s), any server which supports PHP will do here. See [Web server requirements](#web-server-configuration) for more information on how to configure the server.\n\nHere's `spodcast` displaying its help message:\n```\n$ spodcast -h\nusage: spodcast [-h] [-c CONFIG_LOCATION] [-p] [-v] [-l LOGIN] [--root-path ROOT_PATH]\n                [--skip-existing SKIP_EXISTING] [--retry RETRY] [--max-episodes MAX_EPISODES]\n                [--chunk-size CHUNK_SIZE] [--download-real-time DOWNLOAD_REAL_TIME]\n                [--language LANGUAGE] [--credentials-location CREDENTIALS_LOCATION]\n                [--rss-feed RSS_FEED] [--transcode TRANSCODE] [--log-level LOG_LEVEL]\n                [urls ...]\n\nA caching Spotify podcast to RSS proxy.\n\npositional arguments:\n  urls                  Download podcast episode(s) from a url. Can take multiple urls.\n\noptional arguments:\n  -h, --help            show this help message and exit\n  -c CONFIG_LOCATION, --config-location CONFIG_LOCATION\n                        Specify the spodcast.json location\n  -p, --prepare-feed    Installs RSS feed server code in ROOT_PATH.\n  -v, --version         show program's version number and exit\n  -l LOGIN, --login LOGIN\n                        Reads username and password from file passed as argument and stores\n                        credentials for later use.\n  --root-path ROOT_PATH\n                        set root path for podcast cache\n  --skip-existing SKIP_EXISTING\n                        [yes|no] skip files with the same name and size. Defaults to \"yes\".\n  --retry RETRY         retry count for Spotify API access\n  --max-episodes MAX_EPISODES\n                        number of episodes to download\n  --chunk-size CHUNK_SIZE\n                        download chunk size\n  --download-real-time DOWNLOAD_REAL_TIME\n                        simulate streaming client\n  --language LANGUAGE   preferred content language\n  --credentials-location CREDENTIALS_LOCATION\n                        path to credentials file. If a relative path is used the file will be\n                        stored in the same directory as the configuration file (-c\n                        /path/to/config.json -> /path/to).\n  --rss-feed RSS_FEED   [yes|no] add a (php) RSS feed server and related metadata for feed. To\n                        manage feeds, point a web server at the spodcast root path as configured\n                        using --root-path. Defaults to \"yes\".\n  --transcode TRANSCODE\n                        [yes|no] transcode ogg/vorbis to mp3 (where applicable) - only needed\n                        for devices which do not support open formats (e.g. iOS). Defaults to\n                        \"no\".\n  --log-level LOG_LEVEL\n                        log level (debug/info/warning/error/critical)\n```\n\n### Using _Spodcast_ to proxy _Spotify_ podcasts to RSS\nThe following example shows how to use the `spodcast` command to prepare the feed root directory and add a _Spotify_ account to be used. It specifies the configuration file to create (`-c /mnt/audio/podcast/spodcast.json`) and the root path where podcasts will be downloaded to (`--root-path /mnt/audio/spodcast`). The `-p` option tells _spodcast_ to prepare the RSS feed server in the root directory which will also be used to store the credential file created by the `-l spotify.rc` command. That `spotify.rc` file is a plain text file containing the username and password (separated by a single space character) to use to login to _Spotify_. It is only needed to create the stored credentials file(s) so it can be deleted once _Spotcast_ is up and running. If one or more of your preferred listening devices does not supports open audio codecs - e.g. because it runs iOS - you can use `--transcode yes` to enable transcoding of such streams to `mp3`. Transcoding is performed using _ffmpeg_ which needs to be available on your _Spodcast_ host. It can take a considerable amount of time depending on the hardware you're using to run _Spodcast_ so only enable this option when there are no other options.\n```\nspodcast -c /mnt/audio/podcast/spodcast.json --root-path /mnt/audio/spodcast -p -l /home/exampleuser/spotify.rc\n```\nConfigure the [Web server](#web-server-configuration) using the path given as root path (in this example that would be `/mnt/audio/spodcast`) as web root, making sure to exclude files with `.json` and `.info` extenstions to avoid leaking your _Spotify_ credentials (even though these are stored in hashed form using hashed file names). Now point a browser at the site you configured for _Spodcast_ and you're ready to add the first show or episode. This is done easily by entering the _Spotify_ show/episode url (e.g. `https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk` for _The Joe Rogan Experience_ for the whole show, `https://open.spotify.com/episode/2rYwwE7hcpgsDo9vRVHxAI?si=24fb00294b7f40db` for a specific episode, notice the `show` and `episode` parts of these links) and either hitting _Enter_ or clicking the _Add_ button. _Spodcast_ will now create a directory under the given root path, add the `.index.php` RSS feed generator script and the `index.info` show info URL used by that script and the RSS manager script and whatever episode(s) you decided to sync.\n\nOnce the initial feed has been created it can be kept up to date by enabling the feed update service found in the _Settings_ menu. Select the update frequency and the start time and click _Update_, this will create a _cron_ job for the web server which will run the _Spodcast_ manager script to update feeds. If the system scheduler can not be used for some reason - e.g. because the web server user is not allowed to create cron jobs or because the web server is run from a Docker container which does not support cron jobs - you can use the _webcron_ endpoint to initiate update runs. Just point any web client at `SPODCAST_URL/?action=update_shows` to run an update and get a json-encoded report on what has been updated. By running a command line web client - _curl_ and _wget_ are good options - as a user cron job at regular intervals the feeds can be kept up to date.\n\nWhile the update frequency is configured for all shows simultaneously this is not the case for the number of episodes to _sync_ and the number to _keep_ in cache, these can be configured individually for each show. The idea here is that some shows may publish more than one episode between update intervals so by fetching the last X episodes on each update nothing will be missed. Episodes which have already been synced will not be synced again so no time or bandwidth is wasted. In the same vein the number of episodes to _keep_ can be configured to make sure your RSS clients have the opportunity to download these before they are rotated out of cache. Once more than X (being the value chosen for _keep_) episodes have been downloaded the oldest episodes will be deleted to keep the total no more than X.\n\nPoint your RSS clients at the _Spodcast_ feed URL for this show and you should see new episodes appear after they were published on _Spotify_ and subsequently picked up on the next update. For the example given in the [Web server requirements](#web-server-configuration) example that URL would be `http://spodcast.example.org/The_Joe_Rogan_Experience`.\n\nHere's what the Spodcast feed manager looks like:\n\n![Spodcast feed manager](/resources/screenshots/spodcast_showing_a_list_of_shows_likely_to_disappear_from_spotify_sooner_or_later.png?raw=true \"Spodcast feed manager\")\n\n...and on smaller screens it looks like this:\n\n![Spodcast feed manager on a small screen](/resources/screenshots/spodcast_is_responsive.png?raw=true \"Spodcast feed manager, vertical layout on smaller screens\")\n\nThe settings screen is simple and concise:\n\n![Spodcast feed manager settings](/resources/screenshots/spodcast_settings.png?raw=true \"Spodcast feed manager: Settings\")\n\nEach show has its own _sync_ and _keep_ settings. Use the _Delete_ button to, well, delete the show. Use _Refresh_ to retrieve the last [_sync_] episodes, skipping those which have already been synced.\n\n![Show controls](/resources/screenshots/sync_keep_delete_refresh.png?raw=true \"Configure _sync_ and _keep_ settings for each show\")\n\n### Using the _Spodcast_ CLI command to download a single episode\n_Spodcast_ can also be used stand-alone (without the need for a web server) by either just ignoring the feed-related files (`.index.php`, `index.info` plus a `*.info` file for every episode) or by disabling the RSS feed using `--rss no` on the command line. Instead of using the `-l spotify.rc` command to add _Spotify_ credentials it is possible to point _Spotcast_ at a single `credentials.json` file (which will be created if it does not exist yet), `spodcast` wil ask for the username and password when needed. To get single episode links use the _Spotify_ web app and select _Share->Copy Episode Link_ from the episode menu (three dots in the top-right corner of the episode block). The following example shows (an already configured instance of) `spodcast` ready to download a single episode:\n```\nspodcast -c ~/.config/spodcast/spodcast.json --credentials-location ~/.config/spodcast/credentials.json --rss-feed no https://open.spotify.com/episode/2rYwwE7hcpgsDo9vRVHxAI?si=24fb00294b7f40db\n```\nLike in the previous example _Spodcast_ will create a directory under the root path with the same name as the show from which the episode is downloaded. The episode will be downloaded into this directory under a `SHOW_NAME_-__EPISODE_NAME.[ogg|mp3]` name. Point a mediaplayer of choice at this file to play the episode.\nIn \"manual\" mode _Spodcast_ does not do anything by itself, feeds can be kept up to date by running _Spotcast_ with the required settings for `--max-episodes` (which is the value used for _sync_ in the web UI) and the show URL. Here's how to update the _The Joe Rogan Experience_ show using the `spodcast` CLI command, syncing the last 3 episodes:\n```\nspodcast -c ~/.config/spodcast/spodcast.json --rss-feed no --max-episodes 3 https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk`\n```\n## Web server configuration\n_Spodcast_ places a hidden `.index.php` file in the root path and each show directory. The one in the root directory is used to manage feeds while those in the show directories produce RSS feeds based on the information found in all `*.info` files in that directory. Configure the server to serve those `.index.php` files as index to make things work as intended. Don't forget to block all web access to files ending in `.json` and `.info` to make sure you _Spotify_ credentials (which are stored in hashed form in files named `spodcast-cred-MD5_HASH_OF_SPOTIFY_USER_NAME.json` in the root path) can not be accessed. Especially when using the transcoding feature (`--transcode yes`) on less powerful hardware (Raspberry Pi etc.) it can be necessary to increase the timeout for php-fpm/proxy/fastcgi requests. For _nginx_ the following should suffice to produce an unencrypted (HTTP) feed under the domain name `spodcast.example.org` given a feed root directory (as configured using `--root-path`) of `/mnt/audio/spodcast` with _php-fpm 7.4_ listening on `unix:/run/php/php7.4-fpm.sock`, using a 5-minute timeout for fastcgi requests:\n```\nserver {\n        listen 80;\n        listen [::]:80;\n        server_name spodcast.example.org;\n\n        root /mnt/audio/spodcast;\n\n        index .index.php;\n\n        fastcgi_read_timeout 300;\n        fastcgi_send_timeout 300;\t\n\n        # these files should not be accessible\n        location ~\\.(json|info)$ {\n                deny all;\n                return 404;\n        }\n\n        location / {\n                try_files $uri $uri/ =404;\n        }\n\n        location ~ \\.php$ {\n                include snippets/fastcgi-php.conf;\n                fastcgi_pass unix:/run/php/php7.4-fpm.sock;\n        }\n}\n```\nExamples for other web servers can be found elsewhere, this is basically a default PHP configuration with the only difference being that `.index.php` is a hidden file.\n"
  },
  {
    "path": "docker/Dockerfile",
    "content": "FROM python:3-alpine\n\nCOPY . /app\nWORKDIR /app\n\nRUN apk --no-cache add gcc libc-dev ffmpeg bash \\\n\t&& pip3 install .\n\nVOLUME [\"/data\"]\nWORKDIR /data\n\nCOPY docker/run.sh /run.sh\n\nENTRYPOINT [\"/run.sh\"]\n\nLABEL description=\"Spodcast is a caching Spotify podcast to RSS proxy. \\\nUsing Spodcast you can follow Spotify-hosted netcasts/podcasts using any \\\nplayer which supports RSS, thus enabling the use of older hardware which \\\nis not compatible with the Spotify (web) app.\"\nLABEL version=\"0.5.2\"\nLABEL org.opencontainers.image.authors=\"Yetangitu and others\"\n\n"
  },
  {
    "path": "docker/Dockerfile.cron",
    "content": "FROM heywoodlh/spodcast:latest\n\nCOPY docker/cron.sh /cron.sh\n\nLABEL description=\"Spodcast is a caching Spotify podcast to RSS proxy. \\\nUsing Spodcast you can follow Spotify-hosted netcasts/podcasts using any \\\nplayer which supports RSS, thus enabling the use of older hardware which \\\nis not compatible with the Spotify (web) app.\"\nLABEL version=\"0.5.2\"\nLABEL org.opencontainers.image.authors=\"Yetangitu and others\"\n\nENTRYPOINT /cron.sh\n"
  },
  {
    "path": "docker/Dockerfile.web",
    "content": "FROM nginx:stable\n\nRUN apt-get update && apt-get install -y nginx-full \\\n\t&& rm -rf /var/lib/apt/lists/* \\\n\t&& rm /etc/nginx/conf.d/default.conf \\\n\t&& rm /etc/nginx/sites-enabled/default\n\nCOPY docker/nginx/nginx.conf /etc/nginx/nginx.conf\nCOPY docker/nginx/sites-enabled /etc/nginx/sites-enabled\n"
  },
  {
    "path": "docker/cron.sh",
    "content": "#!/usr/bin/env bash\n\n## Set default cron schedule\n[[ -n ${CRON_SCHEDULE} ]] || export CRON_SCHEDULE=\"0 0 * * Sun\"\n\n## Variables for /run.sh\n[[ -n ${SPODCAST_ROOT} ]] || export SPODCAST_ROOT='/data'\n[[ -n ${SPODCAST_HTML} ]] || export SPODCAST_HTML=\"${SPODCAST_ROOT}/html\"\n[[ -n ${SPODCAST_CONFIG_JSON} ]] || export SPODCAST_CONFIG_JSON=\"${SPODCAST_ROOT}/spodcast.json\"\n[[ -n ${SPOTIFY_CREDS_JSON} ]] || export SPOTIFY_CREDS_JSON=\"${SPODCAST_ROOT}/creds.json\"\n[[ -n ${SPOTIFY_RC_PATH} ]] || export SPOTIFY_RC_PATH=\"${SPODCAST_ROOT}/spotify.rc\"\n[[ -n ${SPOTIFY_PASSWORD} ]] || export creds_supplied='false'\n[[ -n ${SPOTIFY_USERNAME} ]] || export creds_supplied='false'\n[[ -n ${MAX_EPISODES} ]] || export MAX_EPISODES='10'\n[[ -n ${LOG_LEVEL} ]] || export LOG_LEVEL='info'\n[[ -n ${CHUNK_SIZE} ]] || export CHUNK_SIZE='50000'\n[[ -n ${RSS_FEED} ]] || export RSS_FEED='yes'\n[[ -n ${TRANSCODE} ]] || export TRANSCODE='no'\n[[ -n ${LANGUAGE} ]] || export LANGUAGE='en'\n[[ -n ${SKIP_EXISTING} ]] || export SKIP_EXISTING='yes'\n\n[[ ${creds_supplied} == 'false' ]] \\\n    && echo 'Please set the SPOTIFY_USERNAME and SPOTIFY_PASSWORD variables. Exiting.' \\\n    && exit 1\n\n## Setup cron\necho SHELL=/bin/bash > /tmp/cron\necho PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin >> /tmp/cron\necho \"${CRON_SCHEDULE} SPODCAST_ROOT=\\\"${SPODCAST_ROOT}\\\" SPODCAST_HTML=\\\"${SPODCAST_HTML}\\\" SPODCAST_CONFIG_JSON=\\\"${SPODCAST_CONFIG_JSON}\\\" SPOTIFY_CREDS_JSON=\\\"${SPOTIFY_CREDS_JSON}\\\" SPOTIFY_RC_PATH=\\\"${SPOTIFY_RC_PATH}\\\" SPOTIFY_PASSWORD=\\\"${SPOTIFY_PASSWORD}\\\" SPOTIFY_USERNAME=\\\"${SPOTIFY_USERNAME}\\\" MAX_EPISODES=\\\"${MAX_EPISODES}\\\" LOG_LEVEL=\\\"${LOG_LEVEL}\\\" CHUNK_SIZE=\\\"${CHUNK_SIZE}\\\" RSS_FEED=\\\"${RSS_FEED}\\\" TRANSCODE=\\\"${TRANSCODE}\\\" LANGUAGE=\\\"${LANGUAGE}\\\" SKIP_EXISTING=\\\"${SKIP_EXISTING}\\\" /run.sh\"  >> /tmp/cron\n\necho \"* * * * * chown -R 101:101 ${SPODCAST_HTML}\" >> /tmp/cron\n\ncrontab /tmp/cron\nrm /tmp/cron\n\ncrond -l 0 -d 0 -f\n"
  },
  {
    "path": "docker/docker-compose.yml",
    "content": "services:\n  spodcast-cron:\n    image: heywoodlh/spodcast-cron:latest\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    environment:\n      - CRON_SCHEDULE=0 * * * *\n      - SPOTIFY_PODCAST_URLS=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk\n      - SPOTIFY_PASSWORD=myawesomepassword\n      - SPOTIFY_USERNAME=email@awesome.com\n      - MAX_EPISODES=1\n      \n  spodcast-php:\n    image: php:7-fpm\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    user: \"101:101\"\n    networks:\n    - spodcast\n\n  spodcast-web:\n    image: heywoodlh/spodcast-web:latest\n    volumes:\n      - spodcast_data:/data\n    restart: unless-stopped\n    networks:\n    - spodcast\n    ports:\n      - 8080:80\n\nnetworks:\n  spodcast:\nvolumes:\n  spodcast_data:\n"
  },
  {
    "path": "docker/nginx/nginx.conf",
    "content": "user  nginx;\nworker_processes  auto;\n\npid        /var/run/nginx.pid;\n\nevents {\n    worker_connections  1024;\n}\n\nhttp {\n    include       /etc/nginx/mime.types;\n    default_type  application/octet-stream;\n\n    log_format  main  '$remote_addr - $remote_user [$time_local] \"$request\" '\n                      '$status $body_bytes_sent \"$http_referer\" '\n                      '\"$http_user_agent\" \"$http_x_forwarded_for\"';\n\n    sendfile        on;\n    #tcp_nopush     on;\n\n    keepalive_timeout  65;\n\n    #gzip  on;\n\n    include /etc/nginx/conf.d/*.conf;\n    include /etc/nginx/sites-enabled/*;\n}\n"
  },
  {
    "path": "docker/nginx/sites-enabled/spodcast",
    "content": "server {\n        listen 80;\n        listen [::]:80;\n\n        root /data/html;\n\t\n        index .index.php;\n\n        # these files should not be accessible\n        location ~\\.(json|info)$ {\n                deny all;\n                return 404;\n        }\n\n        location / {\n                try_files $uri $uri/ =404;\n        }\n\n        location ~ \\.php$ {\n                include snippets/fastcgi-php.conf;\n                fastcgi_pass spodcast-php:9000;\n        }\n}\n"
  },
  {
    "path": "docker/run.sh",
    "content": "#!/usr/bin/env bash\n\n## If the following variables are not defined, set defaults\n[[ -n ${SPODCAST_ROOT} ]] || export SPODCAST_ROOT='/data'\n[[ -n ${SPODCAST_HTML} ]] || export SPODCAST_HTML=\"${SPODCAST_ROOT}/html\"\n[[ -n ${SPODCAST_CONFIG_JSON} ]] || export SPODCAST_CONFIG_JSON=\"${SPODCAST_ROOT}/spodcast.json\"\n[[ -n ${SPOTIFY_CREDS_JSON} ]] || export SPOTIFY_CREDS_JSON=\"${SPODCAST_ROOT}/creds.json\"\n[[ -n ${SPOTIFY_RC_PATH} ]] || export SPOTIFY_RC_PATH=\"${SPODCAST_ROOT}/spotify.rc\"\n[[ -n ${SPOTIFY_PASSWORD} ]] || export creds_supplied='false'\n[[ -n ${SPOTIFY_USERNAME} ]] || export creds_supplied='false'\n[[ -n ${MAX_EPISODES} ]] || export MAX_EPISODES='10'\n[[ -n ${LOG_LEVEL} ]] || export LOG_LEVEL='info'\n[[ -n ${CHUNK_SIZE} ]] || export CHUNK_SIZE='50000'\n[[ -n ${RSS_FEED} ]] || export RSS_FEED='yes'\n[[ -n ${TRANSCODE} ]] || export TRANSCODE='no'\n[[ -n ${LANGUAGE} ]] || export LANGUAGE='en'\n[[ -n ${SKIP_EXISTING} ]] || export SKIP_EXISTING='yes'\n\n## If Spotify credentials were supplied, create ${SPODCAST_ROOT}/spotify.rc\n[[ ${creds_supplied} == 'false' ]] || echo \"${SPOTIFY_USERNAME} ${SPOTIFY_PASSWORD}\" > ${SPODCAST_ROOT}/spotify.rc\n\n## If no arguments were supplied, then use environment variables\nif [[ -z \"$@\" ]]\nthen\n\t## If SPOTIFY_PODCAST_URLS is defined, then run Spodcast\n\tif [[ -n ${SPOTIFY_PODCAST_URLS} ]]\n\tthen\n\t\t## If ${SPOTIFY_RC_PATH} file exists\n\t\tif [[ -e ${SPOTIFY_RC_PATH} ]]\n\t\tthen\n\t\t# Login first and then run spodcast\n\t\t\t/usr/local/bin/spodcast \\\n\t\t\t\t-c \"${SPODCAST_CONFIG_JSON}\" \\\n\t\t\t\t--root-path \"${SPODCAST_HTML}\" \\\n\t\t\t\t--log-level \"${LOG_LEVEL}\" \\\n\t\t\t\t--credentials-location \"${SPOTIFY_CREDS_JSON}\" \\\n\t\t\t\t-p -l ${SPOTIFY_RC_PATH} \\\n\t\t\t\t&& /usr/local/bin/spodcast \\\n\t\t\t\t\t-c ${SPODCAST_CONFIG_JSON} \\\n\t\t\t\t\t--log-level ${LOG_LEVEL} \\\n\t\t\t\t\t--max-episodes ${MAX_EPISODES} \\\n\t\t\t\t\t\"${SPOTIFY_PODCAST_URLS}\"\n\t\telse\n\t\t\techo \"SPOTIFY_PODCAST_URLS is defined, but no credentials were detected. Please set the SPOTIFY_USERNAME and SPOTIFY_PASSWORD variables.\"\n\t\t\texit 1\n\t\tfi\n\t## If SPOTIFY_PODCAST_URLS is not defined and no arguments were supplied, just show the help message\n\telse\n\t\t/usr/local/bin/spodcast --help\t\n\tfi\nfi\n\n## If arguments were supplied, do not use environment variables\n[[ -n $@ ]] && /usr/local/bin/spodcast \"$@\"\n"
  },
  {
    "path": "install.sh",
    "content": "pip3 install -e .\n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\nname = spodcast\nversion = 0.5.2\ndescription = A caching Spotify podcast to RSS proxy.\nlong_description = file:README.md\nlong_description_content_type = text/markdown\nurl = https://github.com/Yetangitu/spodcast.git\nproject_urls =\n    Bug Tracker = https://github.com/Yetangitu/spodcast/issues\nauthor = yetangitu\nauthor_email = github-f@unternet.org\nlicence = GPLv3\nclassifiers =\n    License :: OSI Approved :: GNU General Public License v3 (GPLv3)\n    Programming Language :: Python :: 3.9\n    Programming Language :: PHP\nplatforms = any\n\n[options]\npackages =\n    spodcast\ninstall_requires =\n    librespot >= 0.0.9\n    pybase62\n    ffmpeg-python\n    setuptools\ninclude_package_data =\n    True\n\n[options.entry_points]\nconsole_scripts:\n    spodcast = spodcast.__main__:main\n"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup\n\nif __name__ == \"__main__\":\n    setup()\n"
  },
  {
    "path": "spodcast/__init__.py",
    "content": ""
  },
  {
    "path": "spodcast/__main__.py",
    "content": "import argparse\nimport pkg_resources\n\nfrom spodcast.app import client\nfrom spodcast.config import CONFIG_VALUES\n\ndef main():\n    parser = argparse.ArgumentParser(prog='spodcast', description='A caching Spotify podcast to RSS proxy.')\n    parser.add_argument('-c', '--config-location',\n                        type=str,\n                        help='Specify the spodcast.json location')\n\n    parser.add_argument('-p', '--prepare-feed',\n                       action='store_true',\n                       help='Installs RSS feed server code in ROOT_PATH.')\n\n    parser.add_argument('-v', '--version',\n                       action='version',\n                       version = '%(prog)s ' + pkg_resources.require(\"Spodcast\")[0].version)\n\n    group = parser.add_mutually_exclusive_group(required=True)\n    group.add_argument('urls',\n                       type=str,\n                       # action='extend',\n                       default='',\n                       nargs='*',\n                       help='Download podcast episode(s) from a url. Can take multiple urls.')\n\n    group.add_argument('-l', '--login',\n                       type=str,\n                       help='Reads username and password from file passed as argument and stores credentials for later use.')\n\n    for configkey in CONFIG_VALUES:\n        parser.add_argument(CONFIG_VALUES[configkey]['arg'],\n                            type=str,\n                            default=None,\n                            help=CONFIG_VALUES[configkey]['help'])\n\n    parser.set_defaults(func=client)\n\n    args = parser.parse_args()\n    args.func(args)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "spodcast/app.py",
    "content": "import logging\n\nfrom itertools import islice\nfrom librespot.audio.decoders import AudioQuality\nfrom librespot.metadata import ShowId, EpisodeId\n\nfrom spodcast.podcast import download_episode, get_episodes\nfrom spodcast.utils import regex_input_for_urls\nfrom spodcast.spodcast import Spodcast\n\nlog = logging.getLogger(__name__)\n\ndef client(args) -> None:\n    Spodcast(args)\n    Spodcast.DOWNLOAD_QUALITY = AudioQuality.NORMAL\n\n    if args.urls:\n        for spotify_url in args.urls:\n            episode_id_str, show_id_str = regex_input_for_urls(spotify_url)\n            log.debug(f\"episode_id_str {episode_id_str}. show_id_str {show_id_str}\")\n            if episode_id_str is not None:\n                episode_id = EpisodeId.from_base62(episode_id_str).hex_id()\n                log.debug(\"episode_id: %s\", episode_id)\n                download_episode(episode_id)\n            elif show_id_str is not None:\n                show_id = ShowId.from_base62(show_id_str)\n                log.debug(\"show_id: %s\", show_id)\n                for episode_id in islice(get_episodes(show_id), Spodcast.CONFIG.get_max_episodes()):\n                    log.debug(\"episode_id: %s\", episode_id)\n                    download_episode(episode_id)\n"
  },
  {
    "path": "spodcast/config.py",
    "content": "import json\nimport os\nimport pkg_resources\nimport sys\nfrom typing import Any\n\nCONFIG_FILE_PATH = '../spodcast.json'\n\nCONFIG_DIR = 'CONFIG_DIR'\nCONFIG_PATH = 'CONFIG_PATH'\nVERSION = 'VERSION'\nVERSION_STR = pkg_resources.require(\"Spodcast\")[0].version\n\nROOT_PATH = 'ROOT_PATH'\nSKIP_EXISTING_FILES = 'SKIP_EXISTING_FILES'\nCHUNK_SIZE = 'CHUNK_SIZE'\nDOWNLOAD_REAL_TIME = 'DOWNLOAD_REAL_TIME'\nLANGUAGE = 'LANGUAGE'\nCREDENTIALS_LOCATION = 'CREDENTIALS_LOCATION'\nRETRY = 'RETRY'\nMAX_EPISODES = 'MAX_EPISODES'\nLOG_LEVEL = 'LOG_LEVEL'\nRSS_FEED = 'RSS_FEED'\nTRANSCODE = 'TRANSCODE'\n\nCONFIG_VALUES = {\n    ROOT_PATH:            { 'default': '../Spodcast/',\n                            'type': str,\n                            'arg': '--root-path',\n                            'help': 'set root path for podcast cache' },\n    SKIP_EXISTING_FILES:  { 'default': 'True',\n                            'type': bool,\n                            'arg': '--skip-existing',\n                            'help': '[yes|no] skip files with the same name and size. Defaults to \"yes\".' },\n    RETRY:                { 'default': 5,\n                            'type': int,\n                            'arg': '--retry',\n                            'help': 'retry count for Spotify API access' },\n    MAX_EPISODES:         { 'default': 1000,\n                            'type': int,\n                            'arg': '--max-episodes',\n                            'help': 'number of episodes to download' },\n    CHUNK_SIZE:           { 'default': 50000,\n                            'type': int,\n                            'arg': '--chunk-size',\n                            'help': 'download chunk size' },\n    DOWNLOAD_REAL_TIME:   { 'default': 'False',\n                            'type': bool,\n                            'arg': '--download-real-time',\n                            'help': 'simulate streaming client' },\n    LANGUAGE:             { 'default': 'en',\n                            'type': str,\n                            'arg': '--language',\n                            'help': 'preferred content language' },\n    CREDENTIALS_LOCATION: { 'default': 'credentials.json',\n                            'type': str,\n                            'arg': '--credentials-location',\n                            'help': 'path to credentials file. If a relative path is used the file will be stored in the same directory as the configuration file (-c /path/to/config.json -> /path/to).' },\n    RSS_FEED:             { 'default': 'True',\n                            'type': bool,\n                            'arg': '--rss-feed',\n                            'help': '[yes|no] add a (php) RSS feed server and related metadata for feed. To manage feeds, point a web server at the spodcast root path as configured using --root-path. Defaults to \"yes\".' },\n    TRANSCODE:            { 'default': 'False',\n                            'type': bool,\n                            'arg': '--transcode',\n                            'help': '[yes|no] transcode ogg/vorbis to mp3 (where applicable) - only needed for devices which do not support open formats (e.g. iOS). Defaults to \"no\".' },\n    LOG_LEVEL:            { 'default': 'warning',\n                            'type': str,\n                            'arg': '--log-level',\n                            'help': 'log level (debug/info/warning/error/critical)' }\n}\n\nclass Config:\n    Values = {}\n\n    @classmethod\n    def load(cls, args) -> None:\n        app_dir = os.path.dirname(__file__)\n        dump_config=False\n\n        config_fp = CONFIG_FILE_PATH\n        if args.config_location:\n            config_fp = args.config_location\n\n        true_config_file_path = os.path.join(app_dir, config_fp)\n\n        # Load config from spodcast.json\n\n        if not os.path.exists(true_config_file_path):\n            dump_config=True\n            os.makedirs(os.path.dirname(true_config_file_path), exist_ok=True)\n            cls.Values = cls.get_default_json()\n        else:\n            with open(true_config_file_path, encoding='utf-8') as config_file:\n                jsonvalues = json.load(config_file)\n                cls.Values = {}\n                for key in CONFIG_VALUES:\n                    if key in jsonvalues:\n                        cls.Values[key] = cls.parse_arg_value(key, jsonvalues[key])\n\n        # Add default values for missing keys\n\n        for key in CONFIG_VALUES:\n            if key not in cls.Values:\n                cls.Values[key] = cls.parse_arg_value(key, CONFIG_VALUES[key]['default'])\n                dump_config=True\n\n        # Override config from commandline arguments\n\n        for key in CONFIG_VALUES:\n            if key.lower() in vars(args) and vars(args)[key.lower()] is not None:\n                cls.Values[key] = cls.parse_arg_value(key, vars(args)[key.lower()])\n\n        # dump current config to config file\n\n        if dump_config:\n            with open(true_config_file_path, 'w', encoding='utf-8') as config_file:\n                json.dump(cls.get_config_json(), config_file, indent=4)\n\n        # these values should not be overriden\n\n        cls.Values[CONFIG_DIR] = os.path.dirname(true_config_file_path)\n        cls.Values[CONFIG_PATH] = str(true_config_file_path)\n        cls.Values[VERSION] = str(VERSION_STR)\n\n    @classmethod\n    def get_default_json(cls) -> Any:\n        r = {}\n        for key in CONFIG_VALUES:\n            r[key] = CONFIG_VALUES[key]['default']\n        return r\n\n    @classmethod\n    def get_config_json(cls) -> Any:\n        r = {}\n        for key in CONFIG_VALUES:\n            r[key]=cls.Values[key]\n        return r\n\n    @classmethod\n    def parse_arg_value(cls, key: str, value: Any) -> Any:\n        if type(value) == CONFIG_VALUES[key]['type']:\n            return value\n        if CONFIG_VALUES[key]['type'] == str:\n            return str(value)\n        if CONFIG_VALUES[key]['type'] == int:\n            return int(value)\n        if CONFIG_VALUES[key]['type'] == bool:\n            if str(value).lower() in ['yes', 'true', '1']:\n                return True\n            if str(value).lower() in ['no', 'false', '0']:\n                return False\n            raise ValueError(\"Not a boolean: \" + value)\n        raise ValueError(\"Unknown Type: \" + value)\n\n    @classmethod\n    def get(cls, key: str) -> Any:\n        return cls.Values.get(key)\n\n    @classmethod\n    def get_config_dir(cls) -> str:\n        return cls.get(CONFIG_DIR)\n\n    @classmethod\n    def get_root_path(cls) -> str:\n        return os.path.join(os.path.dirname(__file__), cls.get(ROOT_PATH))\n\n    @classmethod\n    def get_skip_existing_files(cls) -> bool:\n        return cls.get(SKIP_EXISTING_FILES)\n\n    @classmethod\n    def get_chunk_size(cls) -> int:\n        return cls.get(CHUNK_SIZE)\n\n    @classmethod\n    def get_language(cls) -> str:\n        return cls.get(LANGUAGE)\n\n    @classmethod\n    def get_download_real_time(cls) -> bool:\n        return cls.get(DOWNLOAD_REAL_TIME)\n\n    @classmethod\n    def get_credentials_location(cls) -> str:\n        credentials_location = cls.get(CREDENTIALS_LOCATION)\n        return credentials_location if os.path.isabs(credentials_location) else os.path.join(cls.get(CONFIG_DIR), cls.get(CREDENTIALS_LOCATION))\n\n    @classmethod\n    def get_retry(cls) -> int:\n        return cls.get(RETRY)\n\n    @classmethod\n    def get_max_episodes(cls) -> int:\n        return cls.get(MAX_EPISODES)\n\n    @classmethod\n    def get_rss_feed(cls) -> bool:\n        return cls.get(RSS_FEED)\n\n    @classmethod\n    def get_transcode(cls) -> bool:\n        return cls.get(TRANSCODE)\n\n    @classmethod\n    def get_log_level(cls) -> str:\n        return str(cls.get(LOG_LEVEL)).upper()\n\n    @classmethod\n    def get_bin_path(cls) -> str:\n        return str(sys.argv[0])\n\n    @classmethod\n    def get_config_path(cls) -> str:\n        return cls.get(CONFIG_PATH)\n\n    @classmethod\n    def get_version_str(cls) -> str:\n        return cls.get(VERSION)\n\n    @classmethod\n    def get_version_int(cls) -> int:\n        return int(cls.get(VERSION).replace('.',''))\n"
  },
  {
    "path": "spodcast/const.py",
    "content": "TYPE = 'type'\nLIMIT = 'limit'\nOFFSET = 'offset'\nCREDENTIALS_PREFIX = 'spodcast-cred'\nUSER_READ_EMAIL = 'user-read-email'\nFILE_EXISTS = -1\nOPEN_SPOTIFY_URL = 'open.spotify.com'\nIMAGE_CDN = lambda image_id_hex: f'https://i.scdn.co/image/{image_id_hex}'\n"
  },
  {
    "path": "spodcast/feedgenerator.py",
    "content": "import re\n\nRSS_FEED_FILE_NAME = '.index.php'\nRSS_FEED_INFO_EXTENSION = 'info'\nRSS_FEED_SHOW_INDEX = 'index'\nRSS_FEED_SHOW_IMAGE = 'image.jpg'\nRSS_FEED_VERSION = '$SPODCAST_VERSION$ '\nVERSION_NOT_FOUND = 0\n\ndef get_index_version(filename) -> str:\n    with open(filename, 'rb') as f:\n        for line in f.readlines():\n            m = re.search(RSS_FEED_VERSION + ' (\\d+.\\d+.\\d+)', str(line))\n            if m:\n                return int(m[1].replace('.',''))\n\n    return VERSION_NOT_FOUND\n\n\ndef RSS_FEED_CODE(version):\n    return r'''<?php\n/* ''' + RSS_FEED_VERSION + version + r''' */\nconst SHOW_INDEX = \"''' + RSS_FEED_SHOW_INDEX + r'''\";\nconst INFO = \"''' + RSS_FEED_INFO_EXTENSION + r'''\";\n$PROTOCOL = (empty($_SERVER['HTTPS'])) ? \"http://\" : \"https://\";\nheader(\"Content-type: text/xml\");\n$feed_name = \"Spodcast autofeed\";\n$feed_description = \"Spodcast autofeed\";\n$base_url = strtok($PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '?');\n$feed_logo = \"$base_url/''' + RSS_FEED_SHOW_IMAGE + r'''\";\n$feed_link = $base_url;\n$allowed_extensions = array('mp4','m4a','aac','mp3','ogg');\n\n$sinfo=SHOW_INDEX.\".\".INFO;\nif(file_exists($sinfo)) {\n    $json=file_get_contents($sinfo);\n    $info=json_decode($json);\n    $feed_name=$info->title;\n    $feed_description=$info->description;\n    $feed_link=$info->link;\n}\n\n?>\n<?php echo '<?xml version=\"1.0\" encoding=\"utf-8\"?>';  // use php to output the \"<?\" ?>\n<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\" >\n    <channel>\n        <title><?php echo $feed_name; ?></title>\n        <link><?php echo $feed_link; ?></link>\n        <image>\n            <url><?php echo $feed_logo; ?></url>\n            <title><?php echo $feed_name; ?></title>\n            <link><?php echo $feed_link; ?></link>\n        </image>\n        <description><?php echo $feed_description; ?></description>\n        <atom:link href=\"<?php echo $base_url; ?>\" rel=\"self\" type=\"application/rss+xml\" />\n<?php\n$raw_files = scandir ('.');\nusort($raw_files, function($a, $b) {\n    return filemtime($a) < filemtime($b);\n});\n\nforeach ($raw_files as &$raw_file) {\n    $raw_file_info = pathinfo($raw_file);\n    $extension = strtolower($raw_file_info['extension']);\n    if(!empty($extension)) {\n        if(in_array ($extension,$allowed_extensions)) {\n            $finfo=$raw_file.\".\".INFO;\n            if(file_exists($finfo)) {\n                $json=file_get_contents($finfo);\n                $info=json_decode($json);\n                echo \"        <item>\\n\";\n                echo \"            <title>\".$info->title.\"</title>\\n\";\n                echo \"            <description>\".$info->description.\"</description>\\n\";\n                echo \"            <guid>\".$info->guid.\"</guid>\\n\";\n                echo \"            <link>\".$base_url.$info->filename.\"</link>\\n\";\n                echo \"            <enclosure url=\\\"\".$base_url.$info->filename.\"\\\" length=\\\"\".$info->size.\"\\\" type=\\\"\".$info->mimetype.\"\\\" />\\n\";\n                echo \"            <media:content url=\\\"\".$base_url.$info->filename.\"\\\" medium=\\\"\".$info->medium.\"\\\" duration=\\\"\".$info->duration.\"\\\" type=\\\"\".$info->mimetype.\"\\\" />\\n\";\n                echo \"            <pubDate>\".$info->date.\"</pubDate>\\n\";\n                echo \"            <itunes:duration>\".$info->duration.\"</itunes:duration>\\n\";\n                echo \"        </item>\\n\";\n            }\n        }\n    }\n}\n?>\n    </channel>\n</rss>'''\n\ndef RSS_INDEX_CODE(bin_path, config_name, version):\n    return r'''<?php\n/* ''' + RSS_FEED_VERSION + version + r''' */\nconst INFO=\"''' + RSS_FEED_INFO_EXTENSION + r'''\";\nconst SHOW_INFO=\"''' + RSS_FEED_SHOW_INDEX + r'''.\".INFO;\nconst SPODCAST=\"''' + bin_path + r'''\";\nconst SPODCAST_CONFIG=\"''' + config_name + r'''\";\nconst SHOW_IMAGE=\"''' + RSS_FEED_SHOW_IMAGE + r'''\";\nconst FEEDS_INFO=\"feeds.\".INFO;\nconst SETTINGS_INFO=\"settings.\".INFO;\nconst MAX_EPISODES=3;\nconst KEEP_EPISODES=5;\nconst UPDATEABLE=['max','keep'];\nconst CLI_COMMANDS=['refresh'];\nconst SUCCESS='success';\nconst ERROR='error';\nconst LOG_LEVEL='warning';\nconst NOT_FOUND=-1;\n\n$SPODCAST_CONFIG=dirname(__FILE__).\"/\".SPODCAST_CONFIG;\n$SPODCAST_COMMAND=SPODCAST.\" -c \".$SPODCAST_CONFIG;\n\n# CLI\nif (PHP_SAPI == \"cli\") {\n    global $SPODCAST_CONFIG;\n    if (count($argv) < 2) {\n        echo \"use: php \".__FILE__.\" <command> [options...]\".PHP_EOL;\n        echo \"     commands: \".implode(\"|\",CLI_COMMANDS).PHP_EOL;\n        die();\n    }\n\n    $settings=read(dirname(__FILE__).\"/\".SETTINGS_INFO);\n    $feeds=read(dirname(__FILE__).\"/\".FEEDS_INFO);\n\n    $command=$argv[1];\n    if($command == \"refresh\") {\n        list($retval, $result) = refresh_shows($feeds);\n        if ($retval > 0) {\n            echo \"An error occurred during refresh, return value was $retval\" . PHP_EOL;\n        }\n        echo implode(PHP_EOL, $result);\n    }\n    die();\n}\n\n# CGI/API\n$PROTOCOL = (empty($_SERVER['HTTPS'])) ? \"http://\" : \"https://\";\n$SPODCAST_URL = $PROTOCOL . $_SERVER['HTTP_HOST'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);\n$feeds=get_feeds(dirname(__FILE__));\n$settings=get_settings();\n$config=get_spodcast_config();\n$ERROR_MESSAGE=null;\n$ERROR_DETAILS=null;\n\nfunction get_feeds($dir) {\n    global $SPODCAST_URL;\n    foreach(glob($dir.\"/*/\".SHOW_INFO) as $show_info) {\n        $episodes=get_episodes(dirname($show_info));\n        $json=file_get_contents($show_info);\n        $info=json_decode($json);\n        $feeds[$info->link]['title']=$info->title;\n        $feeds[$info->link]['image']=$info->image;\n        $feeds[$info->link]['episodes']=count($episodes);\n        $feeds[$info->link]['last']=date(\"Y-m-d\",strtotime($episodes[0]['date']));\n        $feeds[$info->link]['directory']=dirname($show_info);\n        $feeds[$info->link]['max']=$info->max ?? MAX_EPISODES;\n        $feeds[$info->link]['keep']=$info->keep ?? KEEP_EPISODES;\n        $feeds[$info->link]['feed']=$SPODCAST_URL.basename(dirname($show_info));\n    }\n    uasort($feeds, fn ($a, $b) => strnatcmp($a['title'], $b['title']));\n    store($feeds, FEEDS_INFO);\n    return $feeds;\n}\n\nfunction get_episodes($dir) {\n    $episodes=[];\n    foreach(glob($dir.\"/*.\".INFO) as $episode_info) {\n        if(basename($episode_info) == SHOW_INFO) {\n            continue;\n        }\n        $json=file_get_contents($episode_info);\n        $info=json_decode($json);\n        $episodes[]=[\"filename\"=>$info->filename,\"date\"=>$info->date,\"title\"=>$info->title];\n    }\n    usort($episodes, fn ($a, $b) => strtotime($b[\"date\"]) - strtotime($a[\"date\"]));\n    return $episodes;\n}\n\nfunction get_settings() {\n    global $SPODCAST_URL;\n    $settings=read(SETTINGS_INFO);\n    $settings['spodcast_url']=$settings['spodcast_url'] ?? $SPODCAST_URL;\n    $settings['update_start']=$settings['update_start'] ?? 0;\n    $settings['update_rate']=$settings['update_rate'] ?? 1;\n    $settings['update_enabled']=$settings['update_enabled'] ?? false;\n    $settings['log_level']=$settings['log_level'] ?? LOG_LEVEL;\n    store($settings, SETTINGS_INFO);\n    return $settings;\n}\n\nfunction get_spodcast_config() {\n    global $SPODCAST_CONFIG;\n    $config=read($SPODCAST_CONFIG);\n    return $config;\n}\n\nfunction get(&$var, $default=null) {\n    return isset($var) ? $var : $default;\n}\n\nfunction read($file) {\n    if(is_readable($file)) {\n        $json=file_get_contents($file);\n        $info=json_decode($json, true);\n    } else {\n        $info=[];\n    }\n    return $info;\n}\n\nfunction store($info, $file) {\n    $f = fopen($file,'w');\n    $result = fwrite($f, json_encode($info));\n    fclose($f);\n    return ($result === false) ? ERROR : SUCCESS;\n}\n\nfunction cron_signature($crontab, $CRON_SIGNATURE) {\n    $index = 0;\n    foreach ($crontab as $line) {\n        if (strpos($line, $CRON_SIGNATURE)  !== false) {\n            return $index;\n        }\n        $index++;\n    }\n    return NOT_FOUND;\n}\n\nfunction debug($var) {\n    ob_start();\n    var_dump($var);\n    error_log(ob_get_clean());\n}\n\nfunction submit_crontab($crontab) {\n    $retval = null;\n    $output = null;\n    $tempfile=tempnam(sys_get_temp_dir(), 'spodcast');\n    file_put_contents($tempfile, implode(PHP_EOL,$crontab));\n    $command=\"crontab \".$tempfile;\n    exec($command, $output, $retval);\n    unlink($tempfile);\n\n    return [$retval, $output];\n}\n\nfunction get_range($start, $rate) {\n    for ($i=0; $i < $rate; $i++) {\n        $arr[]=(($start%(24/$rate))+($i*(24/$rate)))%24;\n    }\n    return implode(\",\", $arr);\n}\n\nfunction background_check_id($id) {\n    $runfile = md5($id).\".json\";\n    $log = md5($id).\".log\";\n    if (is_readable($runfile)) {\n        $info = read($runfile);\n        if (background_check($info['pid'])) {\n            return true;\n        }\n        unlink($runfile);\n        unlink($log);\n    }\n    return false;\n}\n\nfunction background_check($pid) {\n    try {\n        $result = shell_exec(sprintf(\"ps %d\", $pid));\n        if (count(preg_split(\"/\\n/\", $result)) > 2) {\n            return true;\n        }\n    } catch(Exception $e) {}\n    return false;\n}\n\n# [ status, output ] return functions\nfunction update_scheduler($enable, $start, $rate) {\n    $CRON_SIGNATURE=\"SPODCAST:\".dirname(__FILE__);\n    $crontab=null;\n    $retval=null;\n    exec(\"crontab -l\", $crontab, $retval);\n    if ($retval == 0) {\n        $index=cron_signature($crontab, $CRON_SIGNATURE);\n        if ($enable == true) {\n            if($index !== NOT_FOUND) {\n                array_splice($crontab, $index, 1);\n            }\n            $crontab[]=sprintf(\"%d %s * * * php %s refresh # %s\".PHP_EOL, rand(5,25), get_range($start, $rate),  __FILE__, $CRON_SIGNATURE);\n            return submit_crontab($crontab);\n        } else {\n            if ($index !== NOT_FOUND) {\n                array_splice($crontab, $index, 1);\n                $crontab[count($crontab)-1]=rtrim($crontab[count($crontab)-1]).PHP_EOL;\n                return submit_crontab($crontab);\n            }\n        }\n    } else {\n        return [$retval, \"failed to update scheduler\"];\n    }\n}\n\nfunction login($username, $password, $return_output=false) {\n    global $SPODCAST_COMMAND;\n    global $settings;\n    $output = null;\n    $retval = null;\n    $tempfile=tempnam(sys_get_temp_dir(), 'spodcast');\n    file_put_contents($tempfile, \"$username $password\");\n    $command=$SPODCAST_COMMAND . \" --log-level \" . $settings['log_level'] . \" -l \".$tempfile.\" 2>&1\";\n    exec($command, $output, $retval);\n    unlink($tempfile);\n\n    return [$retval, $output];\n}\n\nfunction background_run($command, $id) {\n    $retval=null;\n    $md5 = md5($id);\n    $runfile = $md5.\".json\";\n    $output = $md5.\".log\";\n    $cmd = sprintf(\"nohup %s > %s 2>&1 & echo $!\", $command, $output);\n    exec($cmd, $pid, $retval);\n    if ($retval == 0 && count($pid) > 0 && $pid[0] > 0) {\n        $info['command']=$command;\n        $info['log']=$output;\n        $info['pid']=(int) $pid[0];\n        store($info, $runfile);\n        return [$retval, $pid[0]];\n    } else {\n        return [$retval, 0];\n    }\n}\n\nfunction background_add_feed($url, $max) {\n    global $SPODCAST_COMMAND;\n    global $settings;\n    $output = null;\n    $retval = null;\n    $command=$SPODCAST_COMMAND  . \" --log-level \" . $settings['log_level'] . \" --max-episodes \".(int)$max.\" \".escapeshellarg($url);\n    list($retval, $pid) = background_run($command, $url);\n    if ($retval == 0 && (int) $pid > 0) {\n        return [$retval, $pid];\n    }\n    return [$retval, 0];\n}\n\n\nfunction add_feed($url, $max) {\n    global $SPODCAST_COMMAND;\n    global $settings;\n    $output = null;\n    $retval = null;\n    $command=$SPODCAST_COMMAND  . \" --log-level \" . $settings['log_level'] . \" --max-episodes \".(int)$max.\" \".escapeshellarg($url).\" 2>&1\";\n    exec($command, $output, $retval);\n    return [$retval, $output];\n}\n\nfunction update_feed($url, $max, $keep, $feeds) {\n    $output = null;\n    $retval = null;\n    if ($max > 0) {\n    list($retval,$output) = add_feed($url, $max);\n        if ($retval > 0) {\n            return [$retval, $output];\n        }\n    }\n    $directory=$feeds[$url]['directory'];\n    $episodes=get_episodes($directory);\n    if(count($episodes) > $keep) {\n        $to_delete=array_splice($episodes, $keep);\n        foreach ($to_delete as $episode) {\n            $command=\"rm -f \".escapeshellarg($directory.\"/\".$episode['filename']).\" 2>&1\";\n            exec($command, $output, $retval);\n            if ($retval > 0) {\n                return [$retval, $output];\n            }\n            $command=\"rm -f \".escapeshellarg($directory.\"/\".$episode['filename']).\".\".INFO.\" 2>&1\";\n            exec($command, $output, $retval);\n            if ($retval > 0) {\n                return [$retval, $output];\n            }\n        }\n    }\n    return [$retval, $output];\n}\n\nfunction delete_feed($url, $return_output=false) {\n    $output = null;\n    $retval = null;\n    $feeds=read(FEEDS_INFO);\n    $feed_dir=$feeds[$url]['directory'];\n    $command=\"rm -rf \".$feed_dir.\" 2>&1\";\n    exec($command, $output, $retval);\n    return [$retval, $output];\n}\n\nfunction update_show($url, $field, $value) {\n    if (array_search($field, UPDATEABLE) === false) {\n        return [1, \"$field is not an updateable field\"];\n    } else {\n        $feeds=read(FEEDS_INFO);\n        $show_dir=$feeds[$url]['directory'];\n        $show=read($show_dir.\"/\".SHOW_INFO);\n        $show[$field]=$value;\n        store($show, $show_dir.\"/\".SHOW_INFO);\n        return [0, \"$field set to $value\"];\n    }\n}\n\nfunction refresh_shows($feeds) {\n    $result = [];\n    $status = 0;\n    foreach ($feeds as $url => [\"title\"=>$title, \"directory\"=>$directory, \"max\"=>$max, \"keep\"=>$keep]) {\n        $output = null;\n        $retval = 0;\n        list($retval, $output) = update_feed($url, $max, $keep, $feeds, true);\n        if ($retval > 0) {\n            $status = $retval;\n        }\n        $result = array_merge($result, $output);\n    }\n    return [$status, $result];\n}\n\n# terminating functions\n\nfunction show_error($message, $details) {\n    header(\"Location: ./?action=error&message=\".urlencode($message).\"&details=\".urlencode(implode(PHP_EOL,$details)));\n    die();\n}\n\nfunction json_response($info) {\n    header('Content-Type: application/json; charset=utf-8');\n    echo json_encode($info, true);\n    exit();\n}\n\n# CGI commands\n\nswitch(get($_GET['action'])) {\n\ncase 'refresh':\n    $url = get($_POST['url']);\n    $max = (int) get($_POST['max']) ?? MAX_EPISODES;\n    $keep = (int) get($_POST['keep']) ?? KEEP_EPISODES;\n    $info['url']=$url;\n    $info['show']=$feeds[$url];\n    $info['id']=basename($url);\n    if ($max > $keep) {\n        $info['result'] = \"It does not make sense for the number of episodes to refresh to be larger than the number of episodes to keep.\";\n        $info['status'] = 'ERROR';\n    } else {\n        list($result,$output) = update_feed($url, $max, $keep, $feeds, false);\n        $info['status'] = ($result == 0) ? 'SUCCESS': 'ERROR';\n        if ($result != 0) {\n            $info['result'] = \"Refresh failed\";\n        }\n    }\n    json_response($info);\n\ncase 'new':\n    $url = get($_POST['url']);\n    list($result, $output) = background_add_feed($url, MAX_EPISODES, false);\n    $info['url']=$url;\n    $info['show']=$feeds[$url] ?? null;\n    $info['id']=basename($url);\n    $info['status']= ($result == 0) ? 'SUCCESS': 'ERROR';\n    json_response($info);\n\ncase 'update':\n    $url = get($_POST['url']);\n    $field = get($_POST['field']);\n    $value = get($_POST['value']);\n    if (in_array(strtolower($field), UPDATEABLE)) {\n        list($result, $output) = update_show($url, $field, $value);\n        if ($result == 0) {\n            $info['result'] = $output;\n            $info['status'] = 'SUCCESS';\n        } else {\n            $info['result'] = \"Update failed\";\n            $info['status'] = 'ERROR';\n        }\n    } else {\n        $info['result'] = \"$field can not be updated\";\n        $info['status'] = 'ERROR';\n    }\n\n    json_response($info);\n\ncase 'schedule':\n    $enable = (get($_POST['enable']) == \"true\" ? true : false);\n    $start = (int) get($_POST['start']);\n    $rate = (int) get($_POST['rate']);\n    $settings['update_enabled'] = $enable;\n    $settings['update_start'] = $start;\n    $settings['update_rate'] = $rate;\n    $result = store($settings, SETTINGS_INFO);\n    if ($result === ERROR) {\n        $info['status'] = 'ERROR';\n        $info['result'] = 'Could not store scheduler preferences, giving up';\n    } else {\n        list($result, $output) = update_scheduler($enable, $start, $rate);\n        if ($result == 0) {\n            $info['status'] = 'SUCCESS';\n            $info['result'] = ($enable === true) ? \"Scheduled updates enabled, $rate times per day starting at $start:00\" : 'Scheduled updates disabled';\n        } else {\n            $info['status'] = 'ERROR';\n            $info['result'] = implode(PHP_EOL, $result);\n        }\n    }\n    json_response($info);\n\ncase 'transcode':\n    $enable = (get($_POST['enable']) == \"true\" ? true : false);\n    $config['TRANSCODE']=$enable;\n    $result = store($config, $SPODCAST_CONFIG);\n    if ($result === SUCCESS) {\n        $info['status'] = 'SUCCESS';\n        $info['result'] = ($enable) ? 'Transcoding enabled' : 'Transcoding disabled';\n    } else {\n        $info['status'] = 'ERROR';\n        $info['result'] = 'Could not enable transcoding: can not write to config file';\n    }\n    json_response($info);\n\ncase 'logging':\n    $level = get($_POST['level']) ?? LOG_LEVEL;\n    $config['LOG_LEVEL']=$level;\n    if (in_array(strtolower($level), ['critical','error','warning','info','debug'])) {\n        $result = store($config, $SPODCAST_CONFIG);\n        if ($result === SUCCESS) {\n            $info['status'] = 'SUCCESS';\n            $info['result'] = 'Log level set to '. $level;\n        } else {\n            $info['status'] = 'ERROR';\n            $info['result'] = 'Could not change log level: can not write to Spodcast config file';\n        }\n    } else {\n        $info['status'] = 'ERROR';\n        $info['result'] = 'Invalid log level ' . $level;\n    }\n    json_response($info);\n\ncase 'status':\n    $url = get($_POST['url']);\n    $info['url'] = $url;\n    $info['show']=$feeds[$url] ?? null;\n    $info['id'] = basename($url);\n    $info['status'] = background_check_id($url) ? 'ACTIVE' : 'READY';\n    json_response($info);\n\ncase 'delete':\n    $url = get($_POST['url']);\n    $info['url'] = $url;\n    $info['id'] = basename($url);\n    list($result, $output) = delete_feed($url);\n    if ($result !== 0) {\n        $info['status'] = 'ERROR';\n        $info['result'] = \"Delete feed failed: \" . implode(PHP_EOL, $output);\n    } else {\n        $info['status'] = 'SUCCESS';\n        $info['result'] = \"Deleted <i>\" . $feeds[$url]['title'] . \"</i>\" ;\n    }\n    json_response($info);\n\ncase 'login':\n    $username = get($_POST['username']);\n    $password = get($_POST['password']);\n    list($result, $output) = login($username, $password);\n    if ($result === 0) {\n        $info['status'] = 'SUCCESS';\n        $info['result'] = 'Login succeeded';\n    } else {\n        $info['status'] = 'ERROR';\n        $info['result'] = 'Login failed for user '. $username;\n    }\n    json_response($info);\n\ncase 'update_shows':\n    list($result, $output) = refresh_shows($feeds);\n    $info['status'] = ($result == 0) ? 'SUCCESS' : 'ERROR';\n    $info['result'] = $output;\n    json_response($info);\n\ncase 'error':\n    $ERROR_MESSAGE = get($_POST['message']);\n    $ERROR_DETAILS = get($_POST['details']);\ndefault:\n    break;\n}\n\n$ACTIVE=[];\n\nforeach (array_keys($feeds) as $url) {\n    if (background_check_id($url)) {\n        $ACTIVE[$url]=true;\n    }\n}\n\n$TRANSCODE_ENABLED=(array_key_exists('TRANSCODE', $config)) ? (($config['TRANSCODE'] == \"True\") ? true : false) : false;\n$LOG_LEVEL=$config['LOG_LEVEL'];\n$UPDATE_ENABLED=$settings['update_enabled'];\n$UPDATE_START=$settings['update_start'];\n$UPDATE_RATE=$settings['update_rate'];\n?>\n<html>\n<head>\n    <title>Spodcast feed manager</title>\n    <style>\n        div, body, html { background-color: white; margin: 0.5em; }\n        div#new-feed { margin: 0em; display: flex; }\n        input#url { flex: 1; }\n        div#settings-header { text-align: right; }\n        div input, div button { height: 2em; font-size: 1.2em; margin: 0 1em 1em 0; }\n        div#loading { position: fixed; display: flex; width: 100%; height: 100%; top: 0; left: 0; opacity: 0.8; background-color: #fff; z-index: 99; justify-content: center; align-items: center; font-size: 200%; }\n        div#settings, div#error { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99; opacity: 0.95; margin: 0.5em auto; }\n        div.hidden { visibility: hidden; }\n        div.overlay { position: absolute; width: 100%; height: 100%; left: 0; right: 0; background: white; opacity: 0.5; z-index: 100; display: flex; justify-content: center; align-items: center; }\n        .show, .setgroup, .error { position: relative; display: flex; flex-wrap: wrap; margin: 0 0 2em 0; padding: 0; font-family: sans-serif; border: 1px solid #F0F0F0; background: #F0F0F0; border-radius: 6px; }\n        .show .placeholder { height: 4em; }\n        .setgroup { border: 1px solid black; margin: 1em; }\n        .error { border: 2px solid red; margin: 1em; }\n        .entry, .setitem, .errorline { display: flex; box-sizing: border-box; flex-grow: 1; width: 100%; padding: 0.4em 0.6em; overflow: hidden; align-items: center; text-align: left; background: #F0F0F0; }\n        .comment { font-size: 80%; font-style: italic;}\n        .entry > a { text-decoration: none; color: black; }\n        .entry > a:hover { color: red; }\n        .title { background: linear-gradient(90deg, #E0E0E0, #F0F0F0); border-radius: 6px; }\n        .link, .title { width: 40%; }\n        .title { text-transform: uppercase; }\n        .logo { width: 5%; min-width: 5em; flex-grow: 0; background: #F0F0F0; }\n        .logo img { width: 4em; height: 4em; }\n        .stats { width: 10%; min-width: 10em; }\n        .feed { font-size: 90%; }\n        .actions { display: flex; flex-direction: row; align-content: flex-end; flex: wrap; width: 100vw; background: #F0F0F0; }\n        .actions div:nth-of-type(1) { flex-grow: 1; }\n        .actions div { margin: 0 0 0 2em; background: inherit; }\n        .actions a { display: block; border: 1px solid #999; padding: 4px; color: black; text-decoration: none; border-radius: 5px; font-weight: bold; color: #222; background: white; }\n        .actions a:hover { color: white; background: #222; }\n        #delete { color: red; background: white; }\n        #delete:hover { color: white; background: red; }\n        #update-settings { background: inherit; }\n\n        .loader { display: inline-block; width: 4em; height: 4em; }\n        .loader:after { content: \" \"; display: block; width: 2em; height: 2em; margin: 8px; border-radius: 50%; border: 6px solid black; border-color: black transparent black transparent; animation: loader 1.2s linear infinite; }\n        @keyframes loader { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }\n\n        #toast { position: absolute; width: 33%; left: 33%; bottom: 2em; padding: 2em; border-radius: 6px; background: #F0F0F0; font-size: 1.2em; font-family: sans-serif; z-index: 200; text-align: center;}\n        #toast.success { border: 1px solid black; }\n        #toast.error { border: 6px solid red; }\n\n        legend { margin-left: 1.5em; font-size: 100%; border: 1px solid black; border-radius: 6px; background: white; padding: 0.1em 0.5em; }\n        .error legend { border: 2px solid red; }\n \n        @media all and (max-width: 500px) {\n            .show { display: block; }\n            .entry { width: 95% !important; }\n            .last { margin-bottom: 1em; }\n            .actions { flex-direction: column; align-items: flex-end; }\n            .actions div { margin: 0.2em 0; }\n        }\n    </style>\n</head>\n<body>\n    <div id=\"new-feed\">\n        <input id=\"url\" name=\"feed\" type=\"text\" placeholder=\"Spotify show/episode url\">\n        <button id='new'>Add</button>\n        <button id='opensettings' onclick=\"document.getElementById('settings').classList.remove('hidden'); return false;\">Settings</button>\n    </div>\n    <div id=\"feed-list\">\n    <?php foreach($feeds as $url => [\"title\"=>$title,\"image\"=>$image,\"episodes\"=>$episodes,\"last\"=>$last,\"max\"=>$max,\"keep\"=>$keep,\"feed\"=>$feed]): ?>\n        <div class=\"show\" id=\"<?php echo basename($url) ?>\">\n            <div class=\"overlay loader <?php echo (array_key_exists($url, $ACTIVE)) ? \"\" : \"hidden\" ?>\"></div>\n            <div class=\"entry title\"><?=$title?></div>\n            <div class=\"entry logo\"><img src=\"<?=$feed.\"/\".SHOW_IMAGE?>\"/></div>\n            <div class=\"entry link\"><a target=\"_blank\" href=\"<?=$url?>\"><?=htmlspecialchars($url)?></a></div>\n            <div class=\"entry stats\" id=\"stats-<?php echo basename($url) ?>\"><?=$last?>&nbsp;(<?=$episodes?>)</div>\n            <div class=\"entry feed\"><a target=\"_blank\" href=\"<?=$feed?>\"><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-rss\" viewBox=\"0 0 16 16\"><path d=\"M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z\"/><path d=\"M5.5 12a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0zm-3-8.5a1 1 0 0 1 1-1c5.523 0 10 4.477 10 10a1 1 0 1 1-2 0 8 8 0 0 0-8-8 1 1 0 0 1-1-1zm0 4a1 1 0 0 1 1-1 6 6 0 0 1 6 6 1 1 0 1 1-2 0 4 4 0 0 0-4-4 1 1 0 0 1-1-1z\"/></svg>&nbsp;&nbsp;<?=$feed?></a></div>\n            <div class=\"entry last actions\"><div></div><div>sync&nbsp;<select id=\"max-<?=basename($url)?>\" onchange=\"showUpdate(this,'<?=$url?>','max')\"><?php foreach([0,1,2,3,4,5] as $i) { printf(\"<option value='%d'>%d</option>\",$i, $i);}?></select></div><div>keep&nbsp;<select id=\"keep-<?=basename($url)?>\" onchange=\"showUpdate(this,'<?=$url?>','keep')\"><?php foreach([1,2,5,10,25,50,100,250,1000,2500] as $i) { printf(\"<option value='%d'>%d</option>\",$i, $i);}?></select>&nbsp;</div><div><a id=\"delete\" onclick=\"confirmDelete('<?=$title?>','<?=$url?>')\">delete</a></div><div><a id=\"refresh\" onclick=\"refresh('<?=$url?>')\">refresh</a></div></div>\n        </div>\n    <?php endforeach; ?>\n    </div>\n    <div id=\"settings\" class=\"hidden\">\n        <div id=\"settings-header\">\n            <button id='closesettings' onclick=\"document.getElementById('settings').classList.add('hidden'); return false;\">Close</button>\n        </div>\n        <fieldset id=\"credentials\" class=\"setgroup\">\n            <legend>Spotify login</legend>\n            <div class=\"setitem\"><input id=\"username\" name=\"username\" type=\"text\" placeholder=\"Spotify username\">&nbsp;\n            <input id=\"password\" name=\"password\" type=\"password\" placeholder=\"Spotify password\"></div>\n            <div class=\"setitem\"><button id=\"do-login\" name=\"do-login\">Login to Spotify</button></div>\n        </fieldset>\n        <fieldset id=\"scheduler\" class=\"setgroup\">\n            <legend>Feed update schedule</legend>\n            <div class=\"setitem comment\"><span>There are two ways to keep your shows up to date:<ol><li>using the native scheduler</li><li>through webcron: <b><?=$SPODCAST_URL.'?action=update_shows'?></b></li></ol>Enable updates through the native scheduler by clicking the button. If this does not work - e.g. because the web server user is not allowed to add cron jobs or because the web server runs in a Docker container which does not support such jobs - you can point any web client (curl or wget work fine here) at the webcron endpoint (see #2) to initiate an update run. Configure a user cron job for curl/wget to access the refresh endpoint at the desired times for a user experience similar to using the native scheduler.</span>  </div>\n            <div class=\"setitem\"><button id=\"update-enable\" name=\"update-enable\">Enable scheduled updates</button></div>\n            <div id=\"update-settings\">\n            <div class=\"setitem\">Update feed&nbsp;<select id=\"update-rate\"><option value=\"1\">1</option><option value=\"2\">2</option><option value=\"3\">3</option><option value=\"4\">4</option><option value=\"6\">6</option><option value=\"8\">8</option><option value=\"12\">12</option><option value=\"24\">24</option></select>&nbsp;times per day starting around&nbsp;<select id=\"update-start\"><?php for ($i=0; $i<=24; $i++) { printf(\"<option value='%d'>%02d:00</option>\",$i, $i);}?></select></div>\n            <div class=\"setitem comment\">Updates start 5 to 25 minutes after the hour</div>\n            <div class=\"setitem\"><button id=\"do-update\" name=\"do-update\">Update schedule</button>\n            <button id=\"update-disable\" name=\"update-disable\">Disable updates</button></div>\n            </fieldset>\n        <fieldset id=\"transcode\" class=\"setgroup\">\n            <legend>Transcode</legend>\n            <div class=\"setitem comment\"><span>Some devices - mainly Apple iOS - do not support open audio codecs like those used by Spotify. For such devices Spodcast can transcode ogg streams to mp3. This is an expensive operation which can take a substantial amount of time, especially on less powerful hardware. Only enable this option when there are no other options.</span></div>\n            <div class=\"setitem\"><button id=\"transcode-enable\" name=\"transcode-enable\">Enable transcoder</button><button id=\"transcode-disable\" name=\"transcode-disable\">Disable transcoder</button></div>\n        </fieldset>\n        <fieldset id=\"logging\" class=\"setgroup\">\n            <legend>Logging</legend>\n            <div class=\"setitem comment\"><span>The default log level shows which episodes have been downloaded. Change the log level to get more (or less) elaborate information on what Spodcast is up to. Log messages are reported in plain text format through scheduled updates and json-encoded through the webcron endpoint.</span></div>\n            <div class=\"setitem\"><select id=\"log-level\" onchange=\"logUpdate(this)\"><?php foreach([['CRITICAL','Only show critical errors'],['ERROR','Show error messages'],['WARNING','Show which episodes have been downloaded'],['INFO','Show downloaded as well as skipped episodes'],['DEBUG','Show detailed internal information for debugging purposes']] as $s) { printf(\"<option value='%s'>%s</option>\",$s[0], $s[1]);}?></select></div>\n        </fieldset>\n\n\n        </div>\n    </div>\n    <div id=\"error\" class=\"hidden\">\n    <fieldset id=\"errormessage\" class=\"error\">\n        <legend>Error: <?=$ERROR_MESSAGE?></legend>\n        <div class=\"errorline\"><pre><?=$ERROR_DETAILS?></pre></div>\n        <div class=\"errorline\"><button id=\"hide-error\" onclick=\"window.location.href='.'; return false;\">Close this message</button></div>\n    </fieldset>\n    </div>\n    <div class=\"hidden\" id=\"toast\"></div>\n    <script>\n    function xhr(type, url, data, options) {\n        options = options || {};\n        var request = new XMLHttpRequest();\n        request.open(type, url, true);\n        if(type === \"POST\") {\n            request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n        }\n        request.onreadystatechange = function () {\n            if (this.readyState === 4) {\n                if (this.status >= 200 && this.status < 400) {\n                    options.success && options.success(parse(this.responseText));\n                } else {\n                    options.error && options.error(this.status);\n                }\n            }\n        };\n        request.send(data);\n    }\n    function parse(text) {\n        try {\n            return JSON.parse(text);\n        } catch(e) {\n            return text;\n        }\n    }\n    function basename(path) {\n        return path.replace(/.*\\//, '');\n    }\n    function newfeed() {\n        xhr(\"POST\", '?action=new', 'url=' + encodeURI(document.getElementById('url').value), {success:addShow,error:removeShade});\n    }\n    function addShow(info) {\n        title=\"Adding show (\" + info.url + \"), please wait...\";\n        show=document.createElement('div'); show.setAttribute('class', 'show placeholder'); show.setAttribute('id', info.id);\n        shade=document.createElement('div'); shade.setAttribute('class', 'overlay');\n        logo=document.createElement('div'); logo.setAttribute('class', 'entry logo loader');\n        title=document.createElement('div'); title.setAttribute('class', 'entry title');\n        feedlist=document.getElementById('feed-list');\n        show.appendChild(shade); show.appendChild(title); show.appendChild(logo);\n        title.innterHTML = title;\n        first=feedlist.firstElementChild;\n        feedlist.insertBefore(show, first);\n        waitUpdate(info);\n    }\n    function login() {\n        xhr(\"POST\", '?action=login', 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value, {success:showToast, error:showToast});\n    }\n    function refresh(url) {\n        unhide(basename(url));\n        id = basename(url);\n        max=document.getElementById('max-' + id).value;\n        keep=document.getElementById('keep-' + id).value;\n        xhr(\"POST\", '?action=refresh', 'url=' + encodeURI(url) + '&max=' + max + '&keep=' + keep, {success:wait, error:removeShade});\n    }\n    function waitUpdate(info) {\n        if (info.status == 'READY' || info.status == 'ERROR') {\n            window.location.href = '';\n        }\n        if (info.show != null) {\n            document.getElementById(info.id).childNodes.item(1).innerHTML = \"Adding show: \" + info.show.title + \" (\" + info.show.episodes + \" episodes of 3 downloaded)...\";\n        } else {\n            document.getElementById(info.id).childNodes.item(1).innerHTML = \"Adding show: \" + info.url + \"...\";\n        }\n        setTimeout(function() {\n                xhr(\"POST\", '?action=status', 'url=' + encodeURI(info.url), {success:waitUpdate, error:removeShade});\n                }, 2000);\n    }\n    function wait(info) {\n        if (info.status == 'READY' || info.status == 'ERROR') {\n            document.getElementById('stats-' + info.id).innerHTML = info.show.last + '&nbsp;(' + info.show.episodes + ')';\n            hide(info.id);\n        } else { \n            if (info.show != null) {\n                document.getElementById('stats-' + info.id).innerHTML = info.show.last + '&nbsp;(' + info.show.episodes + ')';\n            }\n            setTimeout(function() {\n                    xhr(\"POST\", '?action=status', 'url=' + encodeURI(info.url), {success:wait, error:removeShade});\n                    }, 2000);\n        }\n    }\n    function removeShade(info) {\n        hide(info.id);\n    }\n    function hide(id) {\n        document.getElementById(id).firstElementChild.classList.add('hidden');\n    }\n    function unhide(id) {\n        document.getElementById(id).firstElementChild.classList.remove('hidden');\n    }\n    function schedule(enable) {\n        xhr(\"POST\", '?action=schedule', 'enable=' + enable + '&rate=' + document.getElementById('update-rate').value + '&start=' + document.getElementById('update-start').value, {success:showToast, error:showToast});\n    }\n    function transcode(enable) {\n        xhr(\"POST\", '?action=transcode', 'enable=' + enable, {success:showToast, error:showToast});\n    }\n    function logUpdate(e) {\n        xhr(\"POST\", '?action=logging', 'level=' + e.value, {success:showToast, error:showToast});\n    }\n    function selectElement(id, val) {\n        document.getElementById(id).value=val;\n    }\n    function showUpdate(e,url,field) {\n        id = basename(url);\n        max=document.getElementById('max-' + id);\n        keep=document.getElementById('keep-' + id);\n        maxval = parseInt(max.value);\n        keepval = parseInt(keep.value);\n        if(maxval > keepval) {\n            keeper = (maxval > 2) ? 5 : 2;\n            if (confirm(\"Sync count \" + maxval + \" is higher than Keep count \" + keepval + \"\\n\\n\" +\n                \"It does not make sense to refresh more expisodes than are kept in cache.\" +\n                \"Press OK to continue, Keep will be set to \" + keeper + \". Otherwise press Cancel\")) {\n                keep.value = keeper;\n            } else {\n                keep.value = keepval;\n                max.value = maxval;\n                return false;\n            }\n        }\n        xhr(\"POST\", '?action=update', 'url=' + encodeURI(url) + '&field=' + field + '&value=' + e.value, {success:showToast, error:showToast});\n    }\n    function confirmDelete(title, url) {\n        if (confirm('You are about to delete the following feed:\\n\\nTitle: ' + title + '\\nURL: ' + url + '\\n\\nAre you sure you want to delete this feed?')) {\n            xhr(\"POST\", '?action=delete', 'url=' + encodeURI(url), {success:deleteShow, error:showToast});\n        }\n        return false;\n    }\n    function deleteShow(info) {\n        document.getElementById(info.id).remove();\n        showToast(info);\n    }\n    function showToast(info) {\n        var toast=document.getElementById('toast');\n        if (info.status == 'ERROR') {\n            toast.classList.remove('success');\n            toast.classList.add('error');\n        } else {\n            toast.classList.remove('error');\n            toast.classList.add('success');\n        }\n        toast.innerHTML=info.result;\n        toast.classList.remove(\"hidden\");\n        window.setTimeout(function() {\n            toast = document.getElementById('toast');\n            toast.classList.add(\"hidden\");\n            toast.classList.replace('error', 'success');\n            toast.innerHTML=\"\";\n        }, 2000);\n    }\n\n    document.getElementById('new').onclick = function() {\n        newfeed();\n    };\n    document.getElementById('do-login').onclick = function() {\n        login();\n    };\n    document.getElementById('do-update').onclick = function() {\n        schedule(true);\n    };\n    document.getElementById('url').onkeydown = function(e) {\n        if(e.keyCode == 13) {\n            newfeed();\n        }\n    };\n\n    var schedule_enable = document.getElementById('update-enable');\n    var schedule_disable = document.getElementById('update-disable');\n    var schedule_entries = document.getElementById('update-settings');\n    var transcode_enable = document.getElementById('transcode-enable');\n    var transcode_disable = document.getElementById('transcode-disable');\n    schedule_entries.style.display = '<?php echo ($UPDATE_ENABLED ? 'initial' : 'none');?>';\n    schedule_enable.style.display = '<?php echo ($UPDATE_ENABLED ? 'none' : 'initial');?>';\n    transcode_enable.style.display = '<?php echo ($TRANSCODE_ENABLED ? 'none' : 'initial');?>';\n    transcode_disable.style.display = '<?php echo ($TRANSCODE_ENABLED ? 'initial' : 'none');?>';\n\n    schedule_enable.onclick = function() {\n        schedule_entries.style.display = 'initial';\n        schedule_enable.style.display = 'none';\n        schedule(true);\n    };\n    schedule_disable.onclick = function() {\n        schedule_entries.style.display = 'none';\n        schedule_enable.style.display = 'initial';\n        schedule(false);\n    };\n    transcode_enable.onclick = function() {\n        transcode_enable.style.display = 'none';\n        transcode_disable.style.display = 'initial';\n        transcode(true);\n    };\n    transcode_disable.onclick = function() {\n        transcode_enable.style.display = 'initial';\n        transcode_disable.style.display = 'none';\n        transcode(false);\n    };\n    selectElement('update-rate', '<?=$UPDATE_RATE?>');\n    selectElement('update-start', '<?=$UPDATE_START?>');\n    selectElement('log-level', '<?=$LOG_LEVEL?>');\n    <?php foreach($feeds as $url => [\"keep\"=>$keep,\"max\"=>$max]) {\n        printf(\"    selectElement('keep-%s', '%d');\\n\", basename($url), $keep);\n        printf(\"    selectElement('max-%s', '%d');\\n\", basename($url), $max);\n    }?>\n    <?php if ($ERROR_MESSAGE != null) {\n        echo \"    document.getElementById('error').classList.remove('hidden');\";\n    }?>\n    </script>\n</body>\n</html>'''\n\n"
  },
  {
    "path": "spodcast/podcast.py",
    "content": "import json\nimport logging\nimport os\nimport time\nfrom datetime import datetime\nfrom html import escape\nimport urllib.parse\n\nimport base62\nfrom base62 import CHARSET_INVERTED\nimport ffmpeg\n\nfrom librespot import util\nfrom librespot.metadata import ShowId, EpisodeId\nfrom librespot.core import ApiClient\n\nfrom spodcast.const import FILE_EXISTS, IMAGE_CDN\nfrom spodcast.feedgenerator import RSS_FEED_CODE, RSS_FEED_FILE_NAME, RSS_FEED_SHOW_INDEX, RSS_FEED_INFO_EXTENSION, RSS_FEED_SHOW_IMAGE, RSS_FEED_VERSION, get_index_version\nfrom spodcast.utils import clean_filename, uri_to_url\nfrom spodcast.spodcast import Spodcast\n\nlog = logging.getLogger(__name__)\n\n\ndef hex_to_spotify_id(hex_id):\n    return base62.encodebytes(util.hex_to_bytes(hex_id), CHARSET_INVERTED)\n\n\ndef get_show_info(show_id_hex):\n    log.info(\"Fetching show information...\")\n    show_id = ShowId.from_hex(show_id_hex)\n    uri = f'spotify:show:{hex_to_spotify_id(show_id_hex)}'\n    info = Spodcast.SESSION.api().get_metadata_4_show(show_id)\n    link = uri_to_url(uri)\n    description = info.description\n    image = IMAGE_CDN(util.bytes_to_hex(info.cover_image.image[1].file_id))\n\n    return link, description, image\n\n\ndef get_episode_info(episode_id_hex):\n    log.info(\"Fetching episode information...\")\n    episode_id = EpisodeId.from_hex(episode_id_hex)\n    uri = f'spotify:episode:{hex_to_spotify_id(episode_id_hex)}'\n    info = Spodcast.SESSION.api().get_metadata_4_episode(episode_id)\n    podcast_name = info.show.name\n    podcast_id = util.bytes_to_hex(info.show.gid)\n    episode_name = info.name\n    duration_ms = info.duration\n    description = info.description\n    external_url = info.external_url if info.external_url else None\n    pt = info.publish_time\n    release_date = f'{pt.year}-{pt.month}-{pt.day}T{pt.hour}:{pt.minute}:00Z'\n    date_temp = datetime.strptime(release_date, '%Y-%m-%dT%H:%M:%SZ')\n    release_date_clean = f'{date_temp.strftime(\"%Y\")}-{date_temp.strftime(\"%m\")}-{date_temp.strftime(\"%d\")}'\n\n    return podcast_name, podcast_id, duration_ms, episode_name, description, release_date, uri, external_url, release_date_clean\n\n\ndef get_episodes(show_id):\n    info = Spodcast.SESSION.api().get_metadata_4_show(show_id)\n    episodes = info.episode\n    episodes.sort(key = lambda x: datetime.strptime(f'{x.publish_time.year}-{x.publish_time.month}-{x.publish_time.day}T{x.publish_time.hour}:{x.publish_time.minute}:00Z', \"%Y-%m-%dT%H:%M:%SZ\"), reverse=True)\n\n    return [util.bytes_to_hex(episode.gid) for episode in episodes]\n\n\ndef download_file(url, filepath):\n    import functools\n    import pathlib\n    import shutil\n    import requests\n\n    mimetype = \"audio/mpeg\"\n\n    r = requests.get(url, stream=True, allow_redirects=True)\n    if r.status_code != 200:\n        r.raise_for_status()  # Will only raise for 4xx codes, so...\n        log.error(f\"Request to {url} returned status code {r.status_code}\")\n        return\n\n    file_size = int(r.headers.get('Content-Length', 0))\n\n    if (\n        os.path.isfile(filepath)\n        and abs(file_size - os.path.getsize(filepath)) < 1000\n        and Spodcast.CONFIG.get_skip_existing_files()\n    ):\n        return filepath, FILE_EXISTS, mimetype\n\n    log.info(\"Downloading file\")\n    r.raw.read = functools.partial(r.raw.read, decode_content=True)\n    with open(filepath, \"wb\") as file:\n        shutil.copyfileobj(r.raw, file)\n\n\n    return filepath, os.path.getsize(filepath), mimetype\n\n\ndef download_stream(stream, filepath):\n    size = stream.input_stream.size\n\n    mp3_filepath = os.path.splitext(filepath)[0] + \".mp3\"\n    mimetype = \"audio/ogg\"\n\n    if (\n        # \"FILE SIZE CHECK TEMPORARILY OUT OF ORDER\"\n        # Need to find a way to get decrypted content size\n        # from Spotify to enable file size checks, for now\n        # this only checks for the presence of a file with\n        # the same name. To recover from failed downloads\n        # simply remove incomplete files\n        #\n        #((os.path.isfile(filepath)\n        #and abs(size - os.path.getsize(filepath)) < 1000)\n        (os.path.isfile(filepath)\n        or (Spodcast.CONFIG.get_transcode()\n        and os.path.isfile(mp3_filepath)))\n        and Spodcast.CONFIG.get_skip_existing_files()\n    ):\n        return filepath, FILE_EXISTS, mimetype\n \n    log.info(\"Downloading stream\")\n    time_start = time.time()\n    downloaded = 0\n    with open(filepath, 'wb') as file:\n        data = b\"\"\n        while data := stream.input_stream.stream().read(Spodcast.CONFIG.get_chunk_size()):\n            if data == b\"\":\n                break\n            file.write(data)\n            downloaded += len(data)\n            if Spodcast.CONFIG.get_download_real_time():\n                delta_real = time.time() - time_start\n                delta_want = (downloaded / size) * (duration_ms/1000)\n                log.debug(f\"realtime enabled, waiting for {delta_real} seconds...\")\n                if delta_want > delta_real:\n                    time.sleep(delta_want - delta_real)\n\n    if Spodcast.CONFIG.get_transcode():\n        log.info(\"transcoding ogg->mp3\")\n        transcoder = ffmpeg.input(filepath)\n        transcoder = ffmpeg.output(transcoder, mp3_filepath)\n        ffmpeg.run(transcoder, quiet=True)\n        file.close()\n        os.unlink(filepath)\n        filepath = mp3_filepath\n        downloaded = os.path.getsize(filepath)\n        mimetype = \"audio/mpeg\"\n\n    return filepath, downloaded, mimetype\n\n\ndef download_episode(episode_id) -> None:\n    try:\n        podcast_name, podcast_id, duration_ms, episode_name, description, release_date, uri, download_url, release_date_clean = get_episode_info(episode_id)\n\n        if podcast_name is None:\n            log.warning('Skipping episode (podcast NOT FOUND)')\n        elif episode_name is None:\n            log.warning('Skipping episode (episode NOT FOUND)')\n        else:\n            filename = clean_filename(release_date_clean + ' - ' + podcast_name + ' - ' + episode_name)\n            show_directory = os.path.realpath(os.path.join(Spodcast.CONFIG.get_root_path(), clean_filename(podcast_name) + '/'))\n            os.makedirs(show_directory, exist_ok=True)\n\n            if download_url is None:\n                episode_stream_id = EpisodeId.from_hex(episode_id)\n                stream = Spodcast.get_content_stream(episode_stream_id, Spodcast.DOWNLOAD_QUALITY)\n                basename = f\"{filename}.ogg\"\n                filepath = os.path.join(show_directory, basename)\n                path, size, mimetype = download_stream(stream, filepath)\n                basename = os.path.basename(path) # may have changed due to transcoding\n            else:\n                basename=f\"{filename}.mp3\"\n                filepath = os.path.join(show_directory, basename)\n                path, size, mimetype = download_file(download_url, filepath)\n\n            if size == FILE_EXISTS:\n                log.info(f\"Skipped {podcast_name}: {episode_name}\")\n            else:\n                log.warning(f\"Downloaded {podcast_name}: {episode_name}\")\n\n                if Spodcast.CONFIG.get_rss_feed():\n                    episode_info = {\n                            \"mimetype\": mimetype,\n                            \"medium\": \"audio\",\n                            \"duration\": int(duration_ms/1000),\n                            \"date\": time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\", time.strptime(release_date, \"%Y-%m-%dT%H:%M:%SZ\")),\n                            \"title\": escape(episode_name), \"guid\": uri, \"description\": escape(description),\n                            \"filename\": urllib.parse.quote(basename),\n                            \"size\": int(size) }\n                    info_file = open(os.path.join(show_directory, f\"{basename}.{RSS_FEED_INFO_EXTENSION}\"), \"w\")\n                    info_file.write(json.dumps(episode_info))\n                    info_file.close()\n\n            if Spodcast.CONFIG.get_rss_feed():\n                show_index_file_name = os.path.join(show_directory, f\"{RSS_FEED_SHOW_INDEX}.{RSS_FEED_INFO_EXTENSION}\")\n                if not os.path.isfile(show_index_file_name) or int(get_index_version(show_index_file_name)) < Spodcast.CONFIG.get_version_int():\n                    podcast_link, podcast_description, podcast_image = get_show_info(podcast_id)\n                    show_info = {}\n                    if os.path.isfile(show_index_file_name):\n                        with open(show_index_file_name, encoding='utf-8') as file:\n                            show_info = json.load(file)\n                            file.close()\n                    show_info[\"version\"] = str(RSS_FEED_VERSION + Spodcast.CONFIG.get_version_str())\n                    show_info[\"title\"] = escape(podcast_name)\n                    show_info[\"link\"] = podcast_link\n                    show_info[\"description\"] = escape(podcast_description)\n                    show_info[\"image\"] = RSS_FEED_SHOW_IMAGE \n                    show_index_file = open(show_index_file_name, \"w\")\n                    show_index_file.write(json.dumps(show_info))\n                    show_index_file.close()\n\n                show_image_name = os.path.join(show_directory, f\"{RSS_FEED_SHOW_IMAGE}\")\n                if not os.path.isfile(show_image_name):\n                    download_file(podcast_image, show_image_name)\n\n                rss_file_name = os.path.join(show_directory, RSS_FEED_FILE_NAME)\n                if not os.path.isfile(rss_file_name) or int(get_index_version(rss_file_name)) < Spodcast.CONFIG.get_version_int():\n                    rss_file = open(rss_file_name, \"w\")\n                    rss_file.write(RSS_FEED_CODE(Spodcast.CONFIG.get_version_str()))\n                    rss_file.close()\n\n    except ApiClient.StatusCodeException as status:\n        log.warning(\"episode %s, StatusCodeException: %s\", episode_id, status)\n"
  },
  {
    "path": "spodcast/spodcast.py",
    "content": "from getpass import getpass\nimport glob\nimport hashlib\nfrom logging import Logger\nimport logging\nimport os\nimport os.path\nimport random\nimport requests\nimport sys\nimport time\n\nfrom librespot.audio.decoders import VorbisOnlyAudioQuality\nfrom librespot.core import Session\n\nfrom spodcast.config import Config\nfrom spodcast.const import CREDENTIALS_PREFIX, TYPE, USER_READ_EMAIL, OFFSET, LIMIT\nfrom spodcast.feedgenerator import RSS_FEED_FILE_NAME, RSS_INDEX_CODE, get_index_version\n\nclass Spodcast:    \n    SESSION: Session = None\n    DOWNLOAD_QUALITY = None\n    CONFIG: Config = Config()\n    LOG: Logger = None\n\n    def __init__(self, args):\n        Spodcast.CONFIG.load(args)\n        logging.basicConfig(level=Spodcast.CONFIG.get_log_level())\n        log = logging.getLogger(__name__)\n        Spodcast.LOG = log\n        log.debug(\"args: %s\", args)\n        if args.prepare_feed is True:\n            root_path=Spodcast.CONFIG.get_root_path()\n            os.makedirs(root_path, exist_ok=True)\n            if os.path.exists(root_path):\n                index_file_name = os.path.join(root_path, RSS_FEED_FILE_NAME)\n                if not os.path.isfile(index_file_name) or int(get_index_version(index_file_name)) < Spodcast.CONFIG.get_version_int():\n                    rss_file = open(index_file_name, \"w\")\n                    rss_file.write(RSS_INDEX_CODE(Spodcast.CONFIG.get_bin_path(), os.path.basename(Spodcast.CONFIG.get_config_path()), Spodcast.CONFIG.get_version_str()))\n                    rss_file.close()\n            else:\n                sys.exit(f\"Can not create root path {root_path}\")\n\n        if args.login:\n            filename = args.login\n            if os.path.exists(filename):\n                with open(filename, 'r', encoding='utf-8') as file:\n                    for line in file.readlines():\n                        Spodcast.account(line.strip())\n                sys.exit(0)\n            else:\n                sys.exit(f\"Can not read username/password file {filename}\")\n\n        Spodcast.login()\n\n    @classmethod\n    def account(cls, line):\n        cred_directory = Config.get_config_dir()\n        if os.path.isdir(cred_directory):\n            (username,password) = line.split()\n            cred_filename = CREDENTIALS_PREFIX + \"-\" + hashlib.md5(username.encode('utf-8'),usedforsecurity=False).hexdigest() + \".json\"\n            cred_location = os.path.join(cred_directory, cred_filename)\n            conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).build()\n            session = Session.Builder(conf).user_pass(username, password).create()\n            if not session.is_valid():\n                Spodcast.LOG.error(\"Invalid username/password for username \" + username);\n             \n    @classmethod\n    def login(cls):\n        cred_directory = Config.get_config_dir()\n        credfiles = glob.glob(os.path.join(cred_directory, CREDENTIALS_PREFIX) + \"-*.json\")\n        if credfiles:\n            random.shuffle(credfiles)\n            for credfile in credfiles:\n                try:\n                    cred_location = os.path.join(cred_directory, credfile)\n                    conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).set_store_credentials(False).build()\n                    session = Session.Builder(conf).stored_file().create()\n                    if session.is_valid():\n                        cls.SESSION = session\n                        return\n                    else:\n                        Spodcast.LOG.warning(f\"Invalid credentials in {cred_location}\")\n                except RuntimeError:\n                    Spodcast.LOG.error(\"RuntimeError\")\n                    pass\n                \n        cred_location = Config.get_credentials_location()\n\n        if os.path.isfile(cred_location):\n            try:\n                conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).set_store_credentials(False).build()\n                cls.SESSION = Session.Builder(conf).stored_file().create()\n                return\n            except RuntimeError:\n                pass\n        while True:\n            user_name = ''\n            while len(user_name) == 0:\n                user_name = input('Username: ')\n            password = getpass()\n            try:\n                conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).build()\n                cls.SESSION = Session.Builder(conf).user_pass(user_name, password).create()\n                return\n            except RuntimeError:\n                pass\n\n    @classmethod\n    def get_content_stream(cls, content_id, quality):\n        return cls.SESSION.content_feeder().load(content_id, VorbisOnlyAudioQuality(quality), False, None)\n\n    @classmethod\n    def __get_auth_token(cls):\n        return cls.SESSION.tokens().get_token(USER_READ_EMAIL).access_token\n\n    @classmethod\n    def get_auth_header(cls):\n        return {\n            'Authorization': f'Bearer {cls.__get_auth_token()}',\n            'Accept-Language': f'{cls.CONFIG.get_language()}'\n        }\n\n    @classmethod\n    def get_auth_header_and_params(cls, limit, offset):\n        return {\n            'Authorization': f'Bearer {cls.__get_auth_token()}',\n            'Accept-Language': f'{cls.CONFIG.get_language()}'\n        }, {LIMIT: limit, OFFSET: offset}\n\n    @classmethod\n    def invoke_url_with_params(cls, url, limit, offset, **kwargs):\n        headers, params = cls.get_auth_header_and_params(limit=limit, offset=offset)\n        params.update(kwargs)\n        return requests.get(url, headers=headers, params=params).json()\n\n    @classmethod\n    def invoke_url(cls, url, tryCount=0):\n        headers = cls.get_auth_header()\n        Spodcast.LOG.debug(headers)\n        response = requests.get(url, headers=headers)\n        responsetext = response.text\n        responsejson = response.json()\n\n        if 'error' in responsejson:\n            if tryCount < (cls.CONFIG.get_retry() - 1):\n                Spodcast.LOG.warning(f\"Spotify API Error (try {tryCount + 1}) ({responsejson['error']['status']}): {responsejson['error']['message']}\")\n                time.sleep(5)\n                return cls.invoke_url(url, tryCount + 1)\n\n            Spodcast.LOG.error(f\"Spotify API Error ({responsejson['error']['status']}): {responsejson['error']['message']}\")\n\n        return responsetext, responsejson\n"
  },
  {
    "path": "spodcast/utils.py",
    "content": "import re\nimport string\nimport unicodedata\nfrom enum import Enum\nfrom typing import List, Tuple\n\nfrom spodcast.spodcast import Spodcast\nfrom spodcast.const import OPEN_SPOTIFY_URL\n\nvalid_filename_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n\ndef regex_input_for_urls(search_input) -> Tuple[str, str, str, str, str, str]:\n    episode_uri_search = re.search(\n        r'^spotify:episode:(?P<EpisodeID>[0-9a-zA-Z]{22})$', search_input)\n    episode_url_search = re.search(\n        r'^(https?://)?open\\.spotify\\.com/episode/(?P<EpisodeID>[0-9a-zA-Z]{22})(\\?si=.+?)?$',\n        search_input,\n    )\n\n    show_uri_search = re.search(\n        r'^spotify:show:(?P<ShowID>[0-9a-zA-Z]{22})$', search_input)\n    show_url_search = re.search(\n        r'^(https?://)?open\\.spotify\\.com/show/(?P<ShowID>[0-9a-zA-Z]{22})(\\?si=.+?)?$',\n        search_input,\n    )\n    if episode_uri_search is not None or episode_url_search is not None:\n        episode_id_str = (episode_uri_search\n                          if episode_uri_search is not None else\n                          episode_url_search).group('EpisodeID')\n    else:\n        episode_id_str = None\n\n    if show_uri_search is not None or show_url_search is not None:\n        show_id_str = (show_uri_search\n                       if show_uri_search is not None else\n                       show_url_search).group('ShowID')\n    else:\n        show_id_str = None\n\n    return episode_id_str, show_id_str\n\n\ndef clean_filename(filename, whitelist=valid_filename_chars, replace=' '):\n    for r in replace:\n        filename = filename.replace(r,'_')\n\n    cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()\n    cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist)\n    return cleaned_filename\n\ndef uri_to_url(spotify_id):\n    (spotify,sp_type,sp_id) = spotify_id.split(':')\n    return f'https://{OPEN_SPOTIFY_URL}/{sp_type}/{sp_id}'\n"
  }
]