Full Code of Yetangitu/Spodcast for AI

master be7bc5cbb872 cached
23 files
130.2 KB
32.5k tokens
47 symbols
1 requests
Download .txt
Repository: Yetangitu/Spodcast
Branch: master
Commit: be7bc5cbb872
Files: 23
Total size: 130.2 KB

Directory structure:
gitextract_7zbxfgob/

├── .gitignore
├── LICENSE
├── README.md
├── docker/
│   ├── Dockerfile
│   ├── Dockerfile.cron
│   ├── Dockerfile.web
│   ├── cron.sh
│   ├── docker-compose.yml
│   ├── nginx/
│   │   ├── nginx.conf
│   │   └── sites-enabled/
│   │       └── spodcast
│   └── run.sh
├── install.sh
├── setup.cfg
├── setup.py
└── spodcast/
    ├── __init__.py
    ├── __main__.py
    ├── app.py
    ├── config.py
    ├── const.py
    ├── feedgenerator.py
    ├── podcast.py
    ├── spodcast.py
    └── utils.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
bin/
build/
develop-eggs/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# _Spodcast_

_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.
_Spodcast_ only supports the _Spotify_ podcast service, it does not interface with the music streaming service.

## How does it work

_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:

### _Spodcast_ regularly queries _Spotify_ for new episodes...
```
                  --------------
                 |task scheduler|
                  --------------
                        |             ___________
  -------   APIv1   ----V---         /           \
 |Spotify|- - - - >|Spodcast|------>| File system |
  -------           --------         \___________/
```
### You want to listen to an episode using your old, unsupported but still functional phone...
```
                                           _____         ............
   ___________          ----------        |     | . o O |bla bla bla.|
  /           \        |Web server|  RSS  | YOUR|        ````````````
 | File system |------>|  + PHP   |------>| OLD |
  \___________/         ----------        |PHONE|
                                          |_____|

```
Thus, 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.

## Installation

_Spodcast_ is available as an installable package on PyPi, just run:
```
$ pip install spodcast
```
...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.

_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:
```shell
$ git clone https://github.com/Yetangitu/spodcast.git
$ cd spodcast
$ pip install .
```

Once 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.

## Usage with Docker: 

Pre-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.

### A Note on Environment Variables:

The 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.

Here is the list of permitted environment variables with a brief description:

| Variable | Default Value | Description | 
|----------|---------------|-------------|
| SPOTIFY_PASSWORD | None | Spotify password |
| SPOTIFY_USERNAME | None | Spotify username |
| SPOTIFY_PODCAST_URLS | None | URLs of podcasts to download from spotify (separated by space) |
| 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 | 
| SPODCAST_ROOT | `/data` | Where all assets will go in the container filesystem | 
| SPODCAST_HTML | `${SPODCAST_ROOT}/html` | Where HTML content will be places in container filesystem |
| SPODCAST_CONFIG_JSON | `${SPODCAST_ROOT}/spodcast.json` | Location of the spodcast config file | 
| SPOTIFY_CREDS_JSON | `${SPODCAST_ROOT}/creds.json` | Location of the file containing Spotify credentials that Spodcast will use to continue logging in |
| SPOTIFY_RC_PATH | `${SPODCAST_ROOT}/spotify.rc` | Location of file containing creds to initially login | 
| MAX_EPISODES | `10` | Max amount of episodes to download per podcast | 
| LOG_LEVEL | `info` | Log level of Spodcast |
| CHUNK_SIZE | `50000` | Download chunk size |
| RSS_FEED | `yes` | Create an RSS feed for a web server | 
| TRANSCODE | `no` | Transcode to MP3 format (i.e. so iOS devices can play the audio files) | 
| LANGUAGE | `en` | Language of the content | 
| SKIP_EXISTING | `yes` | Do not re-download episodes that already exist on filesystem |

`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.


### Usage with Docker-Compose and environment variables:

The 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:

```
services:
  spodcast-cron:
    image: heywoodlh/spodcast-cron:latest
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    environment:
      - CRON_SCHEDULE=0 * * * *
      - SPOTIFY_PODCAST_URLS=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk
      - SPOTIFY_PASSWORD=myawesomepassword
      - SPOTIFY_USERNAME=email@awesome.com
      - MAX_EPISODES=1
      
  spodcast-php:
    image: php:7-fpm
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    user: "101:101"
    networks:
    - spodcast

  spodcast-web:
    image: heywoodlh/spodcast-web:latest
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    networks:
    - spodcast
    ports:
      - 8080:80

networks:
  spodcast:
volumes:
  spodcast_data:
```

*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. 

### Using the Docker CLI and supplying arguments:

Prepare `spodcast` directory (this example assumes you will store Spodcast's data in `/tmp/spodcast`):

```
mkdir -p /tmp/spodcast

echo 'spotify_username spotify_password' > /tmp/spodcast/spotify.rc
```

Login to Spotify and configure `spodcast` initially:

```
docker 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
```

Now run `spodcast` (this example will download The Joe Rogan Experience to `/tmp/spodcast/html` on the Docker host):

```
docker run -it -v /tmp/spodcast:/data heywoodlh/spodcast -c /data/spodcast.json --log-level info --max-episodes 10 'https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk'
```

#### Build the image locally:

If you would prefer to build the image locally: 

```
git clone https://github.com/Yetangitu/Spodcast && cd Spodcast

docker build -t spodcast -f docker/Dockerfile .
```

Docker 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`.

## Usage
To 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.

Here's `spodcast` displaying its help message:
```
$ spodcast -h
usage: spodcast [-h] [-c CONFIG_LOCATION] [-p] [-v] [-l LOGIN] [--root-path ROOT_PATH]
                [--skip-existing SKIP_EXISTING] [--retry RETRY] [--max-episodes MAX_EPISODES]
                [--chunk-size CHUNK_SIZE] [--download-real-time DOWNLOAD_REAL_TIME]
                [--language LANGUAGE] [--credentials-location CREDENTIALS_LOCATION]
                [--rss-feed RSS_FEED] [--transcode TRANSCODE] [--log-level LOG_LEVEL]
                [urls ...]

A caching Spotify podcast to RSS proxy.

positional arguments:
  urls                  Download podcast episode(s) from a url. Can take multiple urls.

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG_LOCATION, --config-location CONFIG_LOCATION
                        Specify the spodcast.json location
  -p, --prepare-feed    Installs RSS feed server code in ROOT_PATH.
  -v, --version         show program's version number and exit
  -l LOGIN, --login LOGIN
                        Reads username and password from file passed as argument and stores
                        credentials for later use.
  --root-path ROOT_PATH
                        set root path for podcast cache
  --skip-existing SKIP_EXISTING
                        [yes|no] skip files with the same name and size. Defaults to "yes".
  --retry RETRY         retry count for Spotify API access
  --max-episodes MAX_EPISODES
                        number of episodes to download
  --chunk-size CHUNK_SIZE
                        download chunk size
  --download-real-time DOWNLOAD_REAL_TIME
                        simulate streaming client
  --language LANGUAGE   preferred content language
  --credentials-location CREDENTIALS_LOCATION
                        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).
  --rss-feed RSS_FEED   [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".
  --transcode TRANSCODE
                        [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".
  --log-level LOG_LEVEL
                        log level (debug/info/warning/error/critical)
```

### Using _Spodcast_ to proxy _Spotify_ podcasts to RSS
The 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.
```
spodcast -c /mnt/audio/podcast/spodcast.json --root-path /mnt/audio/spodcast -p -l /home/exampleuser/spotify.rc
```
Configure 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.

Once 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.

While 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.

Point 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`.

Here's what the Spodcast feed manager looks like:

![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")

...and on smaller screens it looks like this:

![Spodcast feed manager on a small screen](/resources/screenshots/spodcast_is_responsive.png?raw=true "Spodcast feed manager, vertical layout on smaller screens")

The settings screen is simple and concise:

![Spodcast feed manager settings](/resources/screenshots/spodcast_settings.png?raw=true "Spodcast feed manager: Settings")

Each 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.

![Show controls](/resources/screenshots/sync_keep_delete_refresh.png?raw=true "Configure _sync_ and _keep_ settings for each show")

### Using the _Spodcast_ CLI command to download a single episode
_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:
```
spodcast -c ~/.config/spodcast/spodcast.json --credentials-location ~/.config/spodcast/credentials.json --rss-feed no https://open.spotify.com/episode/2rYwwE7hcpgsDo9vRVHxAI?si=24fb00294b7f40db
```
Like 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.
In "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:
```
spodcast -c ~/.config/spodcast/spodcast.json --rss-feed no --max-episodes 3 https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk`
```
## Web server configuration
_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:
```
server {
        listen 80;
        listen [::]:80;
        server_name spodcast.example.org;

        root /mnt/audio/spodcast;

        index .index.php;

        fastcgi_read_timeout 300;
        fastcgi_send_timeout 300;	

        # these files should not be accessible
        location ~\.(json|info)$ {
                deny all;
                return 404;
        }

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        }
}
```
Examples 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.


================================================
FILE: docker/Dockerfile
================================================
FROM python:3-alpine

COPY . /app
WORKDIR /app

RUN apk --no-cache add gcc libc-dev ffmpeg bash \
	&& pip3 install .

VOLUME ["/data"]
WORKDIR /data

COPY docker/run.sh /run.sh

ENTRYPOINT ["/run.sh"]

LABEL description="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."
LABEL version="0.5.2"
LABEL org.opencontainers.image.authors="Yetangitu and others"



================================================
FILE: docker/Dockerfile.cron
================================================
FROM heywoodlh/spodcast:latest

COPY docker/cron.sh /cron.sh

LABEL description="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."
LABEL version="0.5.2"
LABEL org.opencontainers.image.authors="Yetangitu and others"

ENTRYPOINT /cron.sh


================================================
FILE: docker/Dockerfile.web
================================================
FROM nginx:stable

RUN apt-get update && apt-get install -y nginx-full \
	&& rm -rf /var/lib/apt/lists/* \
	&& rm /etc/nginx/conf.d/default.conf \
	&& rm /etc/nginx/sites-enabled/default

COPY docker/nginx/nginx.conf /etc/nginx/nginx.conf
COPY docker/nginx/sites-enabled /etc/nginx/sites-enabled


================================================
FILE: docker/cron.sh
================================================
#!/usr/bin/env bash

## Set default cron schedule
[[ -n ${CRON_SCHEDULE} ]] || export CRON_SCHEDULE="0 0 * * Sun"

## Variables for /run.sh
[[ -n ${SPODCAST_ROOT} ]] || export SPODCAST_ROOT='/data'
[[ -n ${SPODCAST_HTML} ]] || export SPODCAST_HTML="${SPODCAST_ROOT}/html"
[[ -n ${SPODCAST_CONFIG_JSON} ]] || export SPODCAST_CONFIG_JSON="${SPODCAST_ROOT}/spodcast.json"
[[ -n ${SPOTIFY_CREDS_JSON} ]] || export SPOTIFY_CREDS_JSON="${SPODCAST_ROOT}/creds.json"
[[ -n ${SPOTIFY_RC_PATH} ]] || export SPOTIFY_RC_PATH="${SPODCAST_ROOT}/spotify.rc"
[[ -n ${SPOTIFY_PASSWORD} ]] || export creds_supplied='false'
[[ -n ${SPOTIFY_USERNAME} ]] || export creds_supplied='false'
[[ -n ${MAX_EPISODES} ]] || export MAX_EPISODES='10'
[[ -n ${LOG_LEVEL} ]] || export LOG_LEVEL='info'
[[ -n ${CHUNK_SIZE} ]] || export CHUNK_SIZE='50000'
[[ -n ${RSS_FEED} ]] || export RSS_FEED='yes'
[[ -n ${TRANSCODE} ]] || export TRANSCODE='no'
[[ -n ${LANGUAGE} ]] || export LANGUAGE='en'
[[ -n ${SKIP_EXISTING} ]] || export SKIP_EXISTING='yes'

[[ ${creds_supplied} == 'false' ]] \
    && echo 'Please set the SPOTIFY_USERNAME and SPOTIFY_PASSWORD variables. Exiting.' \
    && exit 1

## Setup cron
echo SHELL=/bin/bash > /tmp/cron
echo PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin >> /tmp/cron
echo "${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

echo "* * * * * chown -R 101:101 ${SPODCAST_HTML}" >> /tmp/cron

crontab /tmp/cron
rm /tmp/cron

crond -l 0 -d 0 -f


================================================
FILE: docker/docker-compose.yml
================================================
services:
  spodcast-cron:
    image: heywoodlh/spodcast-cron:latest
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    environment:
      - CRON_SCHEDULE=0 * * * *
      - SPOTIFY_PODCAST_URLS=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk
      - SPOTIFY_PASSWORD=myawesomepassword
      - SPOTIFY_USERNAME=email@awesome.com
      - MAX_EPISODES=1
      
  spodcast-php:
    image: php:7-fpm
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    user: "101:101"
    networks:
    - spodcast

  spodcast-web:
    image: heywoodlh/spodcast-web:latest
    volumes:
      - spodcast_data:/data
    restart: unless-stopped
    networks:
    - spodcast
    ports:
      - 8080:80

networks:
  spodcast:
volumes:
  spodcast_data:


================================================
FILE: docker/nginx/nginx.conf
================================================
user  nginx;
worker_processes  auto;

pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


================================================
FILE: docker/nginx/sites-enabled/spodcast
================================================
server {
        listen 80;
        listen [::]:80;

        root /data/html;
	
        index .index.php;

        # these files should not be accessible
        location ~\.(json|info)$ {
                deny all;
                return 404;
        }

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass spodcast-php:9000;
        }
}


================================================
FILE: docker/run.sh
================================================
#!/usr/bin/env bash

## If the following variables are not defined, set defaults
[[ -n ${SPODCAST_ROOT} ]] || export SPODCAST_ROOT='/data'
[[ -n ${SPODCAST_HTML} ]] || export SPODCAST_HTML="${SPODCAST_ROOT}/html"
[[ -n ${SPODCAST_CONFIG_JSON} ]] || export SPODCAST_CONFIG_JSON="${SPODCAST_ROOT}/spodcast.json"
[[ -n ${SPOTIFY_CREDS_JSON} ]] || export SPOTIFY_CREDS_JSON="${SPODCAST_ROOT}/creds.json"
[[ -n ${SPOTIFY_RC_PATH} ]] || export SPOTIFY_RC_PATH="${SPODCAST_ROOT}/spotify.rc"
[[ -n ${SPOTIFY_PASSWORD} ]] || export creds_supplied='false'
[[ -n ${SPOTIFY_USERNAME} ]] || export creds_supplied='false'
[[ -n ${MAX_EPISODES} ]] || export MAX_EPISODES='10'
[[ -n ${LOG_LEVEL} ]] || export LOG_LEVEL='info'
[[ -n ${CHUNK_SIZE} ]] || export CHUNK_SIZE='50000'
[[ -n ${RSS_FEED} ]] || export RSS_FEED='yes'
[[ -n ${TRANSCODE} ]] || export TRANSCODE='no'
[[ -n ${LANGUAGE} ]] || export LANGUAGE='en'
[[ -n ${SKIP_EXISTING} ]] || export SKIP_EXISTING='yes'

## If Spotify credentials were supplied, create ${SPODCAST_ROOT}/spotify.rc
[[ ${creds_supplied} == 'false' ]] || echo "${SPOTIFY_USERNAME} ${SPOTIFY_PASSWORD}" > ${SPODCAST_ROOT}/spotify.rc

## If no arguments were supplied, then use environment variables
if [[ -z "$@" ]]
then
	## If SPOTIFY_PODCAST_URLS is defined, then run Spodcast
	if [[ -n ${SPOTIFY_PODCAST_URLS} ]]
	then
		## If ${SPOTIFY_RC_PATH} file exists
		if [[ -e ${SPOTIFY_RC_PATH} ]]
		then
		# Login first and then run spodcast
			/usr/local/bin/spodcast \
				-c "${SPODCAST_CONFIG_JSON}" \
				--root-path "${SPODCAST_HTML}" \
				--log-level "${LOG_LEVEL}" \
				--credentials-location "${SPOTIFY_CREDS_JSON}" \
				-p -l ${SPOTIFY_RC_PATH} \
				&& /usr/local/bin/spodcast \
					-c ${SPODCAST_CONFIG_JSON} \
					--log-level ${LOG_LEVEL} \
					--max-episodes ${MAX_EPISODES} \
					"${SPOTIFY_PODCAST_URLS}"
		else
			echo "SPOTIFY_PODCAST_URLS is defined, but no credentials were detected. Please set the SPOTIFY_USERNAME and SPOTIFY_PASSWORD variables."
			exit 1
		fi
	## If SPOTIFY_PODCAST_URLS is not defined and no arguments were supplied, just show the help message
	else
		/usr/local/bin/spodcast --help	
	fi
fi

## If arguments were supplied, do not use environment variables
[[ -n $@ ]] && /usr/local/bin/spodcast "$@"


================================================
FILE: install.sh
================================================
pip3 install -e .


================================================
FILE: setup.cfg
================================================
[metadata]
name = spodcast
version = 0.5.2
description = A caching Spotify podcast to RSS proxy.
long_description = file:README.md
long_description_content_type = text/markdown
url = https://github.com/Yetangitu/spodcast.git
project_urls =
    Bug Tracker = https://github.com/Yetangitu/spodcast/issues
author = yetangitu
author_email = github-f@unternet.org
licence = GPLv3
classifiers =
    License :: OSI Approved :: GNU General Public License v3 (GPLv3)
    Programming Language :: Python :: 3.9
    Programming Language :: PHP
platforms = any

[options]
packages =
    spodcast
install_requires =
    librespot >= 0.0.9
    pybase62
    ffmpeg-python
    setuptools
include_package_data =
    True

[options.entry_points]
console_scripts:
    spodcast = spodcast.__main__:main


================================================
FILE: setup.py
================================================
from setuptools import setup

if __name__ == "__main__":
    setup()


================================================
FILE: spodcast/__init__.py
================================================


================================================
FILE: spodcast/__main__.py
================================================
import argparse
import pkg_resources

from spodcast.app import client
from spodcast.config import CONFIG_VALUES

def main():
    parser = argparse.ArgumentParser(prog='spodcast', description='A caching Spotify podcast to RSS proxy.')
    parser.add_argument('-c', '--config-location',
                        type=str,
                        help='Specify the spodcast.json location')

    parser.add_argument('-p', '--prepare-feed',
                       action='store_true',
                       help='Installs RSS feed server code in ROOT_PATH.')

    parser.add_argument('-v', '--version',
                       action='version',
                       version = '%(prog)s ' + pkg_resources.require("Spodcast")[0].version)

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('urls',
                       type=str,
                       # action='extend',
                       default='',
                       nargs='*',
                       help='Download podcast episode(s) from a url. Can take multiple urls.')

    group.add_argument('-l', '--login',
                       type=str,
                       help='Reads username and password from file passed as argument and stores credentials for later use.')

    for configkey in CONFIG_VALUES:
        parser.add_argument(CONFIG_VALUES[configkey]['arg'],
                            type=str,
                            default=None,
                            help=CONFIG_VALUES[configkey]['help'])

    parser.set_defaults(func=client)

    args = parser.parse_args()
    args.func(args)


if __name__ == '__main__':
    main()


================================================
FILE: spodcast/app.py
================================================
import logging

from itertools import islice
from librespot.audio.decoders import AudioQuality
from librespot.metadata import ShowId, EpisodeId

from spodcast.podcast import download_episode, get_episodes
from spodcast.utils import regex_input_for_urls
from spodcast.spodcast import Spodcast

log = logging.getLogger(__name__)

def client(args) -> None:
    Spodcast(args)
    Spodcast.DOWNLOAD_QUALITY = AudioQuality.NORMAL

    if args.urls:
        for spotify_url in args.urls:
            episode_id_str, show_id_str = regex_input_for_urls(spotify_url)
            log.debug(f"episode_id_str {episode_id_str}. show_id_str {show_id_str}")
            if episode_id_str is not None:
                episode_id = EpisodeId.from_base62(episode_id_str).hex_id()
                log.debug("episode_id: %s", episode_id)
                download_episode(episode_id)
            elif show_id_str is not None:
                show_id = ShowId.from_base62(show_id_str)
                log.debug("show_id: %s", show_id)
                for episode_id in islice(get_episodes(show_id), Spodcast.CONFIG.get_max_episodes()):
                    log.debug("episode_id: %s", episode_id)
                    download_episode(episode_id)


================================================
FILE: spodcast/config.py
================================================
import json
import os
import pkg_resources
import sys
from typing import Any

CONFIG_FILE_PATH = '../spodcast.json'

CONFIG_DIR = 'CONFIG_DIR'
CONFIG_PATH = 'CONFIG_PATH'
VERSION = 'VERSION'
VERSION_STR = pkg_resources.require("Spodcast")[0].version

ROOT_PATH = 'ROOT_PATH'
SKIP_EXISTING_FILES = 'SKIP_EXISTING_FILES'
CHUNK_SIZE = 'CHUNK_SIZE'
DOWNLOAD_REAL_TIME = 'DOWNLOAD_REAL_TIME'
LANGUAGE = 'LANGUAGE'
CREDENTIALS_LOCATION = 'CREDENTIALS_LOCATION'
RETRY = 'RETRY'
MAX_EPISODES = 'MAX_EPISODES'
LOG_LEVEL = 'LOG_LEVEL'
RSS_FEED = 'RSS_FEED'
TRANSCODE = 'TRANSCODE'

CONFIG_VALUES = {
    ROOT_PATH:            { 'default': '../Spodcast/',
                            'type': str,
                            'arg': '--root-path',
                            'help': 'set root path for podcast cache' },
    SKIP_EXISTING_FILES:  { 'default': 'True',
                            'type': bool,
                            'arg': '--skip-existing',
                            'help': '[yes|no] skip files with the same name and size. Defaults to "yes".' },
    RETRY:                { 'default': 5,
                            'type': int,
                            'arg': '--retry',
                            'help': 'retry count for Spotify API access' },
    MAX_EPISODES:         { 'default': 1000,
                            'type': int,
                            'arg': '--max-episodes',
                            'help': 'number of episodes to download' },
    CHUNK_SIZE:           { 'default': 50000,
                            'type': int,
                            'arg': '--chunk-size',
                            'help': 'download chunk size' },
    DOWNLOAD_REAL_TIME:   { 'default': 'False',
                            'type': bool,
                            'arg': '--download-real-time',
                            'help': 'simulate streaming client' },
    LANGUAGE:             { 'default': 'en',
                            'type': str,
                            'arg': '--language',
                            'help': 'preferred content language' },
    CREDENTIALS_LOCATION: { 'default': 'credentials.json',
                            'type': str,
                            'arg': '--credentials-location',
                            '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).' },
    RSS_FEED:             { 'default': 'True',
                            'type': bool,
                            'arg': '--rss-feed',
                            '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".' },
    TRANSCODE:            { 'default': 'False',
                            'type': bool,
                            'arg': '--transcode',
                            '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".' },
    LOG_LEVEL:            { 'default': 'warning',
                            'type': str,
                            'arg': '--log-level',
                            'help': 'log level (debug/info/warning/error/critical)' }
}

class Config:
    Values = {}

    @classmethod
    def load(cls, args) -> None:
        app_dir = os.path.dirname(__file__)
        dump_config=False

        config_fp = CONFIG_FILE_PATH
        if args.config_location:
            config_fp = args.config_location

        true_config_file_path = os.path.join(app_dir, config_fp)

        # Load config from spodcast.json

        if not os.path.exists(true_config_file_path):
            dump_config=True
            os.makedirs(os.path.dirname(true_config_file_path), exist_ok=True)
            cls.Values = cls.get_default_json()
        else:
            with open(true_config_file_path, encoding='utf-8') as config_file:
                jsonvalues = json.load(config_file)
                cls.Values = {}
                for key in CONFIG_VALUES:
                    if key in jsonvalues:
                        cls.Values[key] = cls.parse_arg_value(key, jsonvalues[key])

        # Add default values for missing keys

        for key in CONFIG_VALUES:
            if key not in cls.Values:
                cls.Values[key] = cls.parse_arg_value(key, CONFIG_VALUES[key]['default'])
                dump_config=True

        # Override config from commandline arguments

        for key in CONFIG_VALUES:
            if key.lower() in vars(args) and vars(args)[key.lower()] is not None:
                cls.Values[key] = cls.parse_arg_value(key, vars(args)[key.lower()])

        # dump current config to config file

        if dump_config:
            with open(true_config_file_path, 'w', encoding='utf-8') as config_file:
                json.dump(cls.get_config_json(), config_file, indent=4)

        # these values should not be overriden

        cls.Values[CONFIG_DIR] = os.path.dirname(true_config_file_path)
        cls.Values[CONFIG_PATH] = str(true_config_file_path)
        cls.Values[VERSION] = str(VERSION_STR)

    @classmethod
    def get_default_json(cls) -> Any:
        r = {}
        for key in CONFIG_VALUES:
            r[key] = CONFIG_VALUES[key]['default']
        return r

    @classmethod
    def get_config_json(cls) -> Any:
        r = {}
        for key in CONFIG_VALUES:
            r[key]=cls.Values[key]
        return r

    @classmethod
    def parse_arg_value(cls, key: str, value: Any) -> Any:
        if type(value) == CONFIG_VALUES[key]['type']:
            return value
        if CONFIG_VALUES[key]['type'] == str:
            return str(value)
        if CONFIG_VALUES[key]['type'] == int:
            return int(value)
        if CONFIG_VALUES[key]['type'] == bool:
            if str(value).lower() in ['yes', 'true', '1']:
                return True
            if str(value).lower() in ['no', 'false', '0']:
                return False
            raise ValueError("Not a boolean: " + value)
        raise ValueError("Unknown Type: " + value)

    @classmethod
    def get(cls, key: str) -> Any:
        return cls.Values.get(key)

    @classmethod
    def get_config_dir(cls) -> str:
        return cls.get(CONFIG_DIR)

    @classmethod
    def get_root_path(cls) -> str:
        return os.path.join(os.path.dirname(__file__), cls.get(ROOT_PATH))

    @classmethod
    def get_skip_existing_files(cls) -> bool:
        return cls.get(SKIP_EXISTING_FILES)

    @classmethod
    def get_chunk_size(cls) -> int:
        return cls.get(CHUNK_SIZE)

    @classmethod
    def get_language(cls) -> str:
        return cls.get(LANGUAGE)

    @classmethod
    def get_download_real_time(cls) -> bool:
        return cls.get(DOWNLOAD_REAL_TIME)

    @classmethod
    def get_credentials_location(cls) -> str:
        credentials_location = cls.get(CREDENTIALS_LOCATION)
        return credentials_location if os.path.isabs(credentials_location) else os.path.join(cls.get(CONFIG_DIR), cls.get(CREDENTIALS_LOCATION))

    @classmethod
    def get_retry(cls) -> int:
        return cls.get(RETRY)

    @classmethod
    def get_max_episodes(cls) -> int:
        return cls.get(MAX_EPISODES)

    @classmethod
    def get_rss_feed(cls) -> bool:
        return cls.get(RSS_FEED)

    @classmethod
    def get_transcode(cls) -> bool:
        return cls.get(TRANSCODE)

    @classmethod
    def get_log_level(cls) -> str:
        return str(cls.get(LOG_LEVEL)).upper()

    @classmethod
    def get_bin_path(cls) -> str:
        return str(sys.argv[0])

    @classmethod
    def get_config_path(cls) -> str:
        return cls.get(CONFIG_PATH)

    @classmethod
    def get_version_str(cls) -> str:
        return cls.get(VERSION)

    @classmethod
    def get_version_int(cls) -> int:
        return int(cls.get(VERSION).replace('.',''))


================================================
FILE: spodcast/const.py
================================================
TYPE = 'type'
LIMIT = 'limit'
OFFSET = 'offset'
CREDENTIALS_PREFIX = 'spodcast-cred'
USER_READ_EMAIL = 'user-read-email'
FILE_EXISTS = -1
OPEN_SPOTIFY_URL = 'open.spotify.com'
IMAGE_CDN = lambda image_id_hex: f'https://i.scdn.co/image/{image_id_hex}'


================================================
FILE: spodcast/feedgenerator.py
================================================
import re

RSS_FEED_FILE_NAME = '.index.php'
RSS_FEED_INFO_EXTENSION = 'info'
RSS_FEED_SHOW_INDEX = 'index'
RSS_FEED_SHOW_IMAGE = 'image.jpg'
RSS_FEED_VERSION = '$SPODCAST_VERSION$ '
VERSION_NOT_FOUND = 0

def get_index_version(filename) -> str:
    with open(filename, 'rb') as f:
        for line in f.readlines():
            m = re.search(RSS_FEED_VERSION + ' (\d+.\d+.\d+)', str(line))
            if m:
                return int(m[1].replace('.',''))

    return VERSION_NOT_FOUND


def RSS_FEED_CODE(version):
    return r'''<?php
/* ''' + RSS_FEED_VERSION + version + r''' */
const SHOW_INDEX = "''' + RSS_FEED_SHOW_INDEX + r'''";
const INFO = "''' + RSS_FEED_INFO_EXTENSION + r'''";
$PROTOCOL = (empty($_SERVER['HTTPS'])) ? "http://" : "https://";
header("Content-type: text/xml");
$feed_name = "Spodcast autofeed";
$feed_description = "Spodcast autofeed";
$base_url = strtok($PROTOCOL . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '?');
$feed_logo = "$base_url/''' + RSS_FEED_SHOW_IMAGE + r'''";
$feed_link = $base_url;
$allowed_extensions = array('mp4','m4a','aac','mp3','ogg');

$sinfo=SHOW_INDEX.".".INFO;
if(file_exists($sinfo)) {
    $json=file_get_contents($sinfo);
    $info=json_decode($json);
    $feed_name=$info->title;
    $feed_description=$info->description;
    $feed_link=$info->link;
}

?>
<?php echo '<?xml version="1.0" encoding="utf-8"?>';  // use php to output the "<?" ?>
<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" >
    <channel>
        <title><?php echo $feed_name; ?></title>
        <link><?php echo $feed_link; ?></link>
        <image>
            <url><?php echo $feed_logo; ?></url>
            <title><?php echo $feed_name; ?></title>
            <link><?php echo $feed_link; ?></link>
        </image>
        <description><?php echo $feed_description; ?></description>
        <atom:link href="<?php echo $base_url; ?>" rel="self" type="application/rss+xml" />
<?php
$raw_files = scandir ('.');
usort($raw_files, function($a, $b) {
    return filemtime($a) < filemtime($b);
});

foreach ($raw_files as &$raw_file) {
    $raw_file_info = pathinfo($raw_file);
    $extension = strtolower($raw_file_info['extension']);
    if(!empty($extension)) {
        if(in_array ($extension,$allowed_extensions)) {
            $finfo=$raw_file.".".INFO;
            if(file_exists($finfo)) {
                $json=file_get_contents($finfo);
                $info=json_decode($json);
                echo "        <item>\n";
                echo "            <title>".$info->title."</title>\n";
                echo "            <description>".$info->description."</description>\n";
                echo "            <guid>".$info->guid."</guid>\n";
                echo "            <link>".$base_url.$info->filename."</link>\n";
                echo "            <enclosure url=\"".$base_url.$info->filename."\" length=\"".$info->size."\" type=\"".$info->mimetype."\" />\n";
                echo "            <media:content url=\"".$base_url.$info->filename."\" medium=\"".$info->medium."\" duration=\"".$info->duration."\" type=\"".$info->mimetype."\" />\n";
                echo "            <pubDate>".$info->date."</pubDate>\n";
                echo "            <itunes:duration>".$info->duration."</itunes:duration>\n";
                echo "        </item>\n";
            }
        }
    }
}
?>
    </channel>
</rss>'''

def RSS_INDEX_CODE(bin_path, config_name, version):
    return r'''<?php
/* ''' + RSS_FEED_VERSION + version + r''' */
const INFO="''' + RSS_FEED_INFO_EXTENSION + r'''";
const SHOW_INFO="''' + RSS_FEED_SHOW_INDEX + r'''.".INFO;
const SPODCAST="''' + bin_path + r'''";
const SPODCAST_CONFIG="''' + config_name + r'''";
const SHOW_IMAGE="''' + RSS_FEED_SHOW_IMAGE + r'''";
const FEEDS_INFO="feeds.".INFO;
const SETTINGS_INFO="settings.".INFO;
const MAX_EPISODES=3;
const KEEP_EPISODES=5;
const UPDATEABLE=['max','keep'];
const CLI_COMMANDS=['refresh'];
const SUCCESS='success';
const ERROR='error';
const LOG_LEVEL='warning';
const NOT_FOUND=-1;

$SPODCAST_CONFIG=dirname(__FILE__)."/".SPODCAST_CONFIG;
$SPODCAST_COMMAND=SPODCAST." -c ".$SPODCAST_CONFIG;

# CLI
if (PHP_SAPI == "cli") {
    global $SPODCAST_CONFIG;
    if (count($argv) < 2) {
        echo "use: php ".__FILE__." <command> [options...]".PHP_EOL;
        echo "     commands: ".implode("|",CLI_COMMANDS).PHP_EOL;
        die();
    }

    $settings=read(dirname(__FILE__)."/".SETTINGS_INFO);
    $feeds=read(dirname(__FILE__)."/".FEEDS_INFO);

    $command=$argv[1];
    if($command == "refresh") {
        list($retval, $result) = refresh_shows($feeds);
        if ($retval > 0) {
            echo "An error occurred during refresh, return value was $retval" . PHP_EOL;
        }
        echo implode(PHP_EOL, $result);
    }
    die();
}

# CGI/API
$PROTOCOL = (empty($_SERVER['HTTPS'])) ? "http://" : "https://";
$SPODCAST_URL = $PROTOCOL . $_SERVER['HTTP_HOST'] . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$feeds=get_feeds(dirname(__FILE__));
$settings=get_settings();
$config=get_spodcast_config();
$ERROR_MESSAGE=null;
$ERROR_DETAILS=null;

function get_feeds($dir) {
    global $SPODCAST_URL;
    foreach(glob($dir."/*/".SHOW_INFO) as $show_info) {
        $episodes=get_episodes(dirname($show_info));
        $json=file_get_contents($show_info);
        $info=json_decode($json);
        $feeds[$info->link]['title']=$info->title;
        $feeds[$info->link]['image']=$info->image;
        $feeds[$info->link]['episodes']=count($episodes);
        $feeds[$info->link]['last']=date("Y-m-d",strtotime($episodes[0]['date']));
        $feeds[$info->link]['directory']=dirname($show_info);
        $feeds[$info->link]['max']=$info->max ?? MAX_EPISODES;
        $feeds[$info->link]['keep']=$info->keep ?? KEEP_EPISODES;
        $feeds[$info->link]['feed']=$SPODCAST_URL.basename(dirname($show_info));
    }
    uasort($feeds, fn ($a, $b) => strnatcmp($a['title'], $b['title']));
    store($feeds, FEEDS_INFO);
    return $feeds;
}

function get_episodes($dir) {
    $episodes=[];
    foreach(glob($dir."/*.".INFO) as $episode_info) {
        if(basename($episode_info) == SHOW_INFO) {
            continue;
        }
        $json=file_get_contents($episode_info);
        $info=json_decode($json);
        $episodes[]=["filename"=>$info->filename,"date"=>$info->date,"title"=>$info->title];
    }
    usort($episodes, fn ($a, $b) => strtotime($b["date"]) - strtotime($a["date"]));
    return $episodes;
}

function get_settings() {
    global $SPODCAST_URL;
    $settings=read(SETTINGS_INFO);
    $settings['spodcast_url']=$settings['spodcast_url'] ?? $SPODCAST_URL;
    $settings['update_start']=$settings['update_start'] ?? 0;
    $settings['update_rate']=$settings['update_rate'] ?? 1;
    $settings['update_enabled']=$settings['update_enabled'] ?? false;
    $settings['log_level']=$settings['log_level'] ?? LOG_LEVEL;
    store($settings, SETTINGS_INFO);
    return $settings;
}

function get_spodcast_config() {
    global $SPODCAST_CONFIG;
    $config=read($SPODCAST_CONFIG);
    return $config;
}

function get(&$var, $default=null) {
    return isset($var) ? $var : $default;
}

function read($file) {
    if(is_readable($file)) {
        $json=file_get_contents($file);
        $info=json_decode($json, true);
    } else {
        $info=[];
    }
    return $info;
}

function store($info, $file) {
    $f = fopen($file,'w');
    $result = fwrite($f, json_encode($info));
    fclose($f);
    return ($result === false) ? ERROR : SUCCESS;
}

function cron_signature($crontab, $CRON_SIGNATURE) {
    $index = 0;
    foreach ($crontab as $line) {
        if (strpos($line, $CRON_SIGNATURE)  !== false) {
            return $index;
        }
        $index++;
    }
    return NOT_FOUND;
}

function debug($var) {
    ob_start();
    var_dump($var);
    error_log(ob_get_clean());
}

function submit_crontab($crontab) {
    $retval = null;
    $output = null;
    $tempfile=tempnam(sys_get_temp_dir(), 'spodcast');
    file_put_contents($tempfile, implode(PHP_EOL,$crontab));
    $command="crontab ".$tempfile;
    exec($command, $output, $retval);
    unlink($tempfile);

    return [$retval, $output];
}

function get_range($start, $rate) {
    for ($i=0; $i < $rate; $i++) {
        $arr[]=(($start%(24/$rate))+($i*(24/$rate)))%24;
    }
    return implode(",", $arr);
}

function background_check_id($id) {
    $runfile = md5($id).".json";
    $log = md5($id).".log";
    if (is_readable($runfile)) {
        $info = read($runfile);
        if (background_check($info['pid'])) {
            return true;
        }
        unlink($runfile);
        unlink($log);
    }
    return false;
}

function background_check($pid) {
    try {
        $result = shell_exec(sprintf("ps %d", $pid));
        if (count(preg_split("/\n/", $result)) > 2) {
            return true;
        }
    } catch(Exception $e) {}
    return false;
}

# [ status, output ] return functions
function update_scheduler($enable, $start, $rate) {
    $CRON_SIGNATURE="SPODCAST:".dirname(__FILE__);
    $crontab=null;
    $retval=null;
    exec("crontab -l", $crontab, $retval);
    if ($retval == 0) {
        $index=cron_signature($crontab, $CRON_SIGNATURE);
        if ($enable == true) {
            if($index !== NOT_FOUND) {
                array_splice($crontab, $index, 1);
            }
            $crontab[]=sprintf("%d %s * * * php %s refresh # %s".PHP_EOL, rand(5,25), get_range($start, $rate),  __FILE__, $CRON_SIGNATURE);
            return submit_crontab($crontab);
        } else {
            if ($index !== NOT_FOUND) {
                array_splice($crontab, $index, 1);
                $crontab[count($crontab)-1]=rtrim($crontab[count($crontab)-1]).PHP_EOL;
                return submit_crontab($crontab);
            }
        }
    } else {
        return [$retval, "failed to update scheduler"];
    }
}

function login($username, $password, $return_output=false) {
    global $SPODCAST_COMMAND;
    global $settings;
    $output = null;
    $retval = null;
    $tempfile=tempnam(sys_get_temp_dir(), 'spodcast');
    file_put_contents($tempfile, "$username $password");
    $command=$SPODCAST_COMMAND . " --log-level " . $settings['log_level'] . " -l ".$tempfile." 2>&1";
    exec($command, $output, $retval);
    unlink($tempfile);

    return [$retval, $output];
}

function background_run($command, $id) {
    $retval=null;
    $md5 = md5($id);
    $runfile = $md5.".json";
    $output = $md5.".log";
    $cmd = sprintf("nohup %s > %s 2>&1 & echo $!", $command, $output);
    exec($cmd, $pid, $retval);
    if ($retval == 0 && count($pid) > 0 && $pid[0] > 0) {
        $info['command']=$command;
        $info['log']=$output;
        $info['pid']=(int) $pid[0];
        store($info, $runfile);
        return [$retval, $pid[0]];
    } else {
        return [$retval, 0];
    }
}

function background_add_feed($url, $max) {
    global $SPODCAST_COMMAND;
    global $settings;
    $output = null;
    $retval = null;
    $command=$SPODCAST_COMMAND  . " --log-level " . $settings['log_level'] . " --max-episodes ".(int)$max." ".escapeshellarg($url);
    list($retval, $pid) = background_run($command, $url);
    if ($retval == 0 && (int) $pid > 0) {
        return [$retval, $pid];
    }
    return [$retval, 0];
}


function add_feed($url, $max) {
    global $SPODCAST_COMMAND;
    global $settings;
    $output = null;
    $retval = null;
    $command=$SPODCAST_COMMAND  . " --log-level " . $settings['log_level'] . " --max-episodes ".(int)$max." ".escapeshellarg($url)." 2>&1";
    exec($command, $output, $retval);
    return [$retval, $output];
}

function update_feed($url, $max, $keep, $feeds) {
    $output = null;
    $retval = null;
    if ($max > 0) {
    list($retval,$output) = add_feed($url, $max);
        if ($retval > 0) {
            return [$retval, $output];
        }
    }
    $directory=$feeds[$url]['directory'];
    $episodes=get_episodes($directory);
    if(count($episodes) > $keep) {
        $to_delete=array_splice($episodes, $keep);
        foreach ($to_delete as $episode) {
            $command="rm -f ".escapeshellarg($directory."/".$episode['filename'])." 2>&1";
            exec($command, $output, $retval);
            if ($retval > 0) {
                return [$retval, $output];
            }
            $command="rm -f ".escapeshellarg($directory."/".$episode['filename']).".".INFO." 2>&1";
            exec($command, $output, $retval);
            if ($retval > 0) {
                return [$retval, $output];
            }
        }
    }
    return [$retval, $output];
}

function delete_feed($url, $return_output=false) {
    $output = null;
    $retval = null;
    $feeds=read(FEEDS_INFO);
    $feed_dir=$feeds[$url]['directory'];
    $command="rm -rf ".$feed_dir." 2>&1";
    exec($command, $output, $retval);
    return [$retval, $output];
}

function update_show($url, $field, $value) {
    if (array_search($field, UPDATEABLE) === false) {
        return [1, "$field is not an updateable field"];
    } else {
        $feeds=read(FEEDS_INFO);
        $show_dir=$feeds[$url]['directory'];
        $show=read($show_dir."/".SHOW_INFO);
        $show[$field]=$value;
        store($show, $show_dir."/".SHOW_INFO);
        return [0, "$field set to $value"];
    }
}

function refresh_shows($feeds) {
    $result = [];
    $status = 0;
    foreach ($feeds as $url => ["title"=>$title, "directory"=>$directory, "max"=>$max, "keep"=>$keep]) {
        $output = null;
        $retval = 0;
        list($retval, $output) = update_feed($url, $max, $keep, $feeds, true);
        if ($retval > 0) {
            $status = $retval;
        }
        $result = array_merge($result, $output);
    }
    return [$status, $result];
}

# terminating functions

function show_error($message, $details) {
    header("Location: ./?action=error&message=".urlencode($message)."&details=".urlencode(implode(PHP_EOL,$details)));
    die();
}

function json_response($info) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($info, true);
    exit();
}

# CGI commands

switch(get($_GET['action'])) {

case 'refresh':
    $url = get($_POST['url']);
    $max = (int) get($_POST['max']) ?? MAX_EPISODES;
    $keep = (int) get($_POST['keep']) ?? KEEP_EPISODES;
    $info['url']=$url;
    $info['show']=$feeds[$url];
    $info['id']=basename($url);
    if ($max > $keep) {
        $info['result'] = "It does not make sense for the number of episodes to refresh to be larger than the number of episodes to keep.";
        $info['status'] = 'ERROR';
    } else {
        list($result,$output) = update_feed($url, $max, $keep, $feeds, false);
        $info['status'] = ($result == 0) ? 'SUCCESS': 'ERROR';
        if ($result != 0) {
            $info['result'] = "Refresh failed";
        }
    }
    json_response($info);

case 'new':
    $url = get($_POST['url']);
    list($result, $output) = background_add_feed($url, MAX_EPISODES, false);
    $info['url']=$url;
    $info['show']=$feeds[$url] ?? null;
    $info['id']=basename($url);
    $info['status']= ($result == 0) ? 'SUCCESS': 'ERROR';
    json_response($info);

case 'update':
    $url = get($_POST['url']);
    $field = get($_POST['field']);
    $value = get($_POST['value']);
    if (in_array(strtolower($field), UPDATEABLE)) {
        list($result, $output) = update_show($url, $field, $value);
        if ($result == 0) {
            $info['result'] = $output;
            $info['status'] = 'SUCCESS';
        } else {
            $info['result'] = "Update failed";
            $info['status'] = 'ERROR';
        }
    } else {
        $info['result'] = "$field can not be updated";
        $info['status'] = 'ERROR';
    }

    json_response($info);

case 'schedule':
    $enable = (get($_POST['enable']) == "true" ? true : false);
    $start = (int) get($_POST['start']);
    $rate = (int) get($_POST['rate']);
    $settings['update_enabled'] = $enable;
    $settings['update_start'] = $start;
    $settings['update_rate'] = $rate;
    $result = store($settings, SETTINGS_INFO);
    if ($result === ERROR) {
        $info['status'] = 'ERROR';
        $info['result'] = 'Could not store scheduler preferences, giving up';
    } else {
        list($result, $output) = update_scheduler($enable, $start, $rate);
        if ($result == 0) {
            $info['status'] = 'SUCCESS';
            $info['result'] = ($enable === true) ? "Scheduled updates enabled, $rate times per day starting at $start:00" : 'Scheduled updates disabled';
        } else {
            $info['status'] = 'ERROR';
            $info['result'] = implode(PHP_EOL, $result);
        }
    }
    json_response($info);

case 'transcode':
    $enable = (get($_POST['enable']) == "true" ? true : false);
    $config['TRANSCODE']=$enable;
    $result = store($config, $SPODCAST_CONFIG);
    if ($result === SUCCESS) {
        $info['status'] = 'SUCCESS';
        $info['result'] = ($enable) ? 'Transcoding enabled' : 'Transcoding disabled';
    } else {
        $info['status'] = 'ERROR';
        $info['result'] = 'Could not enable transcoding: can not write to config file';
    }
    json_response($info);

case 'logging':
    $level = get($_POST['level']) ?? LOG_LEVEL;
    $config['LOG_LEVEL']=$level;
    if (in_array(strtolower($level), ['critical','error','warning','info','debug'])) {
        $result = store($config, $SPODCAST_CONFIG);
        if ($result === SUCCESS) {
            $info['status'] = 'SUCCESS';
            $info['result'] = 'Log level set to '. $level;
        } else {
            $info['status'] = 'ERROR';
            $info['result'] = 'Could not change log level: can not write to Spodcast config file';
        }
    } else {
        $info['status'] = 'ERROR';
        $info['result'] = 'Invalid log level ' . $level;
    }
    json_response($info);

case 'status':
    $url = get($_POST['url']);
    $info['url'] = $url;
    $info['show']=$feeds[$url] ?? null;
    $info['id'] = basename($url);
    $info['status'] = background_check_id($url) ? 'ACTIVE' : 'READY';
    json_response($info);

case 'delete':
    $url = get($_POST['url']);
    $info['url'] = $url;
    $info['id'] = basename($url);
    list($result, $output) = delete_feed($url);
    if ($result !== 0) {
        $info['status'] = 'ERROR';
        $info['result'] = "Delete feed failed: " . implode(PHP_EOL, $output);
    } else {
        $info['status'] = 'SUCCESS';
        $info['result'] = "Deleted <i>" . $feeds[$url]['title'] . "</i>" ;
    }
    json_response($info);

case 'login':
    $username = get($_POST['username']);
    $password = get($_POST['password']);
    list($result, $output) = login($username, $password);
    if ($result === 0) {
        $info['status'] = 'SUCCESS';
        $info['result'] = 'Login succeeded';
    } else {
        $info['status'] = 'ERROR';
        $info['result'] = 'Login failed for user '. $username;
    }
    json_response($info);

case 'update_shows':
    list($result, $output) = refresh_shows($feeds);
    $info['status'] = ($result == 0) ? 'SUCCESS' : 'ERROR';
    $info['result'] = $output;
    json_response($info);

case 'error':
    $ERROR_MESSAGE = get($_POST['message']);
    $ERROR_DETAILS = get($_POST['details']);
default:
    break;
}

$ACTIVE=[];

foreach (array_keys($feeds) as $url) {
    if (background_check_id($url)) {
        $ACTIVE[$url]=true;
    }
}

$TRANSCODE_ENABLED=(array_key_exists('TRANSCODE', $config)) ? (($config['TRANSCODE'] == "True") ? true : false) : false;
$LOG_LEVEL=$config['LOG_LEVEL'];
$UPDATE_ENABLED=$settings['update_enabled'];
$UPDATE_START=$settings['update_start'];
$UPDATE_RATE=$settings['update_rate'];
?>
<html>
<head>
    <title>Spodcast feed manager</title>
    <style>
        div, body, html { background-color: white; margin: 0.5em; }
        div#new-feed { margin: 0em; display: flex; }
        input#url { flex: 1; }
        div#settings-header { text-align: right; }
        div input, div button { height: 2em; font-size: 1.2em; margin: 0 1em 1em 0; }
        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%; }
        div#settings, div#error { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99; opacity: 0.95; margin: 0.5em auto; }
        div.hidden { visibility: hidden; }
        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; }
        .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; }
        .show .placeholder { height: 4em; }
        .setgroup { border: 1px solid black; margin: 1em; }
        .error { border: 2px solid red; margin: 1em; }
        .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; }
        .comment { font-size: 80%; font-style: italic;}
        .entry > a { text-decoration: none; color: black; }
        .entry > a:hover { color: red; }
        .title { background: linear-gradient(90deg, #E0E0E0, #F0F0F0); border-radius: 6px; }
        .link, .title { width: 40%; }
        .title { text-transform: uppercase; }
        .logo { width: 5%; min-width: 5em; flex-grow: 0; background: #F0F0F0; }
        .logo img { width: 4em; height: 4em; }
        .stats { width: 10%; min-width: 10em; }
        .feed { font-size: 90%; }
        .actions { display: flex; flex-direction: row; align-content: flex-end; flex: wrap; width: 100vw; background: #F0F0F0; }
        .actions div:nth-of-type(1) { flex-grow: 1; }
        .actions div { margin: 0 0 0 2em; background: inherit; }
        .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; }
        .actions a:hover { color: white; background: #222; }
        #delete { color: red; background: white; }
        #delete:hover { color: white; background: red; }
        #update-settings { background: inherit; }

        .loader { display: inline-block; width: 4em; height: 4em; }
        .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; }
        @keyframes loader { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        #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;}
        #toast.success { border: 1px solid black; }
        #toast.error { border: 6px solid red; }

        legend { margin-left: 1.5em; font-size: 100%; border: 1px solid black; border-radius: 6px; background: white; padding: 0.1em 0.5em; }
        .error legend { border: 2px solid red; }
 
        @media all and (max-width: 500px) {
            .show { display: block; }
            .entry { width: 95% !important; }
            .last { margin-bottom: 1em; }
            .actions { flex-direction: column; align-items: flex-end; }
            .actions div { margin: 0.2em 0; }
        }
    </style>
</head>
<body>
    <div id="new-feed">
        <input id="url" name="feed" type="text" placeholder="Spotify show/episode url">
        <button id='new'>Add</button>
        <button id='opensettings' onclick="document.getElementById('settings').classList.remove('hidden'); return false;">Settings</button>
    </div>
    <div id="feed-list">
    <?php foreach($feeds as $url => ["title"=>$title,"image"=>$image,"episodes"=>$episodes,"last"=>$last,"max"=>$max,"keep"=>$keep,"feed"=>$feed]): ?>
        <div class="show" id="<?php echo basename($url) ?>">
            <div class="overlay loader <?php echo (array_key_exists($url, $ACTIVE)) ? "" : "hidden" ?>"></div>
            <div class="entry title"><?=$title?></div>
            <div class="entry logo"><img src="<?=$feed."/".SHOW_IMAGE?>"/></div>
            <div class="entry link"><a target="_blank" href="<?=$url?>"><?=htmlspecialchars($url)?></a></div>
            <div class="entry stats" id="stats-<?php echo basename($url) ?>"><?=$last?>&nbsp;(<?=$episodes?>)</div>
            <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>
            <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>
        </div>
    <?php endforeach; ?>
    </div>
    <div id="settings" class="hidden">
        <div id="settings-header">
            <button id='closesettings' onclick="document.getElementById('settings').classList.add('hidden'); return false;">Close</button>
        </div>
        <fieldset id="credentials" class="setgroup">
            <legend>Spotify login</legend>
            <div class="setitem"><input id="username" name="username" type="text" placeholder="Spotify username">&nbsp;
            <input id="password" name="password" type="password" placeholder="Spotify password"></div>
            <div class="setitem"><button id="do-login" name="do-login">Login to Spotify</button></div>
        </fieldset>
        <fieldset id="scheduler" class="setgroup">
            <legend>Feed update schedule</legend>
            <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>
            <div class="setitem"><button id="update-enable" name="update-enable">Enable scheduled updates</button></div>
            <div id="update-settings">
            <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>
            <div class="setitem comment">Updates start 5 to 25 minutes after the hour</div>
            <div class="setitem"><button id="do-update" name="do-update">Update schedule</button>
            <button id="update-disable" name="update-disable">Disable updates</button></div>
            </fieldset>
        <fieldset id="transcode" class="setgroup">
            <legend>Transcode</legend>
            <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>
            <div class="setitem"><button id="transcode-enable" name="transcode-enable">Enable transcoder</button><button id="transcode-disable" name="transcode-disable">Disable transcoder</button></div>
        </fieldset>
        <fieldset id="logging" class="setgroup">
            <legend>Logging</legend>
            <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>
            <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>
        </fieldset>


        </div>
    </div>
    <div id="error" class="hidden">
    <fieldset id="errormessage" class="error">
        <legend>Error: <?=$ERROR_MESSAGE?></legend>
        <div class="errorline"><pre><?=$ERROR_DETAILS?></pre></div>
        <div class="errorline"><button id="hide-error" onclick="window.location.href='.'; return false;">Close this message</button></div>
    </fieldset>
    </div>
    <div class="hidden" id="toast"></div>
    <script>
    function xhr(type, url, data, options) {
        options = options || {};
        var request = new XMLHttpRequest();
        request.open(type, url, true);
        if(type === "POST") {
            request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        }
        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status >= 200 && this.status < 400) {
                    options.success && options.success(parse(this.responseText));
                } else {
                    options.error && options.error(this.status);
                }
            }
        };
        request.send(data);
    }
    function parse(text) {
        try {
            return JSON.parse(text);
        } catch(e) {
            return text;
        }
    }
    function basename(path) {
        return path.replace(/.*\//, '');
    }
    function newfeed() {
        xhr("POST", '?action=new', 'url=' + encodeURI(document.getElementById('url').value), {success:addShow,error:removeShade});
    }
    function addShow(info) {
        title="Adding show (" + info.url + "), please wait...";
        show=document.createElement('div'); show.setAttribute('class', 'show placeholder'); show.setAttribute('id', info.id);
        shade=document.createElement('div'); shade.setAttribute('class', 'overlay');
        logo=document.createElement('div'); logo.setAttribute('class', 'entry logo loader');
        title=document.createElement('div'); title.setAttribute('class', 'entry title');
        feedlist=document.getElementById('feed-list');
        show.appendChild(shade); show.appendChild(title); show.appendChild(logo);
        title.innterHTML = title;
        first=feedlist.firstElementChild;
        feedlist.insertBefore(show, first);
        waitUpdate(info);
    }
    function login() {
        xhr("POST", '?action=login', 'username=' + document.getElementById('username').value + '&password=' + document.getElementById('password').value, {success:showToast, error:showToast});
    }
    function refresh(url) {
        unhide(basename(url));
        id = basename(url);
        max=document.getElementById('max-' + id).value;
        keep=document.getElementById('keep-' + id).value;
        xhr("POST", '?action=refresh', 'url=' + encodeURI(url) + '&max=' + max + '&keep=' + keep, {success:wait, error:removeShade});
    }
    function waitUpdate(info) {
        if (info.status == 'READY' || info.status == 'ERROR') {
            window.location.href = '';
        }
        if (info.show != null) {
            document.getElementById(info.id).childNodes.item(1).innerHTML = "Adding show: " + info.show.title + " (" + info.show.episodes + " episodes of 3 downloaded)...";
        } else {
            document.getElementById(info.id).childNodes.item(1).innerHTML = "Adding show: " + info.url + "...";
        }
        setTimeout(function() {
                xhr("POST", '?action=status', 'url=' + encodeURI(info.url), {success:waitUpdate, error:removeShade});
                }, 2000);
    }
    function wait(info) {
        if (info.status == 'READY' || info.status == 'ERROR') {
            document.getElementById('stats-' + info.id).innerHTML = info.show.last + '&nbsp;(' + info.show.episodes + ')';
            hide(info.id);
        } else { 
            if (info.show != null) {
                document.getElementById('stats-' + info.id).innerHTML = info.show.last + '&nbsp;(' + info.show.episodes + ')';
            }
            setTimeout(function() {
                    xhr("POST", '?action=status', 'url=' + encodeURI(info.url), {success:wait, error:removeShade});
                    }, 2000);
        }
    }
    function removeShade(info) {
        hide(info.id);
    }
    function hide(id) {
        document.getElementById(id).firstElementChild.classList.add('hidden');
    }
    function unhide(id) {
        document.getElementById(id).firstElementChild.classList.remove('hidden');
    }
    function schedule(enable) {
        xhr("POST", '?action=schedule', 'enable=' + enable + '&rate=' + document.getElementById('update-rate').value + '&start=' + document.getElementById('update-start').value, {success:showToast, error:showToast});
    }
    function transcode(enable) {
        xhr("POST", '?action=transcode', 'enable=' + enable, {success:showToast, error:showToast});
    }
    function logUpdate(e) {
        xhr("POST", '?action=logging', 'level=' + e.value, {success:showToast, error:showToast});
    }
    function selectElement(id, val) {
        document.getElementById(id).value=val;
    }
    function showUpdate(e,url,field) {
        id = basename(url);
        max=document.getElementById('max-' + id);
        keep=document.getElementById('keep-' + id);
        maxval = parseInt(max.value);
        keepval = parseInt(keep.value);
        if(maxval > keepval) {
            keeper = (maxval > 2) ? 5 : 2;
            if (confirm("Sync count " + maxval + " is higher than Keep count " + keepval + "\n\n" +
                "It does not make sense to refresh more expisodes than are kept in cache." +
                "Press OK to continue, Keep will be set to " + keeper + ". Otherwise press Cancel")) {
                keep.value = keeper;
            } else {
                keep.value = keepval;
                max.value = maxval;
                return false;
            }
        }
        xhr("POST", '?action=update', 'url=' + encodeURI(url) + '&field=' + field + '&value=' + e.value, {success:showToast, error:showToast});
    }
    function confirmDelete(title, url) {
        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?')) {
            xhr("POST", '?action=delete', 'url=' + encodeURI(url), {success:deleteShow, error:showToast});
        }
        return false;
    }
    function deleteShow(info) {
        document.getElementById(info.id).remove();
        showToast(info);
    }
    function showToast(info) {
        var toast=document.getElementById('toast');
        if (info.status == 'ERROR') {
            toast.classList.remove('success');
            toast.classList.add('error');
        } else {
            toast.classList.remove('error');
            toast.classList.add('success');
        }
        toast.innerHTML=info.result;
        toast.classList.remove("hidden");
        window.setTimeout(function() {
            toast = document.getElementById('toast');
            toast.classList.add("hidden");
            toast.classList.replace('error', 'success');
            toast.innerHTML="";
        }, 2000);
    }

    document.getElementById('new').onclick = function() {
        newfeed();
    };
    document.getElementById('do-login').onclick = function() {
        login();
    };
    document.getElementById('do-update').onclick = function() {
        schedule(true);
    };
    document.getElementById('url').onkeydown = function(e) {
        if(e.keyCode == 13) {
            newfeed();
        }
    };

    var schedule_enable = document.getElementById('update-enable');
    var schedule_disable = document.getElementById('update-disable');
    var schedule_entries = document.getElementById('update-settings');
    var transcode_enable = document.getElementById('transcode-enable');
    var transcode_disable = document.getElementById('transcode-disable');
    schedule_entries.style.display = '<?php echo ($UPDATE_ENABLED ? 'initial' : 'none');?>';
    schedule_enable.style.display = '<?php echo ($UPDATE_ENABLED ? 'none' : 'initial');?>';
    transcode_enable.style.display = '<?php echo ($TRANSCODE_ENABLED ? 'none' : 'initial');?>';
    transcode_disable.style.display = '<?php echo ($TRANSCODE_ENABLED ? 'initial' : 'none');?>';

    schedule_enable.onclick = function() {
        schedule_entries.style.display = 'initial';
        schedule_enable.style.display = 'none';
        schedule(true);
    };
    schedule_disable.onclick = function() {
        schedule_entries.style.display = 'none';
        schedule_enable.style.display = 'initial';
        schedule(false);
    };
    transcode_enable.onclick = function() {
        transcode_enable.style.display = 'none';
        transcode_disable.style.display = 'initial';
        transcode(true);
    };
    transcode_disable.onclick = function() {
        transcode_enable.style.display = 'initial';
        transcode_disable.style.display = 'none';
        transcode(false);
    };
    selectElement('update-rate', '<?=$UPDATE_RATE?>');
    selectElement('update-start', '<?=$UPDATE_START?>');
    selectElement('log-level', '<?=$LOG_LEVEL?>');
    <?php foreach($feeds as $url => ["keep"=>$keep,"max"=>$max]) {
        printf("    selectElement('keep-%s', '%d');\n", basename($url), $keep);
        printf("    selectElement('max-%s', '%d');\n", basename($url), $max);
    }?>
    <?php if ($ERROR_MESSAGE != null) {
        echo "    document.getElementById('error').classList.remove('hidden');";
    }?>
    </script>
</body>
</html>'''



================================================
FILE: spodcast/podcast.py
================================================
import json
import logging
import os
import time
from datetime import datetime
from html import escape
import urllib.parse

import base62
from base62 import CHARSET_INVERTED
import ffmpeg

from librespot import util
from librespot.metadata import ShowId, EpisodeId
from librespot.core import ApiClient

from spodcast.const import FILE_EXISTS, IMAGE_CDN
from 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
from spodcast.utils import clean_filename, uri_to_url
from spodcast.spodcast import Spodcast

log = logging.getLogger(__name__)


def hex_to_spotify_id(hex_id):
    return base62.encodebytes(util.hex_to_bytes(hex_id), CHARSET_INVERTED)


def get_show_info(show_id_hex):
    log.info("Fetching show information...")
    show_id = ShowId.from_hex(show_id_hex)
    uri = f'spotify:show:{hex_to_spotify_id(show_id_hex)}'
    info = Spodcast.SESSION.api().get_metadata_4_show(show_id)
    link = uri_to_url(uri)
    description = info.description
    image = IMAGE_CDN(util.bytes_to_hex(info.cover_image.image[1].file_id))

    return link, description, image


def get_episode_info(episode_id_hex):
    log.info("Fetching episode information...")
    episode_id = EpisodeId.from_hex(episode_id_hex)
    uri = f'spotify:episode:{hex_to_spotify_id(episode_id_hex)}'
    info = Spodcast.SESSION.api().get_metadata_4_episode(episode_id)
    podcast_name = info.show.name
    podcast_id = util.bytes_to_hex(info.show.gid)
    episode_name = info.name
    duration_ms = info.duration
    description = info.description
    external_url = info.external_url if info.external_url else None
    pt = info.publish_time
    release_date = f'{pt.year}-{pt.month}-{pt.day}T{pt.hour}:{pt.minute}:00Z'
    date_temp = datetime.strptime(release_date, '%Y-%m-%dT%H:%M:%SZ')
    release_date_clean = f'{date_temp.strftime("%Y")}-{date_temp.strftime("%m")}-{date_temp.strftime("%d")}'

    return podcast_name, podcast_id, duration_ms, episode_name, description, release_date, uri, external_url, release_date_clean


def get_episodes(show_id):
    info = Spodcast.SESSION.api().get_metadata_4_show(show_id)
    episodes = info.episode
    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)

    return [util.bytes_to_hex(episode.gid) for episode in episodes]


def download_file(url, filepath):
    import functools
    import pathlib
    import shutil
    import requests

    mimetype = "audio/mpeg"

    r = requests.get(url, stream=True, allow_redirects=True)
    if r.status_code != 200:
        r.raise_for_status()  # Will only raise for 4xx codes, so...
        log.error(f"Request to {url} returned status code {r.status_code}")
        return

    file_size = int(r.headers.get('Content-Length', 0))

    if (
        os.path.isfile(filepath)
        and abs(file_size - os.path.getsize(filepath)) < 1000
        and Spodcast.CONFIG.get_skip_existing_files()
    ):
        return filepath, FILE_EXISTS, mimetype

    log.info("Downloading file")
    r.raw.read = functools.partial(r.raw.read, decode_content=True)
    with open(filepath, "wb") as file:
        shutil.copyfileobj(r.raw, file)


    return filepath, os.path.getsize(filepath), mimetype


def download_stream(stream, filepath):
    size = stream.input_stream.size

    mp3_filepath = os.path.splitext(filepath)[0] + ".mp3"
    mimetype = "audio/ogg"

    if (
        # "FILE SIZE CHECK TEMPORARILY OUT OF ORDER"
        # Need to find a way to get decrypted content size
        # from Spotify to enable file size checks, for now
        # this only checks for the presence of a file with
        # the same name. To recover from failed downloads
        # simply remove incomplete files
        #
        #((os.path.isfile(filepath)
        #and abs(size - os.path.getsize(filepath)) < 1000)
        (os.path.isfile(filepath)
        or (Spodcast.CONFIG.get_transcode()
        and os.path.isfile(mp3_filepath)))
        and Spodcast.CONFIG.get_skip_existing_files()
    ):
        return filepath, FILE_EXISTS, mimetype
 
    log.info("Downloading stream")
    time_start = time.time()
    downloaded = 0
    with open(filepath, 'wb') as file:
        data = b""
        while data := stream.input_stream.stream().read(Spodcast.CONFIG.get_chunk_size()):
            if data == b"":
                break
            file.write(data)
            downloaded += len(data)
            if Spodcast.CONFIG.get_download_real_time():
                delta_real = time.time() - time_start
                delta_want = (downloaded / size) * (duration_ms/1000)
                log.debug(f"realtime enabled, waiting for {delta_real} seconds...")
                if delta_want > delta_real:
                    time.sleep(delta_want - delta_real)

    if Spodcast.CONFIG.get_transcode():
        log.info("transcoding ogg->mp3")
        transcoder = ffmpeg.input(filepath)
        transcoder = ffmpeg.output(transcoder, mp3_filepath)
        ffmpeg.run(transcoder, quiet=True)
        file.close()
        os.unlink(filepath)
        filepath = mp3_filepath
        downloaded = os.path.getsize(filepath)
        mimetype = "audio/mpeg"

    return filepath, downloaded, mimetype


def download_episode(episode_id) -> None:
    try:
        podcast_name, podcast_id, duration_ms, episode_name, description, release_date, uri, download_url, release_date_clean = get_episode_info(episode_id)

        if podcast_name is None:
            log.warning('Skipping episode (podcast NOT FOUND)')
        elif episode_name is None:
            log.warning('Skipping episode (episode NOT FOUND)')
        else:
            filename = clean_filename(release_date_clean + ' - ' + podcast_name + ' - ' + episode_name)
            show_directory = os.path.realpath(os.path.join(Spodcast.CONFIG.get_root_path(), clean_filename(podcast_name) + '/'))
            os.makedirs(show_directory, exist_ok=True)

            if download_url is None:
                episode_stream_id = EpisodeId.from_hex(episode_id)
                stream = Spodcast.get_content_stream(episode_stream_id, Spodcast.DOWNLOAD_QUALITY)
                basename = f"{filename}.ogg"
                filepath = os.path.join(show_directory, basename)
                path, size, mimetype = download_stream(stream, filepath)
                basename = os.path.basename(path) # may have changed due to transcoding
            else:
                basename=f"{filename}.mp3"
                filepath = os.path.join(show_directory, basename)
                path, size, mimetype = download_file(download_url, filepath)

            if size == FILE_EXISTS:
                log.info(f"Skipped {podcast_name}: {episode_name}")
            else:
                log.warning(f"Downloaded {podcast_name}: {episode_name}")

                if Spodcast.CONFIG.get_rss_feed():
                    episode_info = {
                            "mimetype": mimetype,
                            "medium": "audio",
                            "duration": int(duration_ms/1000),
                            "date": time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.strptime(release_date, "%Y-%m-%dT%H:%M:%SZ")),
                            "title": escape(episode_name), "guid": uri, "description": escape(description),
                            "filename": urllib.parse.quote(basename),
                            "size": int(size) }
                    info_file = open(os.path.join(show_directory, f"{basename}.{RSS_FEED_INFO_EXTENSION}"), "w")
                    info_file.write(json.dumps(episode_info))
                    info_file.close()

            if Spodcast.CONFIG.get_rss_feed():
                show_index_file_name = os.path.join(show_directory, f"{RSS_FEED_SHOW_INDEX}.{RSS_FEED_INFO_EXTENSION}")
                if not os.path.isfile(show_index_file_name) or int(get_index_version(show_index_file_name)) < Spodcast.CONFIG.get_version_int():
                    podcast_link, podcast_description, podcast_image = get_show_info(podcast_id)
                    show_info = {}
                    if os.path.isfile(show_index_file_name):
                        with open(show_index_file_name, encoding='utf-8') as file:
                            show_info = json.load(file)
                            file.close()
                    show_info["version"] = str(RSS_FEED_VERSION + Spodcast.CONFIG.get_version_str())
                    show_info["title"] = escape(podcast_name)
                    show_info["link"] = podcast_link
                    show_info["description"] = escape(podcast_description)
                    show_info["image"] = RSS_FEED_SHOW_IMAGE 
                    show_index_file = open(show_index_file_name, "w")
                    show_index_file.write(json.dumps(show_info))
                    show_index_file.close()

                show_image_name = os.path.join(show_directory, f"{RSS_FEED_SHOW_IMAGE}")
                if not os.path.isfile(show_image_name):
                    download_file(podcast_image, show_image_name)

                rss_file_name = os.path.join(show_directory, RSS_FEED_FILE_NAME)
                if not os.path.isfile(rss_file_name) or int(get_index_version(rss_file_name)) < Spodcast.CONFIG.get_version_int():
                    rss_file = open(rss_file_name, "w")
                    rss_file.write(RSS_FEED_CODE(Spodcast.CONFIG.get_version_str()))
                    rss_file.close()

    except ApiClient.StatusCodeException as status:
        log.warning("episode %s, StatusCodeException: %s", episode_id, status)


================================================
FILE: spodcast/spodcast.py
================================================
from getpass import getpass
import glob
import hashlib
from logging import Logger
import logging
import os
import os.path
import random
import requests
import sys
import time

from librespot.audio.decoders import VorbisOnlyAudioQuality
from librespot.core import Session

from spodcast.config import Config
from spodcast.const import CREDENTIALS_PREFIX, TYPE, USER_READ_EMAIL, OFFSET, LIMIT
from spodcast.feedgenerator import RSS_FEED_FILE_NAME, RSS_INDEX_CODE, get_index_version

class Spodcast:    
    SESSION: Session = None
    DOWNLOAD_QUALITY = None
    CONFIG: Config = Config()
    LOG: Logger = None

    def __init__(self, args):
        Spodcast.CONFIG.load(args)
        logging.basicConfig(level=Spodcast.CONFIG.get_log_level())
        log = logging.getLogger(__name__)
        Spodcast.LOG = log
        log.debug("args: %s", args)
        if args.prepare_feed is True:
            root_path=Spodcast.CONFIG.get_root_path()
            os.makedirs(root_path, exist_ok=True)
            if os.path.exists(root_path):
                index_file_name = os.path.join(root_path, RSS_FEED_FILE_NAME)
                if not os.path.isfile(index_file_name) or int(get_index_version(index_file_name)) < Spodcast.CONFIG.get_version_int():
                    rss_file = open(index_file_name, "w")
                    rss_file.write(RSS_INDEX_CODE(Spodcast.CONFIG.get_bin_path(), os.path.basename(Spodcast.CONFIG.get_config_path()), Spodcast.CONFIG.get_version_str()))
                    rss_file.close()
            else:
                sys.exit(f"Can not create root path {root_path}")

        if args.login:
            filename = args.login
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8') as file:
                    for line in file.readlines():
                        Spodcast.account(line.strip())
                sys.exit(0)
            else:
                sys.exit(f"Can not read username/password file {filename}")

        Spodcast.login()

    @classmethod
    def account(cls, line):
        cred_directory = Config.get_config_dir()
        if os.path.isdir(cred_directory):
            (username,password) = line.split()
            cred_filename = CREDENTIALS_PREFIX + "-" + hashlib.md5(username.encode('utf-8'),usedforsecurity=False).hexdigest() + ".json"
            cred_location = os.path.join(cred_directory, cred_filename)
            conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).build()
            session = Session.Builder(conf).user_pass(username, password).create()
            if not session.is_valid():
                Spodcast.LOG.error("Invalid username/password for username " + username);
             
    @classmethod
    def login(cls):
        cred_directory = Config.get_config_dir()
        credfiles = glob.glob(os.path.join(cred_directory, CREDENTIALS_PREFIX) + "-*.json")
        if credfiles:
            random.shuffle(credfiles)
            for credfile in credfiles:
                try:
                    cred_location = os.path.join(cred_directory, credfile)
                    conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).set_store_credentials(False).build()
                    session = Session.Builder(conf).stored_file().create()
                    if session.is_valid():
                        cls.SESSION = session
                        return
                    else:
                        Spodcast.LOG.warning(f"Invalid credentials in {cred_location}")
                except RuntimeError:
                    Spodcast.LOG.error("RuntimeError")
                    pass
                
        cred_location = Config.get_credentials_location()

        if os.path.isfile(cred_location):
            try:
                conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).set_store_credentials(False).build()
                cls.SESSION = Session.Builder(conf).stored_file().create()
                return
            except RuntimeError:
                pass
        while True:
            user_name = ''
            while len(user_name) == 0:
                user_name = input('Username: ')
            password = getpass()
            try:
                conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).build()
                cls.SESSION = Session.Builder(conf).user_pass(user_name, password).create()
                return
            except RuntimeError:
                pass

    @classmethod
    def get_content_stream(cls, content_id, quality):
        return cls.SESSION.content_feeder().load(content_id, VorbisOnlyAudioQuality(quality), False, None)

    @classmethod
    def __get_auth_token(cls):
        return cls.SESSION.tokens().get_token(USER_READ_EMAIL).access_token

    @classmethod
    def get_auth_header(cls):
        return {
            'Authorization': f'Bearer {cls.__get_auth_token()}',
            'Accept-Language': f'{cls.CONFIG.get_language()}'
        }

    @classmethod
    def get_auth_header_and_params(cls, limit, offset):
        return {
            'Authorization': f'Bearer {cls.__get_auth_token()}',
            'Accept-Language': f'{cls.CONFIG.get_language()}'
        }, {LIMIT: limit, OFFSET: offset}

    @classmethod
    def invoke_url_with_params(cls, url, limit, offset, **kwargs):
        headers, params = cls.get_auth_header_and_params(limit=limit, offset=offset)
        params.update(kwargs)
        return requests.get(url, headers=headers, params=params).json()

    @classmethod
    def invoke_url(cls, url, tryCount=0):
        headers = cls.get_auth_header()
        Spodcast.LOG.debug(headers)
        response = requests.get(url, headers=headers)
        responsetext = response.text
        responsejson = response.json()

        if 'error' in responsejson:
            if tryCount < (cls.CONFIG.get_retry() - 1):
                Spodcast.LOG.warning(f"Spotify API Error (try {tryCount + 1}) ({responsejson['error']['status']}): {responsejson['error']['message']}")
                time.sleep(5)
                return cls.invoke_url(url, tryCount + 1)

            Spodcast.LOG.error(f"Spotify API Error ({responsejson['error']['status']}): {responsejson['error']['message']}")

        return responsetext, responsejson


================================================
FILE: spodcast/utils.py
================================================
import re
import string
import unicodedata
from enum import Enum
from typing import List, Tuple

from spodcast.spodcast import Spodcast
from spodcast.const import OPEN_SPOTIFY_URL

valid_filename_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)

def regex_input_for_urls(search_input) -> Tuple[str, str, str, str, str, str]:
    episode_uri_search = re.search(
        r'^spotify:episode:(?P<EpisodeID>[0-9a-zA-Z]{22})$', search_input)
    episode_url_search = re.search(
        r'^(https?://)?open\.spotify\.com/episode/(?P<EpisodeID>[0-9a-zA-Z]{22})(\?si=.+?)?$',
        search_input,
    )

    show_uri_search = re.search(
        r'^spotify:show:(?P<ShowID>[0-9a-zA-Z]{22})$', search_input)
    show_url_search = re.search(
        r'^(https?://)?open\.spotify\.com/show/(?P<ShowID>[0-9a-zA-Z]{22})(\?si=.+?)?$',
        search_input,
    )
    if episode_uri_search is not None or episode_url_search is not None:
        episode_id_str = (episode_uri_search
                          if episode_uri_search is not None else
                          episode_url_search).group('EpisodeID')
    else:
        episode_id_str = None

    if show_uri_search is not None or show_url_search is not None:
        show_id_str = (show_uri_search
                       if show_uri_search is not None else
                       show_url_search).group('ShowID')
    else:
        show_id_str = None

    return episode_id_str, show_id_str


def clean_filename(filename, whitelist=valid_filename_chars, replace=' '):
    for r in replace:
        filename = filename.replace(r,'_')

    cleaned_filename = unicodedata.normalize('NFKD', filename).encode('ASCII', 'ignore').decode()
    cleaned_filename = ''.join(c for c in cleaned_filename if c in whitelist)
    return cleaned_filename

def uri_to_url(spotify_id):
    (spotify,sp_type,sp_id) = spotify_id.split(':')
    return f'https://{OPEN_SPOTIFY_URL}/{sp_type}/{sp_id}'
Download .txt
gitextract_7zbxfgob/

├── .gitignore
├── LICENSE
├── README.md
├── docker/
│   ├── Dockerfile
│   ├── Dockerfile.cron
│   ├── Dockerfile.web
│   ├── cron.sh
│   ├── docker-compose.yml
│   ├── nginx/
│   │   ├── nginx.conf
│   │   └── sites-enabled/
│   │       └── spodcast
│   └── run.sh
├── install.sh
├── setup.cfg
├── setup.py
└── spodcast/
    ├── __init__.py
    ├── __main__.py
    ├── app.py
    ├── config.py
    ├── const.py
    ├── feedgenerator.py
    ├── podcast.py
    ├── spodcast.py
    └── utils.py
Download .txt
SYMBOL INDEX (47 symbols across 7 files)

FILE: spodcast/__main__.py
  function main (line 7) | def main():

FILE: spodcast/app.py
  function client (line 13) | def client(args) -> None:

FILE: spodcast/config.py
  class Config (line 73) | class Config:
    method load (line 77) | def load(cls, args) -> None:
    method get_default_json (line 127) | def get_default_json(cls) -> Any:
    method get_config_json (line 134) | def get_config_json(cls) -> Any:
    method parse_arg_value (line 141) | def parse_arg_value(cls, key: str, value: Any) -> Any:
    method get (line 157) | def get(cls, key: str) -> Any:
    method get_config_dir (line 161) | def get_config_dir(cls) -> str:
    method get_root_path (line 165) | def get_root_path(cls) -> str:
    method get_skip_existing_files (line 169) | def get_skip_existing_files(cls) -> bool:
    method get_chunk_size (line 173) | def get_chunk_size(cls) -> int:
    method get_language (line 177) | def get_language(cls) -> str:
    method get_download_real_time (line 181) | def get_download_real_time(cls) -> bool:
    method get_credentials_location (line 185) | def get_credentials_location(cls) -> str:
    method get_retry (line 190) | def get_retry(cls) -> int:
    method get_max_episodes (line 194) | def get_max_episodes(cls) -> int:
    method get_rss_feed (line 198) | def get_rss_feed(cls) -> bool:
    method get_transcode (line 202) | def get_transcode(cls) -> bool:
    method get_log_level (line 206) | def get_log_level(cls) -> str:
    method get_bin_path (line 210) | def get_bin_path(cls) -> str:
    method get_config_path (line 214) | def get_config_path(cls) -> str:
    method get_version_str (line 218) | def get_version_str(cls) -> str:
    method get_version_int (line 222) | def get_version_int(cls) -> int:

FILE: spodcast/feedgenerator.py
  function get_index_version (line 10) | def get_index_version(filename) -> str:
  function RSS_FEED_CODE (line 20) | def RSS_FEED_CODE(version):
  function RSS_INDEX_CODE (line 89) | def RSS_INDEX_CODE(bin_path, config_name, version):

FILE: spodcast/podcast.py
  function hex_to_spotify_id (line 25) | def hex_to_spotify_id(hex_id):
  function get_show_info (line 29) | def get_show_info(show_id_hex):
  function get_episode_info (line 41) | def get_episode_info(episode_id_hex):
  function get_episodes (line 60) | def get_episodes(show_id):
  function download_file (line 68) | def download_file(url, filepath):
  function download_stream (line 100) | def download_stream(stream, filepath):
  function download_episode (line 154) | def download_episode(episode_id) -> None:

FILE: spodcast/spodcast.py
  class Spodcast (line 20) | class Spodcast:
    method __init__ (line 26) | def __init__(self, args):
    method account (line 57) | def account(cls, line):
    method login (line 69) | def login(cls):
    method get_content_stream (line 110) | def get_content_stream(cls, content_id, quality):
    method __get_auth_token (line 114) | def __get_auth_token(cls):
    method get_auth_header (line 118) | def get_auth_header(cls):
    method get_auth_header_and_params (line 125) | def get_auth_header_and_params(cls, limit, offset):
    method invoke_url_with_params (line 132) | def invoke_url_with_params(cls, url, limit, offset, **kwargs):
    method invoke_url (line 138) | def invoke_url(cls, url, tryCount=0):

FILE: spodcast/utils.py
  function regex_input_for_urls (line 12) | def regex_input_for_urls(search_input) -> Tuple[str, str, str, str, str,...
  function clean_filename (line 43) | def clean_filename(filename, whitelist=valid_filename_chars, replace=' '):
  function uri_to_url (line 51) | def uri_to_url(spotify_id):
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (138K chars).
[
  {
    "path": ".gitignore",
    "chars": 371,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n\n# C extensions\n*.so\n\n# Distribution / packaging\nbin/\nbui"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 20832,
    "preview": "# _Spodcast_\n\n_Spodcast_ is a caching _Spotify_ podcast to RSS proxy. Using _Spodcast_ you can follow _Spotify_-hosted n"
  },
  {
    "path": "docker/Dockerfile",
    "chars": 557,
    "preview": "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\nVO"
  },
  {
    "path": "docker/Dockerfile.cron",
    "chars": 437,
    "preview": "FROM heywoodlh/spodcast:latest\n\nCOPY docker/cron.sh /cron.sh\n\nLABEL description=\"Spodcast is a caching Spotify podcast t"
  },
  {
    "path": "docker/Dockerfile.web",
    "chars": 296,
    "preview": "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/n"
  },
  {
    "path": "docker/cron.sh",
    "chars": 1952,
    "preview": "#!/usr/bin/env bash\n\n## Set default cron schedule\n[[ -n ${CRON_SCHEDULE} ]] || export CRON_SCHEDULE=\"0 0 * * Sun\"\n\n## Va"
  },
  {
    "path": "docker/docker-compose.yml",
    "chars": 772,
    "preview": "services:\n  spodcast-cron:\n    image: heywoodlh/spodcast-cron:latest\n    volumes:\n      - spodcast_data:/data\n    restar"
  },
  {
    "path": "docker/nginx/nginx.conf",
    "chars": 591,
    "preview": "user  nginx;\nworker_processes  auto;\n\npid        /var/run/nginx.pid;\n\nevents {\n    worker_connections  1024;\n}\n\nhttp {\n "
  },
  {
    "path": "docker/nginx/sites-enabled/spodcast",
    "chars": 468,
    "preview": "server {\n        listen 80;\n        listen [::]:80;\n\n        root /data/html;\n\t\n        index .index.php;\n\n        # the"
  },
  {
    "path": "docker/run.sh",
    "chars": 2261,
    "preview": "#!/usr/bin/env bash\n\n## If the following variables are not defined, set defaults\n[[ -n ${SPODCAST_ROOT} ]] || export SPO"
  },
  {
    "path": "install.sh",
    "chars": 18,
    "preview": "pip3 install -e .\n"
  },
  {
    "path": "setup.cfg",
    "chars": 782,
    "preview": "[metadata]\nname = spodcast\nversion = 0.5.2\ndescription = A caching Spotify podcast to RSS proxy.\nlong_description = file"
  },
  {
    "path": "setup.py",
    "chars": 69,
    "preview": "from setuptools import setup\n\nif __name__ == \"__main__\":\n    setup()\n"
  },
  {
    "path": "spodcast/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "spodcast/__main__.py",
    "chars": 1641,
    "preview": "import argparse\nimport pkg_resources\n\nfrom spodcast.app import client\nfrom spodcast.config import CONFIG_VALUES\n\ndef mai"
  },
  {
    "path": "spodcast/app.py",
    "chars": 1223,
    "preview": "import logging\n\nfrom itertools import islice\nfrom librespot.audio.decoders import AudioQuality\nfrom librespot.metadata i"
  },
  {
    "path": "spodcast/config.py",
    "chars": 8009,
    "preview": "import json\nimport os\nimport pkg_resources\nimport sys\nfrom typing import Any\n\nCONFIG_FILE_PATH = '../spodcast.json'\n\nCON"
  },
  {
    "path": "spodcast/const.py",
    "chars": 251,
    "preview": "TYPE = 'type'\nLIMIT = 'limit'\nOFFSET = 'offset'\nCREDENTIALS_PREFIX = 'spodcast-cred'\nUSER_READ_EMAIL = 'user-read-email'"
  },
  {
    "path": "spodcast/feedgenerator.py",
    "chars": 39602,
    "preview": "import re\n\nRSS_FEED_FILE_NAME = '.index.php'\nRSS_FEED_INFO_EXTENSION = 'info'\nRSS_FEED_SHOW_INDEX = 'index'\nRSS_FEED_SHO"
  },
  {
    "path": "spodcast/podcast.py",
    "chars": 9762,
    "preview": "import json\nimport logging\nimport os\nimport time\nfrom datetime import datetime\nfrom html import escape\nimport urllib.par"
  },
  {
    "path": "spodcast/spodcast.py",
    "chars": 6356,
    "preview": "from getpass import getpass\nimport glob\nimport hashlib\nfrom logging import Logger\nimport logging\nimport os\nimport os.pat"
  },
  {
    "path": "spodcast/utils.py",
    "chars": 1934,
    "preview": "import re\nimport string\nimport unicodedata\nfrom enum import Enum\nfrom typing import List, Tuple\n\nfrom spodcast.spodcast "
  }
]

About this extraction

This page contains the full source code of the Yetangitu/Spodcast GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (130.2 KB), approximately 32.5k tokens, and a symbol index with 47 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!