Full Code of digitalec/deemon for AI

main 6ab04eddbe04 cached
68 files
324.3 KB
73.8k tokens
330 symbols
1 requests
Download .txt
Showing preview only (344K chars total). Download the full file or copy to clipboard to get everything.
Repository: digitalec/deemon
Branch: main
Commit: 6ab04eddbe04
Files: 68
Total size: 324.3 KB

Directory structure:
gitextract_dh1lrv7v/

├── .github/
│   └── workflows/
│       ├── deploy-docker.yml
│       ├── discord-release-msg.yml
│       ├── purge-old-betas.yml
│       └── python-publish.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── README.md
├── deemon/
│   ├── __init__.py
│   ├── __main__.py
│   ├── assets/
│   │   └── index.html
│   ├── cli.py
│   ├── cmd/
│   │   ├── __init__.py
│   │   ├── artistconfig.py
│   │   ├── backup.py
│   │   ├── download.py
│   │   ├── extra.py
│   │   ├── generate.py
│   │   ├── monitor.py
│   │   ├── profile.py
│   │   ├── refresh.py
│   │   ├── rollback.py
│   │   ├── search.py
│   │   ├── show.py
│   │   └── upgradelib.py
│   ├── core/
│   │   ├── __init__.py
│   │   ├── api.py
│   │   ├── common.py
│   │   ├── config.py
│   │   ├── db.py
│   │   ├── dmi.py
│   │   ├── exceptions.py
│   │   ├── logger.py
│   │   └── notifier.py
│   └── utils/
│       ├── __init__.py
│       ├── dataprocessor.py
│       ├── dates.py
│       ├── performance.py
│       ├── startup.py
│       ├── ui.py
│       └── validate.py
├── docs/
│   ├── _config.yml
│   ├── _sass/
│   │   └── custom/
│   │       └── custom.scss
│   ├── docs/
│   │   ├── automations/
│   │   │   ├── automations.md
│   │   │   ├── cron.md
│   │   │   └── task-scheduler.md
│   │   ├── commands/
│   │   │   ├── backup.md
│   │   │   ├── commands.md
│   │   │   ├── config.md
│   │   │   ├── download.md
│   │   │   ├── library.md
│   │   │   ├── monitor.md
│   │   │   ├── profile.md
│   │   │   ├── refresh.md
│   │   │   ├── reset.md
│   │   │   ├── rollback.md
│   │   │   ├── search.md
│   │   │   ├── show.md
│   │   │   └── test.md
│   │   ├── configuration.md
│   │   ├── installation.md
│   │   └── troubleshooting/
│   │       ├── logs.md
│   │       ├── queue.md
│   │       └── troubleshooting.md
│   └── index.md
├── requirements.txt
└── setup.py

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

================================================
FILE: .github/workflows/deploy-docker.yml
================================================
name: Deploy Docker

on:
  release:
    types: [released]
  workflow_dispatch:

jobs:
  docker:
    if: "!github.event.release.prerelease"
    runs-on: ubuntu-latest
    steps:
      -
        name: Checkout
        uses: actions/checkout@v2
      -
        name: Set up QEMU
        uses: docker/setup-qemu-action@v1
      -
        name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1
      -
        name: Login to GHCR
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}
      -
        name: Build and push
        uses: docker/build-push-action@v2
        with:
          context: .
          platforms: linux/amd64, linux/arm64, linux/arm/v7
          push: true
          tags: ghcr.io/digitalec/deemon:latest
          labels: ${{ steps.meta.outputs.labels }}


================================================
FILE: .github/workflows/discord-release-msg.yml
================================================

name: Release messages to discord announcement channel

on: 
  release:
    types:
      - created
  workflow_dispatch:

jobs:
  run_main:
    runs-on: ubuntu-22.04
    name: Sends custom message
    steps:
      - name: Sending message
        uses: digitalec/discord-styled-releases@main
        with:
          webhook_id: ${{ secrets.DISCORD_WEBHOOK_ID }}
          webhook_token: ${{ secrets.DISCORD_WEBHOOK_TOKEN }}


================================================
FILE: .github/workflows/purge-old-betas.yml
================================================
name: Delete old beta releases
on:
  workflow_dispatch:

jobs:
  deploy:

    runs-on: ubuntu-latest

    steps:
    - uses: dev-drprasad/delete-older-releases@v0.2.0
      with:
        repo: digitalec/deemon # defaults to current repo
        keep_latest: 0
        delete_tag_pattern: b # defaults to ""
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}


================================================
FILE: .github/workflows/python-publish.yml
================================================
# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries

name: Upload Python Package

on:
  release:
    types: [created]
  workflow_dispatch:

jobs:
  deploy:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
      with:
        python-version: '3.x'
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install setuptools wheel twine packaging
    - name: Build and publish
      env:
        TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
        TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
      run: |
        python setup.py sdist bdist_wheel
        twine upload dist/*


================================================
FILE: .gitignore
================================================
__pycache__/
.idea/
build
deemon.egg-info
dist
test.txt
venv
.cache
tests.py
**/.DS_Store
artists.txt
/deemon/tests/
.vscode/settings.json
.vscode/launch.json
createenv.sh
.python-version


================================================
FILE: Dockerfile
================================================
FROM ubuntu:22.04

RUN apt-get update -y && \
apt-get install -y python3-pip

COPY ./requirements.txt /requirements.txt

WORKDIR /

RUN pip3 install -r requirements.txt && \
mkdir /config && mkdir /deemix && mkdir /downloads && mkdir /import && \
mkdir /root/.config && \
ln -s /config /root/.config/deemon && \
ln -s /deemix /root/.config/deemix

COPY deemon /app/deemon

ENV PYTHONPATH="$PYTHONPATH:/app"

VOLUME /config /downloads /import /deemix


================================================
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: MANIFEST.in
================================================
recursive-include deemon/assets *
include README.md
include LICENSE
include requirements.txt


================================================
FILE: README.md
================================================
<img src="deemon/assets/images/deemon.png" alt="deemon" width="300">

[About](#about) | [Installation](#installation) | [Docker](#docker) | [Documentation](https://digitalec.github.io/deemon) | [Support](#support)

![PyPI](https://img.shields.io/pypi/v/deemon?style=for-the-badge)
![Downloads](https://img.shields.io/pepy/dt/deemon?style=for-the-badge)
![GitHub last release](https://img.shields.io/github/release-date/digitalec/deemon?style=for-the-badge)

![GitHub last commit](https://img.shields.io/github/last-commit/digitalec/deemon?style=for-the-badge)
![Docker](https://img.shields.io/github/actions/workflow/status/digitalec/deemon/deploy-docker.yml?branch=main&style=for-the-badge&logo=docker)

![Discord](https://img.shields.io/discord/831356172464160838?style=for-the-badge&logo=discord)


### About
deemon is a command line tool written in Python that monitors artists for new releases, provides email notifications and can also integrate with the deemix library to automatically download new releases.

### Support
[Open an Issue](https://github.com/digitalec/deemon/issues/new) | [Discord](https://discord.gg/KzNCG2tkvn)

### Installation

#### Using pip

```bash
$ pip install deemon
```

#### From source
```bash
$ pip install -r requirements.txt
$ python3 -m deemon
```

#### Docker

Docker support has been added for `amd64`, `arm64` and `armv7` architectures. It is recommended to save your `docker run` command as a script to execute via cron/Task Scheduler.

**Note:** Inside deemon's `config.json`, download_location **must** be set to `/downloads` until I can integrate this myself.

**Example: Refreshing an existing database**
```
docker run --name deemon \
       --rm \
       -v /path/to/deemon/config:/config \
       -v /path/to/music:/downloads \
       -v /path/to/deemix/config:/deemix  \
       ghcr.io/digitalec/deemon:latest \
       python3 -m deemon refresh
```
#### Unraid

Install Python/PIP using either Nerd-tools Plugin (Unraid 6), Python 3 for UNRAID Plugin (Unraid 6 or 7), or manually via command line.

See the installation instructions [here](https://digitalec.github.io/deemon/docs/installation.html) or install as root (**NOT** recommended!):

```bash
pip install deemon
```
Then:
```bash
deemon --init
```

If deemon is not found in your path, you can also call it as a python module:
```bash
python3 -m deemon --init
```       
If installed using the **root** account, the config.json will be located at: **/root/.config/deemon/config.json**. Edit your configuration using the documentation located [here](https://digitalec.github.io/deemon/docs/configuration.html).

Use `deemon monitor -h` for help on adding artists, playlists, or albums to monitor for new releases.

#### Installation in a Python Virtual Environment (venv)

If you wish to install deemon and it's dependencies in a sandbox-style environment, I would recommend using venv.

Create a venv and install deemon (you may need to use `python3` and `pip3` depending on your system):
```commandline
$ python -m venv venv
$ source ./venv/bin/activate
$ pip install deemon
```

When you are finished, close the terminal or exit our venv:
```commandline
$ deactivate
```

Next time you want to run deemon, activate the venv first:
```commandline
$ source ./venv/bin/activate
$ deemon refresh
```

If you are moving to venv from the Docker container, be sure to update your cron/Task Scheduler scripts.

### Getting Started
You have to manually add artists, playlists, albums, etc.. deemon does not automatically pull artists unless they're being monitored. Refer to the documentation [here](https://digitalec.github.io/deemon/docs/commands/monitor.html).


================================================
FILE: deemon/__init__.py
================================================
#!/usr/bin/env python3
from deemon.utils import startup

__version__ = '2.22'
__dbversion__ = '3.7'

appdata = startup.get_appdata_dir()
startup.init_appdata_dir(appdata)


================================================
FILE: deemon/__main__.py
================================================
from deemon import cli


def main():
    cli.run()


if __name__ == "__main__":
    main()


================================================
FILE: deemon/assets/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="color-scheme" content="light dark">
    <title>deemon</title>
    <style>
    	@import url('https://fonts.googleapis.com/css2?family=Baloo+Tammudu+2&display=swap');
    	
    	:root {
    		--bg: #c0c0c0;
    		--text: #708090;
    		--banner-text: #404040;
    		--card-bg: #f0f0f0;
    		--date-badge-bg: #6106e5;
    		--date-badge-text: #6106e5;
    		--albuminfo-a: #70af71;
    		--album-footer: #e0e0e0;
    		--drop-shadow: #808080;
    	}
    	
    	body {
    		font-family: 'Baloo Tammudu 2', sans-serif;
    		background: var(--bg);
            margin:0;
    	}
    	
		@media (prefers-color-scheme: dark) {
			:root {
				--bg: #000000;
				--text: #ffffff;
    			--banner-text: #ffffff;
				--card-bg: #000000;
    			--date-badge-bg: #ffffff;
    			--date-badge-text: #ffffff;
    			--albuminfo-a: #70af71;
    			--album-footer: #303030;
    			--drop-shadow: #000000;
			}
		}
    	
    	a {
    		text-decoration: none;
    		color: var(--albuminfo-a);
    	}
    	
    	a:hover {
    		text-decoration: underline;
    	}
    	
    	.container {
    		position: relative;
    		font-family: sans-serif;
    		background: var(--card-bg);
    	}
    	
    	.album.container {
    		display: flex;
    		flex-wrap: wrap;
    		justify-content: left;
    		align-items: left;
    	}
    	
    	.album {
    		width:100%;
    		background: var(--card-bg);
    		box-sizing: border-box;
    		padding: 10px;
    	}
    	
    	.album.header {
    		border-top-left-radius: 17px;
    		border-top-right-radius: 17px;
    		background: var(--card-bg);
    		height: 150px;
    		display: flex;
    		justify-content: center;
    		align-items: center;
    		color: #6106e5;
    		padding-top: 35px;
    		font-family: 'Baloo Tammudu 2', sans-serif;
    		font-weight: bold;
    		font-size: 2.5em;
    	}
    	
    	.album.updates {
    		display: flex;
    		justify-content: center;
    		align-items: center;
    		background: #70af71;
    		font-family: sans-serif;
    		font-size: 1em;
    		color: #fff;
    		margin-bottom: 20px;
    	}
    	
    	.album.new-release-banner {
    		display: flex;
    		justify-content: center;
    		align-items: center;
    		font-size: 1.25em;
    		margin-bottom: -10px;
    		color: var(--banner-text);
    	}
    	
    	.album.body {
    		flex: 0 0 25%;
    		min-width: 350px;
    		color: var(--text);
    		padding: 0px;
    		padding-left: 10px;
    		font-size: 0.9em;
    		display: flex;
    		margin-bottom: 30px;
    	}
    	
    	.album.date {
    		margin-top: 40px;
    		margin-bottom: 30px;
    	}
    	
    	.album.date.badge {
    		color: var(--date-badge-text);
    		background: none;
    		border-radius: 7px;
    		border: 1px solid var(--date-badge-bg);
    		text-shadow: none;
    		font-size: 1em;
    		font-family: sans-serif;
    	}
    	
    	.album.subheader {
    		display: flex;
    		justify-content: center;
    		align-items: center;
    	}
    	
    	.footerarea {
    		display: flex;
    		justify-content: center;
    		align-items: center;
    		height: 50px;
    		color: #a0a0a0;
    	}
    	
    	.album.support {
    		font-size: 0.8em;
    		line-height: 1em;
    	}
    	
    	.album.footer {
    		border-bottom-left-radius: 7px;
    		border-bottom-right-radius: 7px;
    		font-family: monospace;
            font-size: 0.60em;
    		background: var(--album-footer);
    	}
    	
    	.albumtitle {
    		margin-top: 5px;
    		font-weight: bold;
    	}
    	
    	.artistname {
    		font-style:italic;
    		padding-bottom:10px;
    	}
    	
    	.albuminfo {
    	}
    	
    	.albuminfo a {
    		color: var(--albuminfo-a);
    	}
    	
    	.albumart {
    		float: left;
    		margin-right: 20px;
    	}
    	
    	.albumart img {
    		border-radius: 7px;
    		filter: drop-shadow(0.1rem 0.1rem 0.2rem var(--drop-shadow));
    		width: 150px;
    		height: 150px;
    	}
    </style>
  </head>
  <body>
	<div class="container">
		<div class="album header">
			deemon
		</div>
		<div class="album updates" style="{VIEW_UPDATE_MESSAGE}">
			{UPDATE_MESSAGE}
		</div>
		<div class="album new-release-banner">
			{NEW_RELEASE_COUNT} new release(s) were found!
		</div>
		<!---- START ALBUM LIST HERE ---->
		<div class="album container">
			{NEW_RELEASE_LIST}
		</div>
		<!---- END ALBUM LIST HERE ---->
		<div class="album support footerarea">
			<span style="white-space: pre-line;">
				Open an issue on <a href="https://github.com/digitalec/deemon">GitHub</a> or join us on <a href="https://discord.gg/KzNCG2tkvn">Discord</a>
			</span>
		</div>
		<div class="album footer footerarea">
			{DEEMON_VER} | {PY_VER} | {SYS_VER}
		</div>
	</div>
  </body>
</html>

================================================
FILE: deemon/cli.py
================================================
import logging
import platform
import sys
import time
from pathlib import Path

import click
from packaging.version import parse as parse_version

from deemon import __version__
from deemon.cmd import download, rollback, backup, extra, tests, upgradelib
from deemon.cmd.artistconfig import artist_lookup
from deemon.cmd.monitor import Monitor
from deemon.cmd.profile import ProfileConfig
from deemon.cmd.refresh import Refresh
from deemon.cmd.search import Search
from deemon.cmd.show import Show
from deemon.core import notifier
from deemon.core.config import Config, LoadProfile
from deemon.core.db import Database
from deemon.core.logger import setup_logger
from deemon.utils import startup, dataprocessor, validate

logger = None
config = None
db = None

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.group(context_settings=CONTEXT_SETTINGS, invoke_without_command=True,
             no_args_is_help=True)
@click.option('--whats-new', is_flag=True, help="Show release notes from this version")
@click.option('--init', is_flag=True, help="""Initialize deemon application data
              directory. Warning: if directory exists, this will delete existing config and database.""")
@click.option('--arl', help="Update ARL")
@click.option('-P', '--profile', help="Specify profile to run deemon as")
@click.version_option(__version__, '-V', '--version', message='deemon %(version)s')
@click.option('-v', '--verbose', is_flag=True, help="Show debug output")
def run(whats_new, init, arl, verbose, profile):
    """Monitoring and alerting tool for new music releases using the Deezer API.

    deemon is a free and open source tool. To report issues or to contribute,
    please visit https://github.com/digitalec/deemon
    """
    global logger
    global config
    global db

    setup_logger(log_level='DEBUG' if verbose else 'INFO', log_file=startup.get_log_file())
    logger = logging.getLogger(__name__)
    logger.debug(f"deemon {__version__}")
    logger.debug(f"command: \"{' '.join([x for x in sys.argv[1:]])}\"")
    logger.debug("Python " + platform.python_version())
    logger.debug(platform.platform())
    logger.debug(f"deemon appdata is located at {startup.get_appdata_dir()}")
    
    if whats_new:
        return startup.get_changelog(__version__)

    if init:
        app_data_path = startup.get_appdata_dir()
        startup.reinit_appdata_dir(app_data_path)

    config = Config()
    db = Database()

    db.do_upgrade()
    tid = db.get_next_transaction_id()
    config.set('tid', tid, validate=False)
    
    if arl:
        if config.set("arl", arl):
            config._Config__write_modified_config()
            reload_config = Config()
            return print(f"ARL has been successfully updated to: {reload_config.arl()}")
        else:
            return print("Error when updating ARL.")

    if profile:
        profile_config = db.get_profile(profile)
        if profile_config:
            LoadProfile(profile_config)
        else:
            logger.error(f"Profile {profile} does not exist.")
            sys.exit(1)
    else:
        profile_config = db.get_profile_by_id(1)
        if profile_config:
            LoadProfile(profile_config)

    if not any(x in sys.argv[1:] for x in ['-h', '--help']):
        last_checked: int = int(db.last_update_check())
        next_check: int = last_checked + (config.check_update() * 86400)
        if config.release_channel() != db.get_release_channel()['value']:
            # If release_channel has changed, check for latest release
            logger.debug(f"Release channel changed to '{config.release_channel()}'")
            db.set_release_channel()
            last_checked = 0
        if time.time() >= next_check or last_checked == 0:
            logger.info(f"Checking for updates ({config.release_channel()})...")
            config.set('update_available', 0, False)
            latest_ver = str(startup.get_latest_version(config.release_channel()))
            if latest_ver:
                db.set_latest_version(latest_ver)
            db.set_last_update_check()
        new_version = db.get_latest_ver()
        if parse_version(new_version) > parse_version(__version__):
            if parse_version(new_version).major > parse_version(__version__).major:
                config.set('update_available', new_version, False)
                print("*" * 80)
                logger.info(f"deemon {parse_version(new_version).major} is available. "
                            f"Please see the release notes before upgrading.")
                logger.info("Release notes available at: https://github.com/digitalec/deemon/releases")
                print("*" * 80)
            else:
                config.set('update_available', new_version, False)
                print("*" * 50)
                logger.info(f"* New version is available: v{__version__} -> v{new_version}")
                if config.release_channel() == "beta":
                    logger.info("* To upgrade, run `pip install --upgrade --pre deemon`")
                else:
                    logger.info("* To upgrade, run `pip install --upgrade deemon`")
                print("*" * 50)
                print("")

    config.set("start_time", int(time.time()), False)


@run.command(name='test')
@click.option('-e', '--email', is_flag=True, help="Send test notification to configured email")
@click.option('-E', '--exclusions', metavar="URL", type=str, help="Test exclude regex pattern against URL")
def test(email, exclusions):
    """Run tests on email configuration, exclusion filters, etc."""
    if email:
        notification = notifier.Notify()
        notification.test()
    elif exclusions:
        if config.exclusion_patterns() or config.exclusion_keywords:
            tests.exclusion_test(exclusions)
        else:
            logger.info("You don't have any exclusions configured or they're disabled")

@run.command(name='download', no_args_is_help=True)
@click.argument('artist', nargs=-1, required=False)
@click.option('-m', '--monitored', is_flag=True, help='Download all currently monitored artists')
@click.option('-i', '--artist-id', multiple=True, metavar='ID', type=int, help='Download by artist ID')
@click.option('-A', '--album-id', multiple=True, metavar='ID', type=int, help='Download by album ID')
@click.option('-T', '--track-id', multiple=True, metavar='ID', type=int, help='Download by track ID')
@click.option('-u', '--url', metavar='URL', multiple=True, help='Download by URL of artist/album/track/playlist')
@click.option('-f', '--file', metavar='FILE', help='Download batch of artists or artist IDs from file', hidden=True)
@click.option('--artist-file', metavar='FILE', help='Download batch of artists or artist IDs from file')
@click.option('--album-file', metavar='FILE', help='Download batch of album IDs from file')
@click.option('--track-file', metavar='FILE', help='Download batch of track IDs from file')
@click.option('-a', '--after', 'from_date', metavar="YYYY-MM-DD", type=str, help='Grab releases released after this date')
@click.option('-B', '--before', 'to_date', metavar="YYYY-MM-DD", type=str, help='Grab releases released before this date')
@click.option('-b', '--bitrate', metavar="BITRATE", help='Set custom bitrate for this operation')
@click.option('-o', '--download-path', metavar="PATH", type=str, help='Specify custom download directory')
@click.option('-t', '--record-type', metavar="TYPE", type=str, help='Specify record types to download')
def download_command(artist, artist_id, album_id, url, file, bitrate,
                     record_type, download_path, from_date, to_date,
                     monitored, track_id, track_file, artist_file,
                     album_file):
    """
    Download specific artist, album ID or by URL

    \b
    Examples:
        download Mozart
        download -i 100 -t album -b 9
    """

    if bitrate:
        config.set('bitrate', bitrate)
    if download_path:
        config.set('download_path', download_path)
    if record_type:
        config.set('record_type', record_type)

    artists = dataprocessor.csv_to_list(artist) if artist else None
    artist_ids = [x for x in artist_id] if artist_id else None
    album_ids = [x for x in album_id] if album_id else None
    track_ids = [x for x in track_id] if track_id else None
    urls = [x for x in url] if url else None

    if file:
        logger.info("WARNING: -f/--file has been replaced with --artist-file and will be removed in future versions.")
        artist_file = file

    if download_path and download_path != "":
        if Path(download_path).exists:
            config.set('download_path', download_path)
            logger.debug(f"Download path has changed: {config.download_path()}")
        else:
            return logger.error(f"Invalid download path: {download_path}")

    dl = download.Download()
    dl.set_dates(from_date, to_date)
    dl.download(artists, artist_ids, album_ids, urls, artist_file, track_file, album_file, track_ids, monitored=monitored)


@run.command(name='monitor', context_settings={"ignore_unknown_options": False}, no_args_is_help=True)
@click.argument('artist', nargs=-1)
@click.option('-a', '--alerts', is_flag=True, help="Enable or disable alerts")
@click.option('-b', '--bitrate', metavar="BITRATE", help="Specify bitrate")
@click.option('-D', '--download', 'dl', is_flag=True, help='Download all releases matching record type')
@click.option('-d', '--download-path', type=str, metavar="PATH", help='Specify custom download directory')
@click.option('-I', '--import', 'im', metavar="PATH", help="Monitor artists/IDs from file or directory")
@click.option('-i', '--artist-id', is_flag=True, help="Monitor artist by ID")
@click.option('-p', '--playlist', is_flag=True, help='Monitor Deezer playlist by URL')
@click.option('--include-artists', is_flag=True, help='Also monitor artists from playlist')
@click.option('-u', '--url', is_flag=True, help='Monitor artist by URL')
@click.option('-R', '--remove', is_flag=True, help='Stop monitoring an artist')
@click.option('-s', '--search', 'search_flag', is_flag=True, help='Show similar artist results to choose from')
@click.option('-T', '--time-machine', type=str, metavar="YYYY-MM-DD", help="Refresh newly added artists on this date")
@click.option('-t', '--record-type', metavar="TYPE", type=str, help='Specify record types to download')
def monitor_command(artist, im, playlist, include_artists, bitrate, record_type, alerts, artist_id,
                    dl, remove, url, download_path, search_flag, time_machine):
    """
    Monitor artist for new releases by ID, URL or name.

    \b
    Examples:
        monitor Mozart
        monitor --artist-id 100
        monitor --url https://www.deezer.com/us/artist/000
    """
    monitor = Monitor()
    if download_path:
        if not Path(download_path).exists():
            return logger.error("Invalid download path provided")

    if time_machine:
        validated = validate.validate_date(time_machine)
        if validated:
            monitor.time_machine = validated
        else:
            return logger.error("Date for time machine is invalid")
    
    if not alerts:
        alerts = None

    monitor.set_options(remove, dl, search_flag)
    monitor.set_config(bitrate, alerts, record_type, download_path)

    if url:
        artist_id = True
        urls = [x.replace(",", "") for x in artist]
        artist = []
        for u in urls:
            id_from_url = u.split('/artist/')
            try:
                aid = int(id_from_url[1])
            except (IndexError, ValueError):
                logger.error(f"Invalid artist URL -- {u}")
                return
            artist.append(aid)

    if playlist:
        urls = [x.replace(",", "") for x in artist]
        playlist_id = []
        for u in urls:
            id_from_url = u.split('/playlist/')
            try:
                aid = int(id_from_url[1])
            except (IndexError, ValueError):
                logger.error(f"Invalid playlist URL -- {u}")
                return
            playlist_id.append(aid)

    if im:
        monitor.importer(im)
    elif playlist:
        monitor.playlists(playlist_id, include_artists)
    elif artist_id:
        monitor.artist_ids(dataprocessor.csv_to_list(artist))
    elif artist:
        monitor.artists(dataprocessor.csv_to_list(artist))


@run.command(name='refresh')
@click.argument('NAME', nargs=-1, type=str, required=False)
@click.option('-p', '--playlist', is_flag=True, help="Refresh a specific playlist by name")
@click.option('-s', '--skip-download', is_flag=True, help="Skips downloading of new releases")
@click.option('-T', '--time-machine', metavar='DATE', type=str, help='Refresh as if it were this date (YYYY-MM-DD)')
def refresh_command(name, playlist, skip_download, time_machine):
    """Check artists for new releases"""

    if time_machine:
        time_machine = validate.validate_date(time_machine)
        if not time_machine:
            return logger.error("Date for time machine is invalid")

    logger.info(":: Starting database refresh")
    refresh = Refresh(time_machine, skip_download)
    if playlist:
        if not len(name):
            return logger.warning("You must provide the name of a playlist")
        refresh.run(playlists=dataprocessor.csv_to_list(name))
    elif name:
        refresh.run(artists=dataprocessor.csv_to_list(name))
    else:
        refresh.run()


@click.group(name="show")
def show_command():
    """
    Show monitored artists and latest releases
    """


@show_command.command(name="artists")
@click.argument('artist', nargs=-1, required=False)
@click.option('-c', '--csv', is_flag=True, help='Output artists as CSV')
@click.option('-e', '--export', type=Path, help='Export CSV data to file; same as -ce')
@click.option('-f', '--filter', type=str, help='Specify filter for CSV output')
@click.option('-H', '--hide-header', is_flag=True, help='Hide header on CSV output')
@click.option('-b', '--backup', type=Path, help='Backup artist IDs to CSV, same as -cHf id -e ...')
def show_artists(artist, csv, export, filter, hide_header, backup):
    """Show artist info monitored by profile"""
    if artist:
        artist = ' '.join([x for x in artist])

    show = Show()
    show.monitoring(artist=True, query=artist, export_csv=csv, save_path=export, filter=filter, hide_header=hide_header,
                    backup=backup)


@show_command.command(name="playlists")
@click.argument('title', nargs=-1, required=False)
@click.option('-c', '--csv', is_flag=True, help='Output artists as CSV')
@click.option('-f', '--filter', type=str, help='Specify filter for CSV output')
@click.option('-H', '--hide-header', is_flag=True, help='Hide header on CSV output')
@click.option('-i', '--playlist-id', is_flag=True, help='Show playlist info by playlist ID')
def show_artists(title, playlist_id, csv, filter, hide_header):
    """Show playlist info monitored by profile"""
    if title:
        title = ' '.join([x for x in title])

    show = Show()
    show.monitoring(artist=False, query=title, export_csv=csv, filter=filter, hide_header=hide_header, is_id=playlist_id)


@show_command.command(name="releases")
@click.argument('N', default=7)
@click.option('-f', '--future', is_flag=True, help='Display future releases')
def show_releases(n, future):
    """
    Show list of new or future releases
    """
    show = Show()
    show.releases(n, future)


run.add_command(show_command)


@run.command(name="backup")
@click.option('-i', '--include-logs', is_flag=True, help='include log files in backup')
@click.option('-r', '--restore', is_flag=True, help='Restore from existing backup')
def backup_command(restore, include_logs):
    """Backup configuration and database to a tar file"""

    if restore:
        backup.restore()
    else:
        backup.run(include_logs)


# TODO @click.option does not support nargs=-1; unable to use spaces without quotations
@run.command(name="api", help="View raw API data for artist, artist ID or playlist ID", hidden=True)
@click.option('-A', '--album-id', type=int, help='Get album ID result via API')
@click.option('-a', '--artist', type=str, help='Get artist result via API')
@click.option('-i', '--artist-id', type=int, help='Get artist ID result via API')
@click.option('-l', '--limit', type=int, help='Set max number of artist results; default=1', default=1)
@click.option('-p', '--playlist-id', type=int, help='Get playlist ID result via API')
@click.option('-r', '--raw', is_flag=True, help='Dump as raw data returned from API')
def api_test(artist, artist_id, album_id, playlist_id, limit, raw):
    """View API result - for testing purposes"""
    import deezer
    dz = deezer.Deezer()
    if artist or artist_id:
        if artist:
            result = dz.api.search_artist(artist, limit=limit)['data']
        else:
            result = dz.api.get_artist(artist_id)

        if raw:
            if isinstance(result, list):
                for row in result:
                    for key, value in row.items():
                        print(f"{key}: {value}")
                    print("\n")
            else:
                for key, value in result.items():
                    print(f"{key}: {value}")
        else:
            if isinstance(result, list):
                for row in result:
                    print(f"Artist ID: {row['id']}\nArtist Name: {row['name']}\n")
            else:
                print(f"Artist ID: {result['id']}\nArtist Name: {result['name']}")

    if album_id:
        result = dz.api.get_album(album_id)

        if raw:
            for key, value in result.items():
                print(f"{key}: {value}")
        else:
            print(f"Album ID: {result['id']}\nAlbum Title: {result['title']}")

    if playlist_id:
        result = dz.api.get_playlist(playlist_id)

        if raw:
            for key, value in result.items():
                print(f"{key}: {value}")
        else:
            print(f"Playlist ID: {result['id']}\nPlaylist Title: {result['title']}")


@run.command(name="reset")
def reset_db():
    """Reset monitoring database"""
    logger.warning("** WARNING: All artists and playlists will be removed regardless of profile! **")
    confirm = input(":: Type 'reset' to confirm: ")
    if confirm.lower() == "reset":
        print("")
        db.reset_database()
    else:
        logger.info("Reset aborted. Database has NOT been modified.")
    return


@run.command(name='profile')
@click.argument('profile', required=False)
@click.option('-a', '--add', is_flag=True, help="Add new profile")
@click.option('-c', '--clear', is_flag=True, help="Clear config for existing profile")
@click.option('-d', '--delete', is_flag=True, help="Delete an existing profile")
@click.option('-e', '--edit', is_flag=True, help="Edit an existing profile")
def profile_command(profile, add, clear, delete, edit):
    """Add, modify and delete configuration profiles"""

    pc = ProfileConfig(profile)
    if profile:
        if add:
            pc.add()
        elif clear:
            pc.clear()
        elif delete:
            pc.delete()
        elif edit:
            pc.edit()
        else:
            pc.show()
    else:
        pc.show()


@run.command(name="extra")
def extra_command():
    """Fetch extra release info"""
    extra.main()


@run.command(name="search")
@click.argument('query', nargs=-1, required=False)
def search(query):
    """Interactively search and download/monitor artists"""
    if query:
        query = ' '.join(query)

    client = Search()
    client.search_menu(query)


@run.command(name="config")
@click.argument('artist', nargs=-1, required=True)
def config_command(artist):
    """Configure per-artist settings by name or ID"""
    artist = ' '.join([x for x in artist])
    artist_lookup(artist)


@run.command(name="rollback", no_args_is_help=True)
@click.argument('num', type=int, required=False)
@click.option('-v', '--view', is_flag=True, help="View recent refresh transactions")
def rollback_command(num, view):
    """Rollback a previous monitor or refresh transaction"""
    if view:
        rollback.view_transactions()
    elif num:
        rollback.rollback_last(num)


@click.group(name="library")
def library_command():
    """
    Library options such as upgrading from MP3 to FLAC
    """


@library_command.command(name="upgrade")
@click.argument('library', metavar='PATH')
@click.option('-A', '--album-only', is_flag=True, help="Get album IDs instead of track IDs (Fastest)")
@click.option('-E', '--allow-exclusions', is_flag=True, help="Allow exclusions to be applied")
@click.option('-O', '--output', metavar='PATH', help="Output file to save IDs (default: current directory)")
def library_upgrade_command(library, output, album_only, allow_exclusions):
    """ (BETA) Scans MP3 files in PATH and generates a text file containing album/track IDs """
    if not output:
        output = Path.cwd()
    upgradelib.upgrade(library, output, album_only, allow_exclusions)


run.add_command(library_command)


================================================
FILE: deemon/cmd/__init__.py
================================================


================================================
FILE: deemon/cmd/artistconfig.py
================================================
import logging

from deemon.core.config import Config as config
from deemon.core.db import Database

logger = logging.getLogger(__name__)
db = Database()


def print_header(message: str = None):
    from os import system, name
    if name == 'nt':
        _ = system('cls')
    else:
        _ = system('clear')
    print("deemon Artist Configurator")
    if message:
        print(":: " + message + "\n")
    else:
        print("")


def get_artist(query: str):
    artist_as_id = False
    artist_fromdb = None

    try:
        artist_as_id = int(query)
    except ValueError:
        pass

    by_name = db.get_monitored_artist_by_name(query)
    if by_name:
        logger.debug("Artist found by name")
        artist_fromdb = by_name

    if artist_as_id:
        by_id = db.get_monitored_artist_by_id(artist_as_id)
        if by_id:
            logger.debug(f"Artist found by ID")
            if not artist_fromdb:
                artist_fromdb = by_id
            else:
                logger.debug("Artist found by both ID and name, prompting user")

                while True:
                    prompt = input(":: Multiple artists found. Was that a name or ID? ")
                    if prompt.lower() == "name":
                        logger.debug("Artist confirmed by user to be a name")
                        return artist_fromdb
                    elif prompt.lower() == "id":
                        logger.debug("Artist confirmed by user to be an ID")
                        return by_id
        else:
            return logger.error(f"Artist/Artist ID not found for '{query}'")

    if artist_fromdb:
        return artist_fromdb
    else:
        return logger.error(f"Artist/Artist ID not found for '{query}'")


def artist_lookup(query):
    result = get_artist(query)
    if not result:
        return
    print_header(f"Configuring '{result['artist_name']}' (Artist ID: {result['artist_id']})")
    modified = 0
    for property in result:
        if property not in ['alerts', 'bitrate', 'record_type', 'download_path']:
            continue
        allowed_opts = config.allowed_values(property)
        if isinstance(allowed_opts, dict):
            allowed_opts = [str(x.lower()) for x in allowed_opts.values()]

        while True:
            friendly_text = property.replace("_", " ").title()
            user_input = input(f"{friendly_text} [{result[property]}]: ")

            if property != "download_path":
                user_input = user_input.lower()

            if user_input == "":
                break
            elif user_input == "false" or user_input == "0":
                user_input = False
            elif user_input == "true" or user_input == "1":
                user_input = True
            if user_input == "none":
                user_input = None
            elif allowed_opts:
                if user_input not in allowed_opts:
                    print(f"Allowed options: " + ', '.join(str(x) for x in allowed_opts))
                    continue
            logger.debug(f"User set {property} to {user_input}")
            result[property] = user_input
            modified += 1
            break
    if modified > 0:
        i = input("\n:: Save these settings? [y|N] ")
        if i.lower() != "y":
            logger.info("No changes made, exiting...")
        else:
            db.update_artist(result)
            print(f"\nArtist '{result['artist_name']}' has been updated!")
    else:
        print("No changes made, exiting...")


================================================
FILE: deemon/cmd/backup.py
================================================
import logging
import os
import tarfile
from datetime import datetime
from pathlib import Path

from packaging.version import parse as parse_version
from tqdm import tqdm

from deemon import __version__
from deemon.utils import startup, dates

logger = logging.getLogger(__name__)


def run(include_logs: bool = False):
    def filter_func(item):
        includes = ['deemon', 'deemon/config.json', 'deemon/deemon.db']
        if include_logs:
            if 'deemon/logs' in item.name:
                includes.append(item.name)
        if item.name in includes:
            return item

    backup_tar = dates.generate_date_filename("backup-" + __version__ + "-") + ".tar"
    backup_path = startup.get_backup_dir()

    with tarfile.open(backup_path / backup_tar, "w") as tar:
        tar.add(startup.get_appdata_dir(), arcname='deemon', filter=filter_func)
        logger.info(f"Backed up to {backup_path / backup_tar}")


def restore():
    restore_file_list = ['deemon/config.json', 'deemon/deemon.db']

    def inspect_tar(fn: Path) -> dict:
        fn_name = fn.name
        fn_name = fn_name.replace('.tar', '').split('-')
        if fn_name[0] == "backup" and len(fn_name) > 3:
            if check_tar_contents(fn):
                backup_appversion = '-'.join(fn_name[1:-2])
                if is_newer_backup(backup_appversion):
                    logger.debug(f"Backup found for newer version {backup_appversion} is not compatible!")
                    return
                backup_time = datetime.strptime(fn_name[-1], "%H%M%S")
                backup_date = datetime.strptime(fn_name[-2], "%Y%m%d")
                try:
                    friendly_time = datetime.strftime(backup_time, "%-I:%M:%S %p")
                except ValueError:
                    # Gotta keep Windows happy...
                    friendly_time = datetime.strftime(backup_time, "%#I:%M:%S %p")
                try:
                    friendly_date = datetime.strftime(backup_date, "%b %-d, %Y")
                except ValueError:
                    # Gotta keep Windows happy...
                    friendly_date = datetime.strftime(backup_date, "%b %#d, %Y")
                backup_info = {
                    'version': backup_appversion,
                    'date': friendly_date,
                    'time': friendly_time,
                    'age': fn_name[-2] + fn_name[-1],
                    'filename': fn
                }
                return backup_info
        else:
            return

    def check_tar_contents(archive: Path):
        tar = tarfile.open(archive)
        file_list = tar.getmembers()
        files = [x.name for x in file_list]
        if all(item in files for item in restore_file_list):
            return True
        logger.debug("Archive is invalid or corrupt: " + str(archive))

    def restore_tarfile(archive: dict):
        logger.debug("Restoring backup from `" + str(archive['filename'].name + "`"))
        extract_dir = startup.get_appdata_dir()
        tar = tarfile.open(archive['filename'])
        progress = tqdm(tar.getmembers(), ascii=" #",
                        bar_format='{desc}  [{bar}] {percentage:3.0f}%')
        for member in progress:
            if member.isreg():
                if member.name in restore_file_list:
                    member.name = os.path.basename(member.name)
                    logger.info(f"Restoring {member.name}...")
                    progress.set_description_str(f"Restoring {member.name}")
                    tar.extract(member, extract_dir)
                    logger.debug(f"Restored {member.name} to {extract_dir}")
            if member == tar.getmembers()[-1]:
                progress.set_description_str("Restore complete")

    def is_newer_backup(version: str):
        if parse_version(version) > parse_version(__version__):
            return True

    def display_backup_list(available_backups: list):
        print("deemon Backup Manager\n")
        for index, backup in enumerate(available_backups, start=1):
            print(f"{index}. {backup['date']} @ {backup['time']} (ver {backup['version']})")

        selected_backup = int
        while selected_backup not in range(len(available_backups)):
            selected_backup = input("\nSelect a backup to restore (or press Enter to exit): ")
            if selected_backup == "":
                return
            try:
                selected_backup = int(selected_backup)
                selected_backup -= 1
            except ValueError:
                logger.warning("Invalid entry. Enter a number corresponding to the backup you wish to restore.")
        print("")
        restore_tarfile(available_backups[selected_backup])

    backups = []
    backup_path = startup.get_backup_dir()
    file_list = [x for x in sorted(Path(backup_path).glob('*.tar'))]
    for backup in file_list:
        tar_files = inspect_tar(backup)
        if tar_files:
            backups.append(tar_files)
    if backups:
        backups = sorted(backups, key=lambda x: x['age'], reverse=True)
        display_backup_list(backups)
    else:
        logger.info("No backups available to restore")


================================================
FILE: deemon/cmd/download.py
================================================
import logging
import os
import sys

import requests
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tqdm import tqdm

import deemix.errors
import deezer
from deezer import errors
import plexapi.exceptions
from plexapi.server import PlexServer

from deemon import utils
from deemon.core import dmi, db, api, common
from deemon.core.config import Config as config
from deemon.utils import ui, dataprocessor, startup, dates

logger = logging.getLogger(__name__)


class QueueItem:
    # TODO - Accept new playlist tracks for output/alerts
    def __init__(self, artist=None, album=None, track=None, playlist=None,
                 bitrate: str = None, download_path: str = None,
                 release_full: dict = None):
        self.artist_name = None
        self.album_id = None
        self.album_title = None
        self.track_id = None
        self.track_title = None
        self.url = None
        self.playlist_title = None
        self.bitrate = bitrate or config.bitrate()
        self.download_path = download_path or config.download_path()
        self.release_type = None
        
        if release_full:
            self.artist_name = release_full['artist_name']
            self.album_id = release_full['id']
            self.album_title = release_full['title']
            self.url = f"https://www.deezer.com/album/{self.album_id}"
            self.release_type = release_full['record_type']
            self.bitrate = release_full['bitrate']
            self.download_path = release_full['download_path']

        if artist:
            try:
                self.artist_name = artist["artist_name"]
            except KeyError:
                self.artist_name = artist["name"]
            if not album and not track:
                self.url = artist["link"]

        if album:
            if not artist:
                self.artist_name = album["artist"]["name"]
            self.album_id = album["id"]
            self.album_title = album["title"]
            try:
                self.url = album["link"]
            except KeyError:
                self.url = f"https://www.deezer.com/album/{album['id']}"

        if track:
            self.artist_name = track["artist"]["name"]
            self.track_id = track["id"]
            self.track_title = track["title"]
            self.url = f"https://deezer.com/track/{self.track_id}"

        if playlist:
            try:
                self.url = playlist["link"]
            except KeyError:
                logger.debug("DEPRECATED dict key: playlist['url'] should not be used in favor of playlist['link']")
                self.url = playlist.get("url", None)
            self.playlist_title = playlist["title"]


def get_deemix_bitrate(bitrate: str):
    for bitrate_id, bitrate_name in config.allowed_values('bitrate').items():
        if bitrate_name.lower() == bitrate.lower():
            logger.debug(f"Setting deemix bitrate to {str(bitrate_id)}")
            return bitrate_id


def get_plex_server():
    if (config.plex_baseurl() != "") and (config.plex_token() != ""):
        session = None
        if not config.plex_ssl_verify():
            requests.packages.urllib3.disable_warnings()
            session = requests.Session()
            session.verify = False
        try:
            print("Plex settings found, trying to connect (10s)... ", end="")
            plex_server = PlexServer(config.plex_baseurl(), config.plex_token(), timeout=10, session=session)
            print(" OK")
            return plex_server
        except Exception as e:
            print(" FAILED")
            logger.error("Error: Unable to reach Plex server, please refresh manually.")
            logger.debug(e)
            return False


def refresh_plex(plexobj):
    try:
        plexobj.library.section(config.plex_library()).update()
        logger.debug("Plex library refreshed successfully")
    except plexapi.exceptions.BadRequest as e:
        logger.error("Error occurred while refreshing your library. See logs for additional info.")
        logger.debug(f"Error during Plex refresh: {e}")
    except plexapi.exceptions.NotFound as e:
        logger.error("Error: Plex library not found. See logs for additional info.")
        logger.debug(f"Error during Plex refresh: {e}")


class Download:

    def __init__(self, active_api=None):
        super().__init__()
        self.api = active_api or api.PlatformAPI()
        self.dz = deezer.Deezer()
        self.di = dmi.DeemixInterface()
        self.queue_list = []
        self.db = db.Database()
        self.bitrate = None
        self.release_from = None
        self.release_to = None
        self.verbose = os.environ.get("VERBOSE")
        self.duplicate_id_count = 0

    def set_dates(self, from_date: str = None, to_date: str = None) -> None:
        """Set to/from dates to get while downloading"""
        if from_date:
            try:
                self.release_from = dates.str_to_datetime_obj(from_date)
            except ValueError as e:
                raise ValueError(f"Invalid date provided - {from_date}: {e}")
        if to_date:
            try:
                self.release_to = dates.str_to_datetime_obj(to_date)
            except ValueError as e:
                raise ValueError(f"Invalid date provided - {to_date}: {e}")

    # @performance.timeit
    def download_queue(self, queue_list: list = None):
        if queue_list:
            self.queue_list = queue_list

        if not self.di.login():
            logger.error("Failed to login, aborting download...")
            return False

        if self.queue_list:
            plex = get_plex_server()
            print("")
            logger.info(":: Sending " + str(len(self.queue_list)) + " release(s) to deemix for download:")

            with open(startup.get_appdata_dir() / "queue.csv", "w", encoding="utf-8") as f:
                f.writelines(','.join([str(x) for x in vars(self.queue_list[0]).keys()]) + "\n")
                logger.debug(f"Writing queue to CSV file - {len(self.queue_list)} items in queue")
                for q in self.queue_list:
                    raw_values = [str(x) for x in vars(q).values()]
                    # TODO move this to shared function
                    for i, v in enumerate(raw_values):
                        if '"' in v:
                            raw_values[i] = v.replace('"', "'")
                        if ',' in v:
                            raw_values[i] = f'"{v}"'
                    f.writelines(','.join(raw_values) + "\n")
            logger.debug(f"Queue exported to {startup.get_appdata_dir()}/queue.csv")

            failed_count = []
            download_progress = tqdm(
                self.queue_list,
                total=len(self.queue_list),
                desc="Downloading releases...",
                ascii=" #",
                bar_format=ui.TQDM_FORMAT
            )
            for index, item in enumerate(download_progress):
                i = str(index + 1)
                t = str(len(download_progress))
                download_progress.set_description_str(f"Downloading release {i} of {t}...")
                dx_bitrate = get_deemix_bitrate(item.bitrate)
                if self.verbose == "true":
                    logger.debug(f"Processing queue item {vars(item)}")
                try:
                    if item.download_path:
                        download_path = item.download_path
                    else:
                        download_path = None

                    if item.artist_name:
                        if item.album_title:
                            logger.info(f"   > {item.artist_name} - {item.album_title}... ")
                            self.di.download_url([item.url], dx_bitrate, download_path)
                        else:
                            logger.info(f"   > {item.artist_name} - {item.track_title}... ")
                            self.di.download_url([item.url], dx_bitrate, download_path)
                    else:
                        logger.info(f"   > {item.playlist_title} (playlist)...")
                        self.di.download_url([item.url], dx_bitrate, download_path, override_deemix=True)
                except (deemix.errors.GenerationError, errors.WrongGeolocation) as e:
                    logger.debug(e)
                    failed_count.append([(item, "No tracks listed or unavailable in your country")])
                except Exception as e:
                    if item.artist_name and item.album_title:
                        logger.info(f"The following error occured while downloading {item.artist_name} - {item.album_title}: {e}")
                    elif item.artist_name and item.track_title:
                        logger.info(f"The following error occured while downloading {item.artist_name} - {item.track_title}: {e}")
                    else:
                        logger.info(f"The following error occured while downloading {item.playlist_title}: {e}")
                    pass


            failed_count = [x for x in failed_count if x]

            print("")
            if len(failed_count):
                logger.info(f"   [!] Downloads completed with {len(failed_count)} error(s):")
                with open(startup.get_appdata_dir() / "failed.csv", "w", encoding="utf-8") as f:
                    f.writelines(','.join([str(x) for x in vars(self.queue_list[0]).keys()]) + "\n")
                    for failed in failed_count:
                        try:
                            raw_values = [str(x) for x in vars(failed[0]).values()]
                        except TypeError as e:
                            print(f"Error reading from failed.csv. Entry that failed was either invalid or empty: {failed}")
                            logger.error(e)
                        else:
                            # TODO move this to shared function
                            for i, v in enumerate(raw_values):
                                if '"' in v:
                                    raw_values[i] = v.replace('"', "'")
                                if ',' in v:
                                    raw_values[i] = f'"{v}"'
                            f.writelines(','.join(raw_values) + "\n")
                            print(f"+ {failed[0].artist_name} - {failed[0].album_title} --- Reason: {failed[1]}")
                print("")
                logger.info(f":: Failed downloads exported to: {startup.get_appdata_dir()}/failed.csv")
            else:
                logger.info("   Downloads complete!")
            if plex and (config.plex_library() != ""):
                refresh_plex(plex)
        return True

    def download(self, artist, artist_id, album_id, url,
                 artist_file, track_file, album_file, track_id, auto=True, monitored=False):

        def filter_artist_by_record_type(artist):
            album_api = self.api.get_artist_albums(query={'artist_name': '', 'artist_id': artist['id']})
            filtered_albums = []
            for album in album_api['releases']:
                if (album['record_type'] == config.record_type()) or config.record_type() == "all":
                    album_date = dates.str_to_datetime_obj(album['release_date'])
                    if self.release_from and self.release_to:
                        if album_date > self.release_from and album_date < self.release_to:
                            filtered_albums.append(album)
                    elif self.release_from:
                        if album_date > self.release_from:
                            filtered_albums.append(album)
                    elif self.release_to:
                        if album_date < self.release_to:
                            filtered_albums.append(album)
                    else:
                        filtered_albums.append(album)
            return filtered_albums

        def get_api_result(artist=None, artist_id=None, album_id=None, track_id=None):
            if artist:
                try:
                    return self.api.search_artist(artist, limit=1)['results'][0]
                except (deezer.api.DataException, IndexError):
                    logger.error(f"Artist {artist} not found.")
            if artist_id:
                try:
                    return self.api.get_artist_by_id(artist_id)
                except (deezer.api.DataException, IndexError):
                    logger.error(f"Artist ID {artist_id} not found.")
            if album_id:
                try:
                    return self.api.get_album(album_id)
                except (deezer.api.DataException, IndexError):
                    logger.error(f"Album ID {album_id} not found.")
            if track_id:
                try:
                    return self.api.get_track(track_id)
                except (deezer.api.DataException, IndexError):
                    logger.error(f"Track ID {track_id} not found.")

        def queue_filtered_releases(api_object):
            filtered = filter_artist_by_record_type(api_object)
            filtered = common.exclude_filtered_versions(filtered)

            for album in filtered:
                if not queue_item_exists(album['id']):
                    self.queue_list.append(QueueItem(artist=api_object, album=album))

        def queue_item_exists(i):
            for q in self.queue_list:
                if q.album_id == i:
                    logger.debug(f"Album ID {i} is already in queue")
                    self.duplicate_id_count += 1
                    return True
            return False

        def process_artist_by_name(name):
            artist_result = get_api_result(artist=name)
            if not artist_result:
                return
            logger.debug(f"Requested Artist: '{name}', Found: '{artist_result['name']}'")
            if artist_result:
                queue_filtered_releases(artist_result)

        def process_artist_by_id(i):
            artist_id_result = get_api_result(artist_id=i)
            if not artist_id_result:
                return
            logger.debug(f"Requested Artist ID: {i}, Found: {artist_id_result['name']}")
            if artist_id_result:
                queue_filtered_releases(artist_id_result)

        def process_album_by_id(i):
            logger.debug("Processing album by ID")
            album_id_result = get_api_result(album_id=i)
            if not album_id_result:
                logger.debug(f"Album ID {i} was not found")
                return
            logger.debug(f"Requested album: {i}, "
                         f"Found: {album_id_result['artist']['name']} - {album_id_result['title']}")
            if album_id_result and not queue_item_exists(album_id_result['id']):
                self.queue_list.append(QueueItem(album=album_id_result))

        def process_track_by_id(id):
            logger.debug("Processing track by ID")
            track_id_result = get_api_result(track_id=id)
            if not track_id_result:
                return
            logger.debug(f"Requested track: {id}, "
                         f"Found: {track_id_result['artist']['name']} - {track_id_result['title']}")
            if track_id_result and not queue_item_exists(id):
                self.queue_list.append(QueueItem(track=track_id_result))

        def process_track_file(id):
            if not queue_item_exists(id):
                track_data = {
                    "artist": {
                        "name": "TRACK ID"
                    },
                    "id": id,
                    "title": id
                }
                self.queue_list.append(QueueItem(track=track_data))

        def process_playlist_by_id(id):
            playlist_api = self.api.get_playlist(id)
            self.queue_list.append(QueueItem(playlist=playlist_api))

        def extract_id_from_url(url):
            id_group = ['artist', 'album', 'track', 'playlist']
            for group in id_group:
                id_type = group
                try:
                    # Strip ID from URL
                    id_from_url = url.split(f'/{group}/')[1]

                    # Support for share links: http://deezer.com/us/track/12345?utm_campaign...
                    id_from_url_extra = id_from_url.split('?')[0]

                    id = int(id_from_url_extra)
                    logger.debug(f"Extracted group={id_type}, id={id}")
                    return id_type, id
                except (IndexError, ValueError) as e:
                    continue
            return False, False

        logger.info("[!] Queueing releases, this might take awhile...")

        if self.release_from or self.release_to:
            if self.release_from and self.release_to:
                logger.info(":: Getting releases that were released between "
                            f"{dates.ui_date(self.release_from)} and "
                            f"{dates.ui_date(self.release_to)}")
            elif self.release_from:
                logger.info(":: Getting releases that were released after "
                            f"{dates.ui_date(self.release_from)}")
            elif self.release_to:
                logger.info(":: Getting releases that were released before "
                            f"{dates.ui_date(self.release_to)}")

        if monitored:
            artist_id = self.db.get_all_monitored_artist_ids()

        if artist:
            [process_artist_by_name(a) for a in artist]

        if artist_id:
            [process_artist_by_id(i) for i in artist_id]

        if album_id:
            [process_album_by_id(i) for i in album_id]

        if track_id:
            [process_track_by_id(i) for i in track_id]

        if album_file:
            logger.info(f":: Reading from file {album_file}")
            if Path(album_file).exists():
                album_list = utils.dataprocessor.read_file_as_csv(album_file, split_new_line=False)
                album_list = utils.dataprocessor.process_input_file(album_list)
                if album_list:
                    if isinstance(album_list[0], int):
                        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                            _api_results = list(tqdm(ex.map(process_album_by_id, album_list),
                                                     total=len(album_list),
                                                     desc=f"Fetching album data for {len(album_list)} "
                                                          f"album(s), please wait...", ascii=" #",
                                                     bar_format=ui.TQDM_FORMAT))
                    else:
                        logger.debug(f"Invalid album ID: \"{album_list[0]}\"")
                        logger.error(f"Invalid album ID file detected.")
            else:
                logger.error(f"The file {album_file} could not be found")
                sys.exit()

        if artist_file:
            # TODO artist_file is in different format than album_file and track_file
            # TODO is one continuous CSV line better than separate lines?
            logger.info(f":: Reading from file {artist_file}")
            if Path(artist_file).exists():
                artist_list = utils.dataprocessor.read_file_as_csv(artist_file)
                if artist_list:
                    if isinstance(artist_list[0], int):
                        logger.debug(f"{artist_file} contains artist IDs")
                        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                            _api_results = list(tqdm(ex.map(process_artist_by_id, artist_list),
                                                     total=len(artist_list),
                                                     desc=f"Fetching artist release data for {len(artist_list)} "
                                                          f"artist(s), please wait...", ascii=" #",
                                                     bar_format=ui.TQDM_FORMAT))
                    elif isinstance(artist_list[0], str):
                        logger.debug(f"{artist_file} contains artist names")
                        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                            _api_results = list(tqdm(ex.map(process_artist_by_name, artist_list),
                                                     total=len(artist_list),
                                                     desc=f"Fetching artist release data for {len(artist_list)} "
                                                          f"artist(s), please wait...",
                                                     ascii=" #",
                                                     bar_format=ui.TQDM_FORMAT))
            else:
                logger.error(f"The file {artist_file} could not be found")
                sys.exit()

        if track_file:
            logger.info(f":: Reading from file {track_file}")
            if Path(track_file).exists():
                track_list = utils.dataprocessor.read_file_as_csv(track_file, split_new_line=False)
                try:
                    track_list = [int(x) for x in track_list]
                except TypeError:
                    logger.info("Track file must only contain track IDs")
                    return

                if track_list:
                    with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                        _api_results = list(tqdm(ex.map(process_track_file, track_list),
                                                 total=len(track_list),
                                                 desc=f"Fetching track release data for {len(track_list)} "
                                                      f"track(s), please wait...", ascii=" #",
                                                 bar_format=ui.TQDM_FORMAT))
            else:
                logger.error(f"The file {track_file} could not be found")
                sys.exit()

        if url:
            logger.debug("Processing URLs")
            for u in url:
                egroup, eid = extract_id_from_url(u)
                if not egroup or not eid:
                    logger.error(f"Invalid URL -- {u}")
                    continue

                if egroup == "artist":
                    process_artist_by_id(eid)
                elif egroup == "album":
                    process_album_by_id(eid)
                elif egroup == "playlist":
                    process_playlist_by_id(eid)
                elif egroup == "track":
                    process_track_by_id(eid)

        if self.duplicate_id_count > 0:
            logger.info(f"Cleaned up {self.duplicate_id_count} duplicate release(s). See log for additional info.")

        if auto:
            if len(self.queue_list):
                self.download_queue()
            else:
                print("")
                logger.info("No releases found matching applied filters.")


================================================
FILE: deemon/cmd/extra.py
================================================
from concurrent.futures import ThreadPoolExecutor
import logging
from tqdm import tqdm
from deemon.core import db as dbase
from deemon.core.api import PlatformAPI
from deemon.core.config import Config as config
from deemon.utils import ui, performance

logger = logging.getLogger(__name__)



def debugger(message: str, payload = None):
    if config.debug_mode():
        if not payload:
            payload = ""
        logger.debug(f"DEBUG_MODE: {message} {str(payload)}")
            

def main():
    db = dbase.Database()
    api = PlatformAPI()
    releases = db.get_artist_releases()
    if not len(releases):
        return logger.warning("No releases found in local database")
    logger.debug("Fetching extra release data...")
    debugger("SpawningThreads", api.max_threads)
    with ThreadPoolExecutor(max_workers=api.max_threads) as ex:
        api_result = list(
            tqdm(ex.map(api.get_extra_release_info, releases),
                    total=len(releases),
                    desc=f"Fetching extra release data for {len(releases):,} "
                         "releases, please wait...", ascii=" #",
                    bar_format=ui.TQDM_FORMAT)
        )

    if len(api_result):
        logger.info(":: Saving changes to database, this can take several minutes...")
        db.add_extra_release_info(api_result)
        db.commit()
        print("")
        performance.operation_time(config.get('start_time'))
        logger.info("Extra release info has been updated")


================================================
FILE: deemon/cmd/generate.py
================================================
from pathlib import Path

import tqdm as tqdm
from deezer import Deezer


def read_album_ids_from_file(filename):
    if not Path(filename).exists():
        raise Exception("File does not exist")
    ids = []
    with open(filename, 'r') as f:
        f.readline()
        for l in f:
            ids.append(l.encode("ascii", "ignore"))
        print("Total lines read from text file: " + str(len(ids)))
        return ids


def clean_absolute_paths(album_list):
    stripped = []
    for line in album_list:
        stripped.append(line.split("\\"))
    return stripped


def clean_year_from_album(album_list, level: int = 5):
    artist_album = []
    for line in album_list:
        if len(line) == level:
            strip_year = line[3][-6:].strip("()")
            try:
                int(strip_year)
            except Exception:
                artist_album.append([line[2], line[3]])
                continue
            artist_album.append([line[2], line[3][:-6]])
    return artist_album


def clean_artist_album_text(album_list: list):
    stripped = []
    for line in album_list:
        line = line.decode()
        line = line.replace('\n', '')
        line = line.replace('�', '')
        line = line.replace('¡', '')
        line = line.replace('É', 'E')
        line = line.replace('.', '')
        line = line.replace('+', ' ')
        line = line.replace('/', ' ')
        stripped.append(line.split(" - "))
    return stripped


def get_artist_album(filename: str, absolute_path: bool = False):
    list_from_file = read_album_ids_from_file(filename)
    if absolute_path:
        stripped_paths = clean_absolute_paths(list_from_file)
        artist_album = clean_year_from_album(stripped_paths, level=5)
    else:
        artist_album = clean_artist_album_text(list_from_file)
    print("Total albums to lookup: " + str(len(artist_album)))
    return sorted(x for x in artist_album)


def get_api_results(album_list, artist_name: str = None):
    dz = Deezer()

    for x in album_list:
        album_list.set_description_str(f"Pass: {str(len(id_list))} | Fail: {str(len(fail_list))}")
        # For testing, only process this artist
        if artist_name and artist_name != x[0]:
            continue
        # Remove things like "(Bonus Tracks)"
        artist_from_file = x[0]
        album_from_file = x[1]
        stripped_album_from_file = x[1].split(" (")[0]

        api_artist = dz.api.search_artist(x[0], limit=10)['data']
        found_artist = True
        for artist_result in api_artist:
            # TODO name decode - replace unknown with ? - use as wildcard
            encoded_name = artist_result['name'].encode("ascii", "replace")
            decoded_name = encoded_name.decode()
            if artist_from_file == decoded_name:
                api_artist = artist_result
                found_artist = True
                break
            else:
                found_artist = False

        # TODO make this add albums to id and break out
        if found_artist is False:
            for artist in api_artist:
                get_albums = dz.api.get_artist_albums(artist['id'])['data']
                if album_from_file in [x['title'] for x in get_albums]:
                    api_artist = artist
                    break
            #
            # print("Searched all albums, nothing matches!")
            # exit()
        try:
            all_albums = dz.api.get_artist_albums(api_artist['id'])['data']
        except:
            fail_list.append(f"{x[0]} - {x[1]}")
            continue
        api_albums = [[x['title'].split(" (")[0], x['id']] for x in all_albums]
        for [title, id] in api_albums:
            clean_title = title
            clean_title = clean_title.replace('¡', '')
            clean_title = clean_title.replace('É', 'E')
            clean_title = clean_title.replace('.', '')
            clean_title = clean_title.replace(' + ', ' ')
            clean_title = clean_title.replace(' / ', ' ')
            if album_from_file.lower() == clean_title.lower() or stripped_album_from_file.lower() == clean_title.lower():
                if id not in id_list:
                    id_list.append(id)
                break
            if album_from_file.lower() in clean_title.lower() or stripped_album_from_file.lower() in clean_title.lower():
                if id not in id_list:
                    id_list.append(id)
                break
        else:
            fail_list.append(f"{x[0]} - {x[1]}")


id_list = []
fail_list = []
input_file_or_directory: str = None
output_file_passing: str = None
output_file_failing: str = None

album_list = get_artist_album(input_file_or_directory)

progress = tqdm.tqdm(album_list, ascii=" #",
                     bar_format='{desc}...  {n_fmt}/{total_fmt} [{bar:40}] {percentage:3.0f}%')
progress.set_description_str("Getting IDs")

get_api_results(progress)

print("PASS: " + str(len(id_list)))
with open(output_file_passing, "w") as f:
    for id in id_list:
        f.write(str(id) + "\n")

print("FAIL: " + str(len(fail_list)))
with open(output_file_failing, "w") as f:
    for id in fail_list:
        f.write(str(id) + "\n")


================================================
FILE: deemon/cmd/monitor.py
================================================
import logging
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from tqdm import tqdm

from deemon.cmd import search
from deemon.cmd.refresh import Refresh
from deemon.core.api import PlatformAPI
from deemon.core.config import Config as config
from deemon.core.db import Database
from deemon.utils import dataprocessor, ui

logger = logging.getLogger(__name__)


class Monitor:

    def __init__(self, active_api=None):
        self.bitrate = None
        self.alerts = False
        self.record_type = None
        self.download_path = None
        self.remove = False
        self.refresh = True
        self.is_search = False
        self.duplicates = 0
        self.time_machine = None
        self.dl = None
        self.db = Database()
        self.api = active_api or PlatformAPI()

    def set_config(self, bitrate: str, alerts: bool, record_type: str, download_path: Path):
        self.bitrate = bitrate
        self.alerts = alerts
        self.record_type = record_type
        self.download_path = download_path
        self.debugger("SetConfig", {'bitrate': bitrate, 'alerts': alerts, 'type': record_type, 'path': download_path})

    def set_options(self, remove, dl_all, search):
        self.remove = True if remove else False
        self.dl = True if dl_all else False
        self.is_search = True if search else False
        self.debugger("SetOptions", {'remove': remove, 'dl': dl_all, 'search': search})

    def debugger(self, message: str, payload=None):
        if config.debug_mode():
            if not payload:
                payload = ""
            logger.debug(f"DEBUG_MODE: {message} {str(payload)}")

    def get_best_result(self, api_result) -> list:
        name = api_result['query']

        if self.is_search:
            logger.debug("Waiting for user input...")
            prompt = self.prompt_search(name, api_result['results'])
            if prompt:
                logger.debug(f"User selected {prompt}")
                return [prompt]

        matches = [r for r in api_result['results'] if r['name'].lower() == name.lower()]
        self.debugger("Matches", matches)

        if len(matches) == 1:
            return [matches[0]]
        elif len(matches) > 1:
            logger.debug(f"Multiple matches were found for artist \"{api_result['query']}\"")
            if config.prompt_duplicates():
                logger.debug("Waiting for user input...")
                prompt = self.prompt_search(name, matches)
                if prompt:
                    logger.debug(f"User selected {prompt}")
                    return [prompt]
                else:
                    logger.info(f"No selection made, skipping {name}...")
                    return []
            else:
                self.duplicates += 1
                return [matches[0]]
        elif not len(matches):
            logger.debug(f"   [!] No matches were found for artist \"{api_result['query']}\"")
            if config.prompt_no_matches() and len(api_result['results']):
                logger.debug("Waiting for user input...")
                prompt = self.prompt_search(name, api_result['results'])
                if prompt:
                    logger.debug(f"User selected {prompt}")
                    return [prompt]
                else:
                    logger.info(f"No selection made, skipping {name}...")
                    return []
            else:
                logger.info(f"   [!] Artist {name} not found")
                return []

    def prompt_search(self, value, api_result):
        menu = search.Search(active_api=self.api)
        ask_user = menu.artist_menu(value, api_result, True)
        if ask_user:
            return {'id': ask_user['id'], 'name': ask_user['name']}
        return logger.debug("No artist selected, skipping...")

    # @performance.timeit
    def build_artist_query(self, api_result: list):
        existing = self.db.get_all_monitored_artist_ids()
        artists_to_add = []
        pbar = tqdm(api_result, total=len(api_result), desc="Setting up artists for monitoring...", ascii=" #",
                    bar_format=ui.TQDM_FORMAT)
        for artist in pbar:
            if artist is None:
                continue
            if artist['id'] in existing:
                logger.info(f"   - Already monitoring {artist['name']}, skipping...")
            else:
                artist.update({'bitrate': self.bitrate, 'alerts': self.alerts, 'record_type': self.record_type,
                               'download_path': self.download_path, 'profile_id': config.profile_id(),
                               'trans_id': config.transaction_id()})
                artists_to_add.append(artist)
        if len(artists_to_add):
            logger.debug("New artists have been monitored. Saving changes to the database...")
            self.db.new_transaction()
            self.db.fast_monitor(artists_to_add)
            self.db.commit()
            return True

    def build_playlist_query(self, api_result: list, include_artists: bool):

        if include_artists:
            include_artists = '1'

        existing = self.db.get_all_monitored_playlist_ids() or []
        playlists_to_add = []
        pbar = tqdm(api_result, total=len(api_result), desc="Setting up playlists for monitoring...", ascii=" #",
                    bar_format=ui.TQDM_FORMAT)
        for i, playlist in enumerate(pbar):
            if not playlist:
                continue
            if playlist['id'] in existing:
                logger.info(f"   Already monitoring {playlist['title']}, skipping...")
            else:
                playlist.update(
                    {
                        'bitrate': self.bitrate,
                        'alerts': self.alerts,
                        'download_path': self.download_path,
                        'profile_id': config.profile_id(),
                        'trans_id': config.transaction_id(),
                        'monitor_artists': include_artists
                    }
                )
                playlists_to_add.append(playlist)
        if len(playlists_to_add):
            logger.debug("New playlists have been monitored. Saving changes to the database...")
            self.db.new_transaction()
            self.db.fast_monitor_playlist(playlists_to_add)
            self.db.commit()
            return True

    def call_refresh(self):
        refresh = Refresh(self.time_machine, ignore_filters=self.dl, active_api=self.api)
        refresh.run()

    # @performance.timeit
    def artists(self, names: list) -> None:
        """
        Return list of dictionaries containing each artist
        """
        if self.remove:
            return self.purge_artists(names=names)
        self.debugger("SpawningThreads", self.api.max_threads)
        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
            api_result = list(
                tqdm(ex.map(self.api.search_artist, names), total=len(names),
                     desc=f"Fetching artist data for {len(names):,} artist(s), please wait...",
                     ascii=" #", bar_format=ui.TQDM_FORMAT))

        select_artist = tqdm(api_result, total=len(api_result), desc="Examining results for best match...", ascii=" #",
                             bar_format=ui.TQDM_FORMAT)

        to_monitor = []
        for artist in select_artist:
            best_result = self.get_best_result(artist)
            if best_result:
                to_monitor.append(best_result)

        to_process = [item for elem in to_monitor for item in elem if len(item)]
        if self.build_artist_query(to_process):
            self.call_refresh()
        else:
            print("")
            logger.info("No new artists have been added, skipping refresh.")

    # @performance.timeit
    def artist_ids(self, ids: list):
        ids = [int(x) for x in ids]
        if self.remove:
            return self.purge_artists(ids=ids)
        self.debugger("SpawningThreads", self.api.max_threads)
        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
            api_result = list(
                tqdm(ex.map(self.api.get_artist_by_id, ids), total=len(ids),
                     desc=f"Fetching artist data for {len(ids):,} artist(s), please wait...",
                     ascii=" #", bar_format=ui.TQDM_FORMAT))

        if self.build_artist_query(api_result):
            self.call_refresh()
        else:
            print("")
            logger.info("No new artists have been added, skipping refresh.")

    # @performance.timeit
    def importer(self, import_path: str):
        if Path(import_path).is_file():
            imported_file = dataprocessor.read_file_as_csv(import_path)
            artist_list = dataprocessor.process_input_file(imported_file)
            if isinstance(artist_list[0], int):
                self.artist_ids(artist_list)
            else:
                self.artists(artist_list)
        elif Path(import_path).is_dir():
            import_list = [x.relative_to(import_path).name for x in sorted(Path(import_path).iterdir()) if x.is_dir()]
            if import_list:
                self.artists(import_list)
        else:
            logger.error(f"File or directory not found: {import_path}")
            return

    # @performance.timeit
    def playlists(self, playlists: list, include_artists: bool):
        if self.remove:
            return self.purge_playlists(ids=playlists)
        ids = [int(x) for x in playlists]
        self.debugger("SpawningThreads", self.api.max_threads)
        with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
            api_result = list(
                tqdm(ex.map(self.api.get_playlist, ids), total=len(ids),
                     desc=f"Fetching playlist data for {len(ids):,} playlist(s), please wait...",
                     ascii=" #", bar_format=ui.TQDM_FORMAT))

        if self.build_playlist_query(api_result, include_artists):
            self.call_refresh()
        else:
            print("")
            logger.info("No new playlists have been added, skipping refresh.")

    # @performance.timeit
    def purge_artists(self, names: list = None, ids: list = None):
        if names:
            for n in names:
                monitored = self.db.get_monitored_artist_by_name(n)
                if monitored:
                    self.db.remove_monitored_artist(monitored['artist_id'])
                    logger.info(f"No longer monitoring {monitored['artist_name']}")
                else:
                    logger.info(f"{n} is not being monitored yet")
        if ids:
            for i in ids:
                monitored = self.db.get_monitored_artist_by_id(i)
                if monitored:
                    self.db.remove_monitored_artist(monitored['artist_id'])
                    logger.info(f"\nNo longer monitoring {monitored['artist_name']}")
                else:
                    logger.info(f"{i} is not being monitored yet")

    def purge_playlists(self, titles: list = None, ids: list = None):
        if ids:
            for i in ids:
                monitored = self.db.get_monitored_playlist_by_id(i)
                if monitored:
                    self.db.remove_monitored_playlists(monitored['id'])
                    logger.info(f"\nNo longer monitoring {monitored['title']}")
                else:
                    logger.info(f"{i} is not being monitored yet")


================================================
FILE: deemon/cmd/profile.py
================================================
import logging

from deemon.core.config import Config as config
from deemon.core.db import Database

logger = logging.getLogger(__name__)


class ProfileConfig:
    def __init__(self, profile_name):
        self.db = Database()
        self.profile_name = profile_name
        self.profile = None

    # TODO move this to utils
    @staticmethod
    def print_header(message: str = None):
        print("deemon Profile Editor")
        if message:
            print(":: " + message + "\n")
        else:
            print("")

    def edit(self):
        profile = self.db.get_profile(self.profile_name)
        self.print_header(f"Configuring '{profile['name']}' (Profile ID: {profile['id']})")
        modified = 0
        for property in profile:
            if property == "id":
                continue
            allowed_opts = config.allowed_values(property)
            if isinstance(allowed_opts, dict):
                allowed_opts = [str(x.lower()) for x in allowed_opts.values()]

            while True:
                friendly_text = property.replace("_", " ").title()
                user_input = input(f"{friendly_text} [{profile[property]}]: ").lower()
                if user_input == "":
                    break
                # TODO move to function to share with Config.set()?
                elif user_input == "false" or user_input == "0":
                    user_input = False
                elif user_input == "true" or user_input == "1":
                    user_input = True
                elif property == "name" and self.profile_name != user_input:
                    if self.db.get_profile(user_input):
                        print("Name already in use")
                        continue
                if user_input == "none" and property != "name":
                    user_input = None
                elif allowed_opts:
                    if user_input not in allowed_opts:
                        print(f"Allowed options: " + ', '.join(str(x) for x in allowed_opts))
                        continue
                logger.debug(f"User set {property} to {user_input}")
                profile[property] = user_input
                modified += 1
                break

        if modified > 0:
            user_input = input("\n:: Save these settings? [y|N] ")
            if user_input.lower() != "y":
                logger.info("No changes made, exiting...")
            else:
                self.db.update_profile(profile)
                print(f"\nProfile '{profile['name']}' has been updated!")
        else:
            print("No changes made, exiting...")

    def add(self):
        new_profile = {}
        profile_config = self.db.get_profile(self.profile_name)
        if profile_config:
            return logger.error(f"Profile {self.profile_name} already exists")
        else:
            logger.info("Adding new profile: " + self.profile_name)
            print("** Any option left blank will fallback to global config **\n")
            new_profile['name'] = self.profile_name

        menu = [
            {'setting': 'email', 'type': str, 'text': 'Email address', 'allowed': []},
            {'setting': 'alerts', 'type': bool, 'text': 'Alerts', 'allowed': config.allowed_values('alerts')},
            {'setting': 'bitrate', 'type': str, 'text': 'Bitrate',
             'allowed': config.allowed_values('bitrate').values()},
            {'setting': 'record_type', 'type': str, 'text': 'Record Type',
             'allowed': config.allowed_values('record_type')},
            {'setting': 'plex_baseurl', 'type': str, 'text': 'Plex Base URL', 'allowed': []},
            {'setting': 'plex_token', 'type': str, 'text': 'Plex Token', 'allowed': []},
            {'setting': 'plex_library', 'type': str, 'text': 'Plex Library', 'allowed': []},
            {'setting': 'download_path', 'type': str, 'text': 'Download Path', 'allowed': []},
        ]

        for m in menu:
            repeat = True
            while repeat:
                i = input(m['text'] + ": ")
                if i == "":
                    new_profile[m['setting']] = None
                    break
                if not isinstance(i, m['type']):
                    try:
                        i = int(i)
                    except ValueError:
                        print(" - Allowed options: " + ', '.join(str(x) for x in m['allowed']))
                        continue
                if len(m['allowed']) > 0:
                    if i not in m['allowed']:
                        print(" - Allowed options: " + ', '.join(str(x) for x in m['allowed']))
                        continue
                new_profile[m['setting']] = i
                break

        print("\n")
        i = input(":: Save these settings? [y|N] ")
        if i.lower() != "y":
            return logger.info("Operation cancelled. No changes saved.")
        else:
            self.db.create_profile(new_profile)
            logger.debug(f"New profile created with the following configuration: {new_profile}")

    def delete(self):
        profile_config = self.db.get_profile(self.profile_name)
        if not profile_config:
            return logger.error(f"Profile {self.profile_name} not found")

        if profile_config['id'] == 1:
            return logger.info("You cannot delete the default profile.")

        i = input(f":: Remove the profile '{self.profile_name}'? [y|N] ")
        if i.lower() == "y":
            self.db.delete_profile(self.profile_name)
            return logger.info("Profile " + self.profile_name + " deleted.")
        else:
            return logger.info("Operation cancelled")

    def show(self):
        if not self.profile_name:
            profile = self.db.get_all_profiles()
            self.print_header(f"Showing all profiles")
        else:
            profile = [self.db.get_profile(self.profile_name)]
            self.print_header(f"Showing profile '{profile[0]['name']}' (Profile ID: {profile[0]['id']})")
            if len(profile) == 0:
                return logger.error(f"Profile {self.profile_name} not found")

        print("{:<10} {:<40} {:<8} {:<8} {:<8} {:<25} "
              "{:<20} {:<20} {:<20}".format('Name', 'Email', 'Alerts', 'Bitrate', 'Type',
                                            'Plex Base URL', 'Plex Token', 'Plex Library', 'Download Path'))
        for u in profile:
            id, name, email, alerts, bitrate, rtype, url, token, \
            lib, dl_path = [x if x is not None else '' for x in u.values()]
            print("{:<10} {:<40} {:<8} {:<8} {:<8} {:<25} "
                  "{:<20} {:<20} {:<20}".format(name, email, alerts, bitrate, rtype, url, token, lib, dl_path))
            print("")

    def clear(self):
        profile = self.db.get_profile(self.profile_name)
        self.print_header(f"Configuring '{profile['name']}' (Profile ID: {profile['id']})")
        if not profile:
            return logger.error(f"Profile {self.profile_name} not found")

        for value in profile:
            if value in ["id", "name"]:
                continue
            profile[value] = None
        self.db.update_profile(profile)
        logger.info("All values have been cleared.")


================================================
FILE: deemon/cmd/refresh.py
================================================
import logging
import re
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta

from tqdm import tqdm

from deemon.cmd.download import QueueItem, Download
from deemon.core import db, api, notifier, common
from deemon.core.config import Config as config
from deemon.utils import dates, ui, performance

logger = logging.getLogger(__name__)


class Refresh:
    def __init__(self, time_machine: datetime = None, skip_download: bool = False, ignore_filters: bool = False, active_api=None):
        self.db = db.Database()
        self.refresh_date = datetime.now()
        self.max_refresh_date = None
        self.api = active_api or api.PlatformAPI()
        self.new_releases = []
        self.new_releases_alert = []
        self.new_playlist_releases = []
        self.time_machine = time_machine
        self.total_new_releases = 0
        self.queue_list = []
        self.skip_download = skip_download
        self.download_all = ignore_filters
        self.seen = None

        if self.time_machine:
            logger.info(f":: Time Machine active: {datetime.strftime(self.time_machine, '%b %d, %Y')}!")
            config._CONFIG['new_releases']['release_max_age'] = 0
            if not self.waiting_for_refresh():
                self.db.remove_specific_releases({'tm_date': str(self.time_machine)})
                self.db.commit()

    @staticmethod
    def debugger(message: str, payload = None):
        if config.debug_mode():
            if not payload:
                payload = ""
            logger.debug(f"DEBUG_MODE: {message} {str(payload)}")

    def remove_existing_releases(self, payload: dict, seen: dict) -> list:
        """
        Return list of releases that have not been stored in the database
        """
        new_releases = []

        if payload.get('artist_id'):
            seen_releases = seen
            if seen_releases:
                seen_releases = [v for x in seen_releases for k, v in x.items() if not x.get('future_release', 0)]
                new_releases = [x for x in payload['releases'] if type(x) == dict for k, v in x.items() if
                                k == "id" and v not in seen_releases]
                return new_releases
            return [x for x in payload['releases']]

        if payload.get('tracks'):
            playlist_id = payload['id']
            seen_releases = self.db.get_playlist_tracks(playlist_id)
            if seen_releases:
                seen_releases = [v for x in seen_releases for k, v in x.items()]
                new_releases = [x for x in payload['tracks']
                                if type(x) == dict for k, v in x.items()
                                if k == "id" and v not in seen_releases]
                return new_releases
            return [x for x in payload['tracks']]

        return new_releases

    def filter_artist_releases(self, payload: dict):
        """ Inspect artist releases and decide what to do with each release """
        self.debugger(f"{payload['artist_name']} has {len(payload['releases'])} new releases")

        for release in payload['releases']:
            release['artist_id'] = payload['artist_id']
            release['artist_name'] = payload['artist_name']
            release['bitrate'] = payload['bitrate'] or config.bitrate()
            release['download_path'] = payload['download_path'] or config.download_path()
            release['future'] = self.is_future_release(release['release_date'])
            release['alerts'] = payload['alerts']
            
            if release['explicit_lyrics'] != 1:
                release['explicit_lyrics'] = 0
            
            self.append_database_release(release)
            
            if release['future']:
                continue

            if not common.exclude_filtered_versions([{'title': release['title']}]):
                # exclude_filtered_versions returns empty list if excluded
                continue

            explicit_album_id = self.explicit_id(release['title'], payload['releases'])
            if explicit_album_id:
                if explicit_album_id == release['id']:
                    logger.debug(f"An explicit release was found for {release['title']}")
                else:
                    continue

            if self.download_all:
                self.queue_release(release)
                continue

            if not self.allowed_record_type(payload['record_type'], release['record_type']):
                logger.debug(f"Record type \"{release['record_type']}\" has been filtered out, skipping release "
                             f"{release['id']}")
                continue

            if self.release_too_old(release['release_date']):
                logger.debug(f"Release {release['id']} is too old, skipping it.")
                continue

            if not payload['refreshed'] and not self.time_machine:
                continue

            self.queue_release(release)

    def append_database_release(self, new_release: dict):
        self.new_releases.append(new_release)
                
    @staticmethod
    def explicit_id(release_title: str, payload: list):
        for release in payload:
            if release['title'] == release_title:
                if release['explicit_lyrics'] == 1:
                    return release['id']

    def release_too_old(self, release_date: str):
        release_date_dt = dates.str_to_datetime_obj(release_date)
        if self.time_machine:
            if release_date_dt <= self.time_machine:
                self.debugger(f"Release date \"{release_date}\" is older than TIME_MACHINE ({str(dates.ui_date(self.time_machine))})")
                return True
        if config.release_max_age():
            if release_date_dt < (self.refresh_date - timedelta(config.release_max_age())):
                self.debugger(f"Release date \"{release_date}\" is older than RELEASE_MAX_AGE ({config.release_max_age()} day(s))")
                return True
            

    @staticmethod
    def is_future_release(release_date: str):
        """ Return 1 if release date is in future, otherwise return 0 """
        release_date_dt = dates.str_to_datetime_obj(release_date)
        if release_date_dt > datetime.now():
            return 1
        else:
            return 0

    @staticmethod
    def allowed_record_type(artist_rec_type, release_rec_type: str):
        """ Compare actual record_type against allowable """
        
        if artist_rec_type:
            if artist_rec_type == release_rec_type or artist_rec_type == "all":
                return True
            else:
                return
        elif config.record_type() == release_rec_type:
            return True
        elif config.record_type() == "all":
            return True

    def queue_release(self, release: dict):
        """ Add release to download queue and create alert notification """

        # Create notification of release if per-artist is set to True
        if release['alerts'] is not False and config.alerts():
            self.create_notification(release)
        self.queue_list.append(QueueItem(release_full=release))

    def filter_playlist_releases(self, payload: dict):
        self.debugger(f"Filtering {len(payload['tracks'])} tracks for playlist {payload['title']}")

        if len(payload['tracks']):
            for track in payload['tracks']:
                new_track = track.copy()
                new_track['playlist_id'] = payload['id']
                self.new_playlist_releases.append(new_track)

            if payload['refreshed'] == 0:
                return

            queue_obj = QueueItem(playlist=payload, bitrate=payload['bitrate'], download_path=payload['download_path'])
            self.debugger("QueuePlaylistItem", queue_obj)
            self.queue_list.append(queue_obj)

    def waiting_for_refresh(self):
        playlists = self.db.get_unrefreshed_playlists()
        artists = self.db.get_unrefreshed_artists()
        if len(playlists) or len(artists):
            return {'artists': artists, 'playlists': playlists}

    def prep_payload(self, p):
        if len(p):
            p['releases'] = self.remove_existing_releases(p, self.seen)
            self.filter_artist_releases(p)
        else:
            logger.debug("No payload provided")

    def run(self, artists: list = None, playlists: list = None):

        if config.check_account_status():
            if self.api.account_type == "free" and config.bitrate() != "128":
                notification = notifier.Notify()
                notification.expired_arl()
                return logger.error("   [X] ARL expired? Deezer account only allows low"
                                    " quality. If you wish to download "
                                    "anyway, set `check_account_status` "
                                    "to False in the config.")

        if artists:
            self.debugger("ManualRefresh", artists)
            monitored_artists = [x for x in (self.db.get_monitored_artist_by_name(a) for a in artists) if x]
            if not len(monitored_artists):
                return logger.warning("Specified artist(s) were not found")
            api_result = self.get_release_data({'artists': monitored_artists})
        elif playlists:
            self.debugger("ManualRefresh", playlists)
            monitored_playlists = [x for x in (self.db.get_monitored_playlist_by_name(p) for p in playlists) if x]
            if not len(monitored_playlists):
                return logger.warning("Specified playlist(s) were not found")
            api_result = self.get_release_data({'playlists': monitored_playlists})
        else:
            waiting = self.waiting_for_refresh()
            if waiting:
                logger.debug(f"There are {len(waiting['playlists'])} playlist(s) and "
                             f"{len(waiting['artists'])} artist(s) waiting to be refreshed.")
                api_result = self.get_release_data(waiting)
            else:
                self.debugger("FullRefresh")
                monitored_playlists = self.db.get_all_monitored_playlists()
                monitored_artists = self.db.get_all_monitored_artists()
                if not len(monitored_playlists) and not len(monitored_artists):
                    return logger.warning("No artists found to refresh")
                api_result = self.get_release_data({'artists': monitored_artists, 'playlists': monitored_playlists})

        if len(api_result):
            self.seen = self.db.get_artist_releases()
            payload_container = tqdm(api_result['artists'], total=len(api_result['artists']),
                                     desc=f"Scanning release data for new releases...",
                                     ascii=" #",
                                     bar_format=ui.TQDM_FORMAT)
            for payload in payload_container:
                self.prep_payload(payload)

        playlist_monitor_artists = []
        for payload in api_result['playlists']:
            if payload and len(payload):
                self.seen = self.db.get_playlist_tracks(payload['id'])
                payload['tracks'] = self.remove_existing_releases(payload, self.seen)
                self.filter_playlist_releases(payload)

                if payload['monitor_artists']:
                    logger.debug(f"Artists from this playlist ({payload['id']}) are to be monitored!")
                    for track in payload['tracks']:
                        playlist_monitor_artists.append(track['artist_id'])
        playlist_monitor_artists = list(set(playlist_monitor_artists))

        if self.skip_download:
            logger.info(f"   [!] You have opted to skip downloads, clearing {len(self.queue_list):,} item(s) from queue...")
            self.queue_list.clear()
            self.new_releases_alert.clear()

        if len(self.queue_list):
            dl = Download(active_api=self.api)
            dl.download_queue(self.queue_list)

        if len(self.new_playlist_releases) or len(self.new_releases):
            if len(self.new_playlist_releases):
                logger.debug("Updating playlist releases in database...")
                self.db.add_new_playlist_releases(self.new_playlist_releases)
            if len(self.new_releases):
                logger.debug("Updating artist releases in database...")
                self.db.add_new_releases(self.new_releases)
            self.db.commit()
            self.db_stats()
            performance.operation_time(config.get('start_time'))
            logger.info("Database is up-to-date.")
        else:
            self.db_stats()
            performance.operation_time(config.get('start_time'))
            logger.info("Database is up-to-date. No new releases were found.")

        if len(self.new_releases_alert) > 0:
            notification = notifier.Notify(self.new_releases_alert)
            notification.send()

        if playlist_monitor_artists:
            print("")
            logger.info(":: New artists to monitor, stand by...")
            time.sleep(2)
            from deemon.cmd.monitor import Monitor
            monitor = Monitor(active_api=self.api)
            monitor.artist_ids(playlist_monitor_artists)

    def db_stats(self):
        artists = len(self.db.get_all_monitored_artist_ids())
        playlists = len(self.db.get_all_monitored_playlist_ids())
        releases = len(self.db.get_artist_releases())
        future = len(self.db.get_future_releases())

        print("")
        print(f"+ Artists monitored: {artists:,}")
        print(f"+ Playlists monitored: {playlists:,}")
        print(f"+ Releases seen: {releases:,}")
        print(f"+ Pending future releases: {future:,}")
        print("")

    def get_release_data(self, to_refresh: dict) -> dict:
        """
        Generate a list of dictionaries containing artist (DB) and release (API)
        information.
        """

        api_result = {'artists': [], 'playlists': []}

        logger.debug(f"Standby, starting refresh...")

        if to_refresh.get('playlists') and len(to_refresh.get('playlists')):
            logger.debug("Fetching playlist track data...")
            self.debugger("SpawningThreads", self.api.max_threads)
            with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                api_result['playlists'] = list(
                    tqdm(ex.map(self.api.get_playlist_tracks,
                                to_refresh['playlists']),
                         total=len(to_refresh['playlists']),
                         desc=f"Fetching playlist track data for "
                              f"{len(to_refresh['playlists'])} playlist(s), "
                              "please wait...",
                         ascii=" #",
                         bar_format=ui.TQDM_FORMAT)
                )

        if to_refresh.get('artists') and len(to_refresh['artists']):
            logger.debug("Fetching artist release data...")
            self.debugger("SpawningThreads", self.api.max_threads)
            with ThreadPoolExecutor(max_workers=self.api.max_threads) as ex:
                api_result['artists'] = list(
                    tqdm(ex.map(self.api.get_artist_albums, to_refresh['artists']),
                         total=len(to_refresh['artists']), desc=f"Fetching artist release data for {len(to_refresh['artists']):,} artist(s), please wait...", ascii=" #",
                         bar_format=ui.TQDM_FORMAT)
                )
        return api_result

    def create_notification(self, release: dict):
        for days in self.new_releases_alert:
            for key in days:
                if key == "release_date":
                    if release['release_date'] in days[key]:
                        days["releases"].append(
                            {
                                'artist': release['artist_name'],
                                'album': release['title'],
                                'cover': release['cover_big'],
                                'url': release['link'],
                                'track_num': release.get('nb_tracks', None),
                                'record_type': release['record_type'],
                            }
                        )
                        return

        self.new_releases_alert.append(
            {
                'release_date': release['release_date'], 
                'releases': [
                    {
                        'artist': release['artist_name'],
                        'album': release['title'],
                        'cover': release['cover_big'],
                        'url': release['link'],
                        'track_num': release.get('nb_tracks', None),
                        'record_type': release['record_type'],
                    }
                ]
            }
        )


================================================
FILE: deemon/cmd/rollback.py
================================================
import logging

from deemon.core.db import Database
from deemon.utils import dates

logger = logging.getLogger(__name__)
db = Database()


def view_transactions():
    transactions = db.get_transactions()
    if not transactions:
        return logger.info("No transactions are available to be rolled back.")

    for i, transaction in enumerate(transactions, start=1):
        release_id = []
        artist_names = []
        playlist_titles = []

        for k, v in transaction.items():
            if (k == "releases" or k == "playlist_tracks") and transaction[k]:
                for item in transaction[k]:
                    for key, val in item.items():
                        if key == "album_id" or key == "track_id":
                            if item[key] not in release_id:
                                release_id.append(item[key])
            if k == "monitor" and transaction[k]:
                if transaction[k] not in artist_names:
                    artist_names = [x['artist_name'] for x in transaction[k]]
            if k == "playlists" and transaction[k]:
                if transaction[k] not in playlist_titles:
                    playlist_titles.append(transaction[k][0]['title'])

        release_id_len = len(release_id)

        if release_id_len == 1:
            release_text = f" and {release_id_len} release"
        elif release_id_len > 1:
            release_text = f" and {release_id_len} releases"
        else:
            release_text = ""

        if len(artist_names) > 1:
            if len(playlist_titles) > 1:
                playlist_text = f", {len(playlist_titles)} playlists"
            elif len(playlist_titles) == 1:
                playlist_text = f", {len(playlist_titles)} playlist"
            else:
                playlist_text = ""
            output_text = f"Added {artist_names[0]} + {len(artist_names) - 1} artist(s){playlist_text}{release_text}"
        elif len(artist_names) == 1:
            if len(playlist_titles) > 1:
                playlist_text = f", {len(playlist_titles)} playlists"
            elif len(playlist_titles) == 1:
                playlist_text = f", {len(playlist_titles)} playlist"
            else:
                playlist_text = ""
            output_text = f"Added {artist_names[0]}{playlist_text}{release_text}"
        else:
            if len(playlist_titles) > 1:
                output_text = f"Added {playlist_titles[0]} + {len(playlist_titles) - 1}{release_text}"
            elif len(playlist_titles) == 1:
                output_text = f"Added {playlist_titles[0]}{release_text}"
            else:
                output_text = f"Added {release_text[4:]}"

        print(f"{i}. {dates.get_friendly_date(transaction['timestamp'])} - {output_text}")

    rollback = None
    while rollback not in range(len(transactions)):
        rollback = input("\nSelect specific refresh to rollback (or press Enter to exit): ")
        if rollback == "":
            return
        try:
            rollback = int(rollback) - 1
        except ValueError:
            logger.error("Invalid input")

    rollback = transactions[rollback]['id']
    logger.debug(f"Rolling back transaction {rollback}")
    db.rollback_refresh(rollback)


def rollback_last(i: int):
    db.rollback_last_refresh(i)
    logger.info(f"Rolled back the last {i} transaction(s).")


================================================
FILE: deemon/cmd/search.py
================================================
import logging
import sys

from deezer import Deezer

from deemon.cmd import download
from deemon.cmd import monitor as mon
from deemon.core import db, api
from deemon.core.config import Config as config
from deemon.utils import dates

logger = logging.getLogger(__name__)


class Search:
    def __init__(self, active_api=None):
        self.api = active_api or api.PlatformAPI()
        self.artist_id: int = None
        self.artist: str = None
        self.choices: list = []
        self.status_message: str = None
        self.queue_list = []
        self.select_mode = False
        self.explicit_only = False
        self.search_results: str = None

        self.sort: str = "release_date"
        self.filter: str = None
        self.desc: bool = True

        self.gte_year = None
        self.lte_year = None
        self.eq_year = None

        self.db = db.Database()
        self.dz = Deezer()

    @staticmethod
    def truncate_artist(name: str):
        if len(name) > 45:
            return name[0:40] + "..."
        return name

    def get_latest_release(self, artist_id: int):
        try:
            all_releases = self.dz.api.get_artist_albums(artist_id)['data']
            sorted_releases = sorted(all_releases, key=lambda x: x['release_date'], reverse=True)
            latest_release = sorted_releases[0]
        except IndexError:
            return "       - No releases found"
        return f"       - Latest release: {latest_release['title']} ({dates.get_year(latest_release['release_date'])})"

    def display_monitored_status(self, artist_id: int):
        if self.db.get_monitored_artist_by_id(artist_id):
            return "[M] "
        return "    "

    @staticmethod
    def has_duplicate_artists(name: str, artist_dicts: dict):
        names = [x['name'] for x in artist_dicts if x['name'] == name]
        if len(names) > 1:
            return True

    def show_mini_queue(self):
        num_queued = len(self.queue_list)
        if num_queued > 0:
            return f" ({str(num_queued)} Queued)"
        return ""

    def search_menu(self, query: str = None):
        exit_search: bool = False
        quick_search: bool = False

        while exit_search is False:
            self.clear()
            print("deemon Interactive Search Client\n")
            if len(self.queue_list) > 0:
                self.display_options(options="(d) Download Queue  (Q) Show Queue")
            if query:
                search_query = query
                query = None
            else:
                search_query = input(f":: Enter an artist to search for{self.show_mini_queue()}: ")
                if search_query == "exit":
                    if self.exit_search():
                        sys.exit()
                    continue
                elif search_query == "d":
                    if len(self.queue_list) > 0:
                        self.start_queue()
                        continue
                elif search_query == "Q":
                    if len(self.queue_list) > 0:
                        self.queue_menu()
                    else:
                        self.status_message = "Queue is empty"
                    continue
                elif search_query == "":
                    continue
            
            self.clear()
            print("deemon Interactive Search Client\n")
            self.search_results = self.api.search_artist(search_query, config.query_limit())
            if not self.search_results['results']:
                self.status_message = "No results found for: " + search_query
                continue

            smart_search = None
            if config.smart_search():
                for result in self.search_results['results']:
                    if result['name'].lower() == search_query.lower():
                        if not smart_search:
                            smart_search = result
                        else:
                            smart_search = None
                            break
            
            if smart_search:
                self.artist = smart_search['name']
                album_selected = self.album_menu(smart_search)
                if album_selected:
                    return [album_selected]

            artist_selected = self.artist_menu(self.search_results['query'], self.search_results['results'], quick_search)
            if artist_selected:
                return [artist_selected]

    def queue_menu_options(self):
        ui_options = ("(d) Download Queue  (c) Clear Queue  (b) Back")
        self.display_options(options=ui_options)

    def artist_menu(self, query: str, results: dict, artist_only: bool = False):
        exit_artist: bool = False
        while exit_artist is False:
            self.clear()
            print("Search results for artist: " + query)
            for idx, option in enumerate(results, start=1):
                print(f"{self.display_monitored_status(option['id'])}{idx}. {self.truncate_artist(option['name'])}")
                if self.has_duplicate_artists(option['name'], results):
                    print(self.get_latest_release(option['id']))
                    print("       - Artist ID: " + str(option['id']))
                    if not option.get('nb_album'):
                        option['nb_album'] = self.dz.api.get_artist(option['id'])['nb_album']
                    print("       - Total releases: " + str(option['nb_album']))
                    self.status_message = "Duplicate artists found"
            # TODO make options smarter/modular
            if len(self.queue_list) > 0:
                self.display_options(options="(b) Back  (d) Download Queue  (Q) Show Queue")
            else:
                self.display_options(options="(b) Back")
            response = input(f":: Please choose an option or type 'exit'{self.show_mini_queue()}: ")
            if response == "d":
                if len(self.queue_list) > 0:
                    self.start_queue()
                    continue
            elif response == "Q":
                if len(self.queue_list) > 0:
                    self.queue_menu()
                else:
                    self.status_message = "Queue is empty"
                continue
            elif response == "b":
                break
            elif response == "exit":
                if self.exit_search() and not artist_only:
                    sys.exit()
                else:
                    return
            elif response == "":
                continue

            try:
                response = int(response)
            except ValueError:
                self.status_message = f"Invalid selection: {response}"
            else:
                response = response - 1
                if response in range(len(results)):
                    self.artist = results[response]['name']
                    if artist_only:
                        self.clear()
                        return results[response]
                    self.album_menu(results[response])
                else:
                    self.status_message = f"Invalid selection: {response}"
                    continue

    def get_filtered_year(self):
        if self.gte_year and self.lte_year:
            return f"{self.gte_year} - {self.lte_year}"
        elif self.gte_year:
            return f">={self.gte_year}"
        elif self.lte_year:
            return f"<={self.lte_year}"
        elif self.eq_year:
            return f"{self.eq_year}"
        else:
            return "All"

    def album_menu_header(self, artist: str):
        filter_text = "All" if not self.filter else self.filter.title()
        filter_year = self.get_filtered_year()
        if self.explicit_only:
            filter_text = filter_text + " (Explicit Only)"
        desc_text = "desc" if self.desc else "asc"
        sort_text = self.sort.replace("_", " ").title() + " (" + desc_text + ")"
        print("Discography for artist: " + artist)
        print("Filter: " + filter_text + " | Sort: " + sort_text + " | Year: " + filter_year + "\n")

    def album_menu_options(self, monitored):
        print("")
        if not monitored:
            monitor_opt = "(m) Monitor"
        else:
            monitor_opt = "(m) Stop Monitoring"
        ui_filter = "Filters: (*) All  (a) Albums  (e) EP  (s) Singles - (E) Explicit (r) Reset"
        ui_sort = "   Sort: (y) Release Date (desc)  (Y) Release Date (asc)  (t) Title (desc)  (T) Title (asc)"
        ui_mode = "   Mode: (S) Toggle Select"
        ui_options = ("(b) Back  (d) Download Queue  (Q) Show Queue  (f) Queue Filtered  "
                      f"{monitor_opt}")
        self.display_options(ui_filter, ui_sort, ui_mode, ui_options)

    @staticmethod
    def explicit_lyrics(is_explicit):
        if is_explicit > 0:
            return f"[E]"
        else:
            return f"   "

    def item_selected(self, id):
        if self.select_mode:
            if [x for x in self.queue_list if x.album_id == id or x.track_id == id]:
                return "[*] "
            else:
                return "[ ] "
        else:
            return "    "

    def show_mode(self):
        if self.select_mode:
            return "[SELECT] "
        return ""

    def album_menu(self, artist: dict):
        exit_album_menu: bool = False
        # Rewrite DICT to follow old format used by get_artist_albums
        artist_tmp = {'artist_id': artist['id'], 'artist_name': artist['name']}

        artist_albums = self.api.get_artist_albums(artist_tmp)['releases']
        while exit_album_menu is False:
            self.clear()
            self.album_menu_header(artist['name'])
            filtered_choices = self.filter_choices(artist_albums)
            for idx, album in enumerate(filtered_choices, start=1):
                print(f"{self.explicit_lyrics(album['explicit_lyrics'])} {self.item_selected(album['id'])}{idx}. ({dates.get_year(album['release_date'])}) "
                      f"{album['title']}")
            monitored = self.db.get_monitored_artist_by_id(artist['id'])
            self.album_menu_options(monitored)

            prompt = input(f":: {self.show_mode()}Please choose an option or type 'exit'{self.show_mini_queue()}: ")
            if prompt == "a":
                self.filter = "album"
            elif prompt == "e":
                self.filter = "ep"
            elif prompt == "s":
                self.filter = "single"
            elif prompt == "*":
                self.filter = None
            elif prompt == "E":
                self.explicit_only ^= True
            elif prompt == "r":
                self.filter = None
                self.explicit_only = False
                self.sort = "release_date"
                self.desc = True
                self.gte_year = None
                self.lte_year = None
                self.eq_year = None
            elif prompt.startswith(">="):
                self.eq_year = None
                self.gte_year = int(prompt[2:])
            elif prompt.startswith("<="):
                self.eq_year = None
                self.lte_year = int(prompt[2:])
            elif prompt.startswith("="):
                self.lte_year = None
                self.gte_year = None
                self.eq_year = int(prompt[1:])
            elif prompt == "y":
                self.sort = "release_date"
                self.desc = True
            elif prompt == "Y":
                self.sort = "release_date"
                self.desc = False
            elif prompt == "t":
                self.sort = "title"
                self.desc = True
            elif prompt == "T":
                self.sort = "title"
                self.desc = False
            elif prompt == "S":
                self.select_mode ^= True
            elif prompt == "m":
                if monitored:
                    stop = True
                else:
                    stop = False
                record_type = self.filter or config.record_type()
                self.clear()
                monitor = mon.Monitor()
                monitor.set_config(None, None, record_type, None)
                monitor.set_options(stop, False, False)
                monitor.artist_ids([artist['id']])
            elif prompt == "f":
                if len(filtered_choices) > 0:
                    for item in filtered_choices:
                        self.send_to_queue(item)
                else:
                    self.status_message = "No items to add"
            elif prompt == "d":
                if len(self.queue_list) > 0:
                    self.start_queue()
            elif prompt == "Q":
                if len(self.queue_list) > 0:
                    self.queue_menu()
                else:
                    self.status_message = "Queue is empty"
            elif prompt == "b":
                break
            elif prompt == "":
                self.status_message = "Hint: to exit, type 'exit'!"
                continue
            elif prompt == "exit":
                if self.exit_search():
                    sys.exit()
            else:
                try:
                    selected_index = (int(prompt) - 1)
                except ValueError:
                    self.status_message = "Invalid filter, sort or option provided"
                    continue
                except IndexError:
                    self.status_message = "Invalid selection, please choose from above"
                    continue

                if selected_index in range(len(filtered_choices)):
                    if self.select_mode:
                        selected_item = filtered_choices[selected_index]
                        self.send_to_queue(selected_item)
                        continue
                    else:
                        self.track_menu(filtered_choices[selected_index])
                else:
                    self.status_message = "Invalid selection, please choose from above"
                    continue

    def track_menu_options(self):
        ui_options = ("(b) Back  (d) Download Queue  (Q) Show Queue")
        self.display_options(options=ui_options)

    def track_menu_header(self, album):
        print("deemon Interactive Search Client")
        print(f"Artist: {self.artist}  |  Album: {album['title']}\n")

    def track_menu(self, album):
        exit_track_menu: bool = False
        track_list = self.dz.api.get_album_tracks(album['id'])['data']
        self.select_mode = True
        while not exit_track_menu:
            self.clear()
            self.track_menu_header(album)

            for idx, track in enumerate(track_list, start=1):
                print(f"{self.item_selected(track['id'])}{idx}. {track['title']}")
            self.track_menu_options()

            prompt = input(f":: {self.show_mode()}Please choose an option or type 'exit'{self.show_mini_queue()}: ")
            if prompt == "d":
                if len(self.queue_list) > 0:
                    self.start_queue()
                else:
                    self.status_message = "Queue is empty"
            elif prompt == "Q":
                if len(self.queue_list) > 0:
                    self.queue_menu()
                else:
                    self.status_message = "Queue is empty"
            elif prompt == "b":
                self.select_mode = False
                break
            elif prompt == "":
                self.status_message = "Hint: to exit, type 'exit'!"
                continue
            elif prompt == "exit":
                if self.exit_search():
                    sys.exit()
            else:
                try:
                    selected_index = (int(prompt) - 1)
                except ValueError:
                    self.status_message = "Invalid filter, sort or option provided"
                    continue
                except IndexError:
                    self.status_message = "Invalid selection, please choose from above"
                    continue

                if selected_index in range(len(track_list)):
                    selected_item = track_list[selected_index]
                    selected_item['record_type'] = 'track'
                    self.send_to_queue(selected_item)
                    continue
                else:
                    self.status_message = "Invalid selection, please choose from above"
                    continue

    def search_header(self):
        pass

    def queue_menu(self):
        exit_queue_list = False
        while exit_queue_list is False:
            self.clear()
            for idx, q in enumerate(self.queue_list, start=1):
                if q.album_title:
                    print(f"{idx}. {q.artist_name} - {q.album_title}")
                else:
                    print(f"{idx}. {q.artist_name} - {q.track_title}")
            print("")
            self.queue_menu_options()
            response = input(f":: Please choose an option or type exit {self.show_mini_queue()}: ")
            if response == "d":
                if len(self.queue_list) > 0:
                    self.start_queue()
                else:
                    self.status_message = "Queue is empty"
            if response == "c":
                self.queue_list = []
                break
            if response == "b":
                break
            if response == "exit":
                if self.exit_search():
                    sys.exit()
            try:
                response = int(response) - 1
            except ValueError:
                continue
            if response in range(len(self.queue_list)):
                self.queue_list.pop(response)
                if len(self.queue_list) == 0:
                    break

    def exit_search(self):
        if len(self.queue_list) > 0:
            exit_all = input(":: Quit before downloading queue? [y|N] ")
            if exit_all.lower() != 'y':
                return False
        return True

    def display_options(self, filter=None, sort=None, mode=None, options=None):
        if filter:
            print(filter)
        if sort:
            print(sort)
        if mode:
            print(mode)
        if options:
            print("")
            print(options)
        if self.status_message:
            print("** " + self.status_message + " **")
            self.status_message = None

    @staticmethod
    def clear():
        from os import system, name
        if name == 'nt':
            _ = system('cls')
        else:
            _ = system('clear')

    def filter_choices(self, choices):
        apply_filter = [x for x in choices if x['record_type'] == self.filter or self.filter is None]
        if self.explicit_only:
            apply_filter = [x for x in apply_filter if x['explicit_lyrics'] > 0]

        if any([self.gte_year, self.lte_year, self.eq_year]):
            if self.eq_year:
                apply_filter = [x for x in apply_filter if dates.get_year(x['release_date']) == self.eq_year]
            elif self.gte_year and self.lte_year:
                apply_filter = [x for x in apply_filter if dates.get_year(x['release_date']) >= self.gte_year and dates.get_year(x['release_date']) <= self.lte_year]
            elif self.gte_year:
                apply_filter = [x for x in apply_filter if dates.get_year(x['release_date']) >= self.gte_year]
            elif self.lte_year:
                apply_filter = [x for x in apply_filter if dates.get_year(x['release_date']) <= self.lte_year]

        return sorted(apply_filter, key=lambda x: x[self.sort], reverse=self.desc)

    def start_queue(self):
        self.clear()
        dl = download.Download(active_api=self.api)
        dl.queue_list = self.queue_list
        download_result = dl.download_queue()
        self.queue_list.clear()
        if download_result:
            self.status_message = "Downloads complete"
        else:
            self.status_message = "Downloads failed, please check logs"

    def send_to_queue(self, item):
        if item['record_type'] in ['album', 'ep', 'single']:
            album = {
                'id': item['id'],
                'title': item['title'],
                'link': item['link'],
                'artist': {
                    'name': self.artist
                }
            }
            for i, q in enumerate(self.queue_list):
                if q.album_id == album['id']:
                    del self.queue_list[i]
                    return
            self.queue_list.append(download.QueueItem(album=album))
        elif item['record_type'] == 'track':
            track = {
                'id': item['id'],
                'title': item['title'],
                'link': item['link'],
                'artist': {
                    'name': self.artist
                }
            }
            for i, q in enumerate(self.queue_list):
                if q.track_id == track['id']:
                    del self.queue_list[i]
                    return

            self.queue_list.append(download.QueueItem(track=track))

        else:
            logger.error("Unknown record type. Please report this to add support:")
            logger.error(item)


================================================
FILE: deemon/cmd/show.py
================================================
import csv
import logging
import os
import time
from pathlib import Path
from typing import Union

from deemon.core.db import Database
from deemon.utils.dates import generate_date_filename

logger = logging.getLogger(__name__)


class Show:

    def __init__(self):
        self.db = Database()

    def monitoring(self, artist: bool = True, query: str = None, export_csv: bool = False,
                   save_path: Union[str, Path] = None, filter: str = None, hide_header: bool = False,
                   is_id: bool = False, backup: Union[str, Path] = None):

        def csv_output(line: str):
            if save_path:
                output_to_file.append(line)
            else:
                print(line)

        output_to_file = []

        if backup:
            export_csv = True
            filter = "id"
            hide_header = True
            save_path = backup

        if artist:
            if query:
                db_result = self.db.get_monitored_artist_by_name(query)
            else:
                db_result = self.db.get_all_monitored_artists()

            if not db_result:
                if query:
                    return logger.error("Artist not found: " + str(query))
                else:
                    return logger.error("No artists are being monitored")
        else:
            if query:
                if is_id:
                    try:
                        query = int(query)
                    except ValueError:
                        return logger.error(f"Invalid Playlist ID - {query}")
                    db_result = self.db.get_monitored_playlist_by_id(query)
                else:
                    db_result = self.db.get_monitored_playlist_by_name(query)
            else:
                db_result = self.db.get_all_monitored_playlists()

            if not db_result:
                if query:
                    return logger.error("Playlist/ID not found: " + str(query))
                else:
                    return logger.error("No playlists are being monitored")

        if artist and query:
            for key, val in db_result.items():
                if val == None:
                    db_result[key] = "-"

            print("{:<10} {:<35} {:<10} {:<10} {:<10} {:<25}".format('ID', 'Artist', 'Alerts',
                                                                     'Bitrate', 'Type', 'Download Path'))

            print("{!s:<10} {!s:<35} {!s:<10} {!s:<10} {!s:<10} {!s:<25}".format(db_result['artist_id'],
                                                                                 db_result['artist_name'],
                                                                                 db_result['alerts'],
                                                                                 db_result['bitrate'],
                                                                                 db_result['record_type'],
                                                                                 db_result['download_path']))
            print("")
        elif not artist and query:
            for key, val in db_result.items():
                if val == None:
                    db_result[key] = "-"

            print("{:<15} {:<30} {:<50} {:<10} {:<10} {:<25}".format('ID', 'Title', 'URL', 'Alerts',
                                                                     'Bitrate', 'Download Path'))

            print("{!s:<15} {!s:<30} {!s:<50}  {!s:<10} {!s:<10} {!s:<25}".format(db_result['id'], db_result['title'],
                                                                                  db_result['url'], db_result['alerts'],
                                                                                  db_result['bitrate'],
                                                                                  db_result['download_path']))
            print("")
        else:
            if export_csv or save_path:
                if artist:
                    if not filter:
                        filter = "name,id,bitrate,alerts,type,path"
                    filter = filter.split(',')
                    logger.debug(f"Generating CSV data using filters: {', '.join(filter)}")
                    column_names = ['artist_id' if x == 'id' else x for x in filter]
                    column_names = ['artist_name' if x == 'name' else x for x in column_names]
                    column_names = ['record_type' if x == 'type' else x for x in column_names]
                    column_names = ['download_path' if x == 'path' else x for x in column_names]
                else:
                    if not filter:
                        filter = "id,title,url,bitrate,alerts,path"
                    filter = filter.split(',')
                    logger.debug(f"Generating CSV data using filters: {', '.join(filter)}")
                    column_names = ['download_path' if x == 'path' else x for x in filter]

                for column in column_names:
                    if not len([x for x in db_result if column in x.keys()]):
                        logger.warning(f"Unknown filter specified: {column}")
                        column_names.remove(column)

                if not hide_header:
                    csv_output(','.join(filter))
                for artist in db_result:
                    filtered_artists = []
                    for key, value in artist.items():
                        if value is None:
                            artist[key] = ""
                    for column in column_names:
                        filtered_artists.append(str(artist[column]))
                    if len(filtered_artists):
                        for i, a in enumerate(filtered_artists):
                            if '"' in a:
                                a = a.replace('"', "'")
                            if ',' in a:
                                filtered_artists[i] = f'"{a}"'
                        csv_output(",".join(filtered_artists))

                if output_to_file:
                    if Path(save_path).is_dir():
                        output_filename = Path(save_path / f"{generate_date_filename('deemon_')}.csv")
                    else:
                        output_filename = Path(save_path)

                    with open(output_filename, 'w', encoding="utf-8") as f:
                        for line in output_to_file:
                            if line == output_to_file[-1]:
                                f.writelines(line)
                                break
                            f.writelines(line + "\n")

                    return logger.info("CSV data has been saved to: " + str(output_filename))

                return

            if artist:
                db_result = [x['artist_name'] for x in db_result]
            else:
                db_result = [x['title'] for x in db_result]
            if len(db_result) < 10:
                for artist in db_result:
                    print(artist)
            else:
                db_result = self.truncate_long_artists(db_result)

                try:
                    size = os.get_terminal_size()
                    max_cols = (int(size.columns / 30))
                except:
                    max_cols = 5
                    
                if max_cols > 5:
                    max_cols = 5

                while len(db_result) % max_cols != 0:
                    db_result.append(" ")

                if max_cols >= 5:
                    for a, b, c, d, e in zip(db_result[0::5], db_result[1::5], db_result[2::5], db_result[3::5],
                                             db_result[4::5]):
                        print('{:<30}{:<30}{:<30}{:<30}{:<30}'.format(a, b, c, d, e))
                elif max_cols >= 4:
                    for a, b, c, d in zip(db_result[0::4], db_result[1::4], db_result[2::4], db_result[3::4]):
                        print('{:<30}{:<30}{:<30}{:<30}'.format(a, b, c, d))
                elif max_cols >= 3:
                    for a, b, c in zip(db_result[0::3], db_result[1::3], db_result[2::3]):
                        print('{:<30}{:<30}{:<30}'.format(a, b, c))
                elif max_cols >= 2:
                    for a, b in zip(db_result[0::2], db_result[1::2]):
                        print('{:<30}{:<30}'.format(a, b))
                else:
                    for a in db_result:
                        print(a)

    def playlists(self, csv=False):
        monitored_playlists = self.db.get_all_monitored_playlists()
        for p in monitored_playlists:
            print(f"{p[1]} ({p[2]})")

    @staticmethod
    def truncate_long_artists(all_artists):
        for idx, artist in enumerate(all_artists):
            if len(artist) > 25:
                all_artists[idx] = artist[:22] + "..."
            all_artists[idx] = artist
        return all_artists

    def releases(self, days, future):
        if future:
            future_releases = self.db.get_future_releases()
            future_release_list = [x for x in future_releases]
            if len(future_release_list) > 0:
                logger.info(f"Future releases:")
                print("")
                future_release_list.sort(key=lambda x: x['album_release'], reverse=True)
                for release in future_release_list:
                    print('+ [%-10s] %s - %s' % (release['album_release'], release['artist_name'], release['album_name']))
            else:
                logger.info("No future releases have been detected")
        else:
            seconds_per_day = 86400
            days_in_seconds = (days * seconds_per_day)
            now = int(time.time())
            back_date = (now - days_in_seconds)
            releases = self.db.show_new_releases(back_date, now)
            release_list = [x for x in releases]
            if len(release_list) > 0:
                logger.info(f"New releases found within last {days} day(s):")
                print("")
                release_list.sort(key=lambda x: x['album_release'], reverse=True)
                for release in release_list:
                    print('+ [%-10s] %s - %s' % (release['album_release'], release['artist_name'], release['album_name']))
            else:
                logger.info(f"No releases found in the last {days} day(s)")


================================================
FILE: deemon/cmd/upgradelib.py
================================================
import sys
import time
import logging
from datetime import timedelta
from pathlib import Path
from mutagen.easyid3 import EasyID3
from itertools import groupby
from operator import itemgetter
from deezer import Deezer
from concurrent.futures import ThreadPoolExecutor
from unidecode import unidecode
from tqdm import tqdm
from deemon.core.common import exclude_filtered_versions
from deemon.core.config import Config as config

logger = logging.getLogger(__name__)

dz = Deezer()

LIBRARY_ROOT = None
ALBUM_ONLY = None
ALLOW_EXCLUSIONS = None

# TODO - Add an 'exclusions' key to albums/tracks for count
# TODO - to improve album title matching, extract all a-zA-Z0-9 and compare (remove special chars)

library_metadata = []
performance = {
    'startID3': 0,
    'endID3': 0,
    'completeID3': 0,
    'startAPI': 0,
    'endAPI': 0,
    'completeAPI': 0
}


class Performance:
    def __init__(self):
        self.startID3 = 0
        self.endID3 = 0
        self.completeID3 = 0
        self.startAPI = 0
        self.endAPI = 0
        self.completeAPI = 0

    def start(self, module: str):
        if module == 'ID3':
            self.startID3 = time.time()
        elif module == 'API':
            self.startAPI = time.time()

    def end(self, module: str):
        if module == 'ID3':
            self.endID3 = time.time()
            self.completeID3 = self.endID3 - self.startID3
        elif module == 'API':
            self.endAPI = time.time()
            self.completeAPI = self.endAPI - self.startAPI


def read_metadata(file):
    metadata = {
        'abs_path': file,
        'rel_path': str(file).replace(LIBRARY_ROOT, ".."),
        'error': None
    }

    try:
        _audio = EasyID3(file)

        # Remove featured artists from artist tag
        metadata['artist'] = _audio['artist'][0].split("/")[0].strip()

        # Remove special character replacement for search query
        metadata['album'] = _audio['album'][0].replace("_", " ").strip()
        metadata['title'] = _audio['title'][0].strip()
    except Exception as e:
        metadata['error'] = e

    return metadata


def get_time_from_secs(secs):
    td_str = str(timedelta(seconds=secs))
    x = td_str.split(":")
    x[2] = x[2].split(".")[0]

    if x[0] != "0":
        friendly_time = f"{x[0]} Hours {x[1]} Minutes {x[2]} Seconds"
    elif x[1] != "00":
        friendly_time = f"{x[1]} Minutes {x[2]} Seconds"
    elif x[2] == "00":
        friendly_time = f"Less than 1 second"
    else:
        friendly_time = f"{x[2]} Seconds"

    return friendly_time


def invalid_metadata(track: dict) -> bool:
    if not all([track['artist'], track['album'], track['title']]):
        return True
    else:
        return False


def get_artist_api(name: str) -> list:
    """ Get list of artists with exact name matches from API """
    artist_api = dz.gw.search(name)['ARTIST']['data']
    artist_matches = []

    for artist in artist_api:
        if artist['ART_NAME'].lower() == name.lower():
            artist_matches.append(artist)

    return artist_matches


def get_artist_discography_api(artist_name, artist_id) -> list:
    """ Get list of albums with exact name matches from API """
    album_search = dz.gw.search(artist_name)['ALBUM']['data']
    album_gw = dz.gw.get_artist_discography(artist_id)['data']
    album_api = dz.api.get_artist_albums(artist_id)['data']

    albums = []

    for album in album_api:
        if album['record_type'] == 'single':
            album['record_type'] = '0'
        elif album['record_type'] == 'album':
            album['record_type'] = '1'
        elif album['record_type'] == 'compilation':
            album['record_type'] = '2'
        elif album['record_type'] == 'ep':
            album['record_type'] = '3'

        if album['explicit_lyrics']:
            album['explicit_lyrics'] = '1'
        else:
            album['explicit_lyrics'] = '0'

        alb = {
            'ALB_ID': str(album['id']),
            'ALB_TITLE': album['title'],
            'EXPLICIT_LYRICS': album['explicit_lyrics'],
            'TYPE': album['record_type']
        }
        albums.append(alb)

    for album in album_gw:
        if album['ALB_ID'] not in [x['ALB_ID'] for x in albums]:
            albums.append(album)

    for album in album_search:
        if album['ART_ID'] == artist_id:
            if album['ALB_ID'] not in [x['ALB_ID'] for x in albums]:
                # Album returned via Search is missing EXPLICIT_LYRICS key
                if not album.get('EXPLICIT_LYRICS'):
                    album['EXPLICIT_LYRICS'] = '0'
                albums.append(album)

    return albums


def get_album_tracklist_api(album_id: str) -> list:
    """ Get tracklist for album based on album_id """
    tracklist_api = dz.gw.get_album_tracks(album_id)
    return tracklist_api


def retrieve_track_ids_per_artist(discography: tuple):
    artist = discography[0]
    albums = discography[1]

    # TODO - Need to implement this
    duplicate_artists = False
    found_artist = False

    track_ids = []
    album_ids = []

    api_artists = get_artist_api(artist)

    tqdm.write(f"Getting track IDs for tracks by \"{artist}\"")

    if len(api_artists):
        if len(api_artists) > 1:
            tqdm.write(f"Duplicate artists detected for \"{artist}\"")
            duplicate_artists = True

        for api_artist in api_artists:

            if found_artist:
                tqdm.write("Found correct artist, skipping duplicates")
                break

            if duplicate_artists:
                tqdm.write(f"Searching with: {api_artist['ART_NAME']} ({api_artist['ART_ID']})")

            discog = get_artist_discography_api(api_artist['ART_NAME'], api_artist['ART_ID'])

            for album, tracks in groupby(albums, key=itemgetter('album')):

                # Convert itertools.groupby to list so we can use it more than once
                tracks = [track for track in tracks]

                api_album_matches = [alb for alb in discog if alb['ALB_TITLE'].lower() == album.lower()]

                if ALLOW_EXCLUSIONS:
                    filtered_album_matches = exclude_filtered_versions(api_album_matches)
                    api_album = get_preferred_album(filtered_album_matches, len(tracks))
                else:
                    api_album = get_preferred_album(api_album_matches, len(tracks))

                if ALBUM_ONLY:
                    if api_album:
                        album_ids.append(api_album)
                        continue
                    else:
                        album_ids.append(
                            {
                                'artist': artist,
                                'title': album,
                                'info': "Album not found"
                            }
                        )
                        continue

                if api_album:
                    tracklist = get_album_tracklist_api(api_album['ALB_ID'])
                    for track in tracks:
                        track_variations = [track['title'].lower(), unidecode(track['title']).lower()]

                        for i, track_api in enumerate(tracklist, start=1):
                            if track_api['SNG_TITLE'].lower() in track_variations:
                                found_artist = True
                                track['id'] = track_api['SNG_ID']
                                track_ids.append(track)
                                break

                            elif f"{track_api['SNG_TITLE']} {track_api.get('VERSION', '')}".lower() in track_variations:
                                found_artist = True
                                track['id'] = track_api['SNG_ID']
                                track_ids.append(track)
                                break

                            if i == len(tracklist):
                                track['info'] = "Track not found"
                                tqdm.write(f"{track['info']}: {track['title']}")
                                track_ids.append(track)
                                break
                else:
                    if duplicate_artists:
                        info = f"Album not found under artist ID {api_artist['ART_ID']}"
                    else:
                        info = f"Album not found"
                    tqdm.write(f"{info}: {album}")
                    for track in tracks:
                        track['info'] = info
                        track_ids.append(track)
    else:
        tqdm.write(f"Artist not found: {artist}")
        for album, tracks in groupby(albums, key=itemgetter('album')):
            for track in tracks:
                track['info'] = "Artist not found"
                track_ids.append(track)

    if ALBUM_ONLY:
        return album_ids
    else:
        return track_ids


def get_preferred_album(api_albums: list, num_tracks: int):
    """ Return preferred album order based on config.prefer_explicit() """
    preferred_album = None

    if num_tracks < 4:
        preferred_album = [album for album in api_albums if album['EXPLICIT_LYRICS'] == '1' and album['TYPE'] == '0']
        if not preferred_album:
            preferred_album = [album for album in api_albums if album['TYPE'] == '0']

    if num_tracks >= 4 or not preferred_album:
        preferred_album = [album for album in api_albums if album['EXPLICIT_LYRICS'] == '1' and album['TYPE'] in ['1', '2', '3']]
        if not preferred_album:
            preferred_album = [album for album in api_albums if album['TYPE'] in ['1', '2', '3']]

    if preferred_album:
        return preferred_album[0]


def get_preferred_track_id(title: str, tracklist: list):
    """ Return preferred track ID by comparing against title of local track """
    track_id = None
    for track in tracklist:
        if track.get('VERSION'):
            api_title = f"{track['SNG_TITLE']} {track['VERSION']}".lower()
            if title.lower() == api_title:
                return track['SNG_ID']
        else:
            if track['SNG_TITLE'].lower() == title.lower():
                track_id = track['SNG_ID']
    return track_id


def upgrade(library, output, albums=False, exclusions=False):

    global ALBUM_ONLY
    global ALLOW_EXCLUSIONS
    global LIBRARY_ROOT

    ALBUM_ONLY = albums
    ALLOW_EXCLUSIONS = exclusions
    LIBRARY_ROOT = library

    output_ids = Path(output) / "library_upgrade_ids.txt"
    output_log = Path(output) / "library_upgrade.log"

    perf = Performance()
    logger.info("Scanning library, standby...")
    logger.debug(f"Library path: {LIBRARY_ROOT}")
    library_files = Path(LIBRARY_ROOT).glob("**/*.mp3")
    files = [file for file in library_files if not file.name.startswith(".")]
    files.sort()

    if files:
        print(f"Found {len(files)} MP3 files")
    else:
        print("No MP3 files found")
        sys.exit()

    perf.start('ID3')
    with ThreadPoolExecutor(10) as executor:
        library_metadata = list(
            tqdm(
                executor.map(read_metadata, files),
                total=(len(files)),
                desc="Reading metadata",
            )
        )
    perf.end('ID3')

    library_metadata_errors = [file for file in library_metadata if file.get('error')]
    library_metadata = [file for file in library_metadata if not file.get('error')]

    artists = sorted(library_metadata, key=itemgetter('artist'))
    artist_list = [(artist, list(albums)) for artist, albums in groupby(artists, key=itemgetter('artist'))]

    perf.start('API')
    with ThreadPoolExecutor(20) as executor:
        result = list(
            tqdm(
                executor.map(retrieve_track_ids_per_artist, artist_list),
                total=len(artist_list),
                desc="Processing tracks by artist"
            )
        )
        if ALBUM_ONLY:
            album_result = result
            track_result = []
        else:
            track_result = result
            album_result = []
    perf.end('API')

    albums = [album for artist in album_result for album in artist]
    album_ids = [album['ALB_ID'] for album in albums if album.get('ALB_ID')]
    album_not_found = [album for album in albums if not album.get('ALB_ID')]

    tracks = [track for artist in track_result for track in artist]
    track_ids = [track['id'] for track in tracks if track.get('id') and not track.get('error')]
    track_not_found = [track for track in tracks if not track.get('id') and not track.get('error')]

    # TODO move this to function for reuse in f.write() below
    print(f"Found: {len(track_ids)} | Not Found: {len(track_not_found)} | "
          f"Errors: {len(library_metadata_errors)} | Total: {len(files)}\n\n")
    print(f"Time to read metadata: {get_time_from_secs(perf.completeID3)}")
    print(f"Time to retrieve API data: {get_time_from_secs(perf.completeAPI)}\n\n")

    if (ALBUM_ONLY and album_ids) or track_ids:
        with open(output_ids, "w") as f:
            if ALBUM_ONLY and album_ids:
                f.write(', '.join(album_ids))
            elif track_ids:
                f.write(', '.join(track_ids))

    with open(output_log, "w") as f:
        if ALBUM_ONLY:
            f.write(f"Albums Found: {len(album_ids)} | Albums Not Found: {len(album_not_found)} | "
                    f"ID3 Errors: {len(library_metadata_errors)} | Total Files: {len(files)}\n\n")
            f.write(f"Time to read metadata: {get_time_from_secs(perf.completeID3)}\n")
            f.write(f"Time to retrieve API data: {get_time_from_secs(perf.completeAPI)}\n\n")

            if library_metadata_errors:
                f.write("The following files had missing/invalid ID3 tag data:\n\n")
                for track in library_metadata_errors:
                    if track.get('error'):
                        f.write(f"\tFile: {track['rel_path']}\n")
                        f.write(f"\t\tError: {track['error']}\n\n")
                f.write("\n")

            if album_not_found:

                artists_not_found = [track['artist'] for track in tracks if track['info'] == 'Artist not found']
                if artists_not_found:
                    f.write("The following artists were not found:\n")
                    for artist in artists_not_found:
                        f.write("\n\t{track['artist']\n")

                f.write("The following albums were not found:\n")
                for album in album_not_found:
                    f.write(f"\n\tArtist: {album['artist']}\n")
                    f.write(f"\tAlbum: {album['title']}\n")
                    if album.get('info'):
                        f.write(f"\tInfo: {album['info']}\n")
        else:
            f.write(f"Tracks Found: {len(track_ids)} | Tracks Not Found: {len(track_not_found)} | "
                    f"ID3 Errors: {len(library_metadata_errors)} | Total Files: {len(files)}\n\n")
            f.write(f"Time to read metadata: {get_time_from_secs(perf.completeID3)}\n")
            f.write(f"Time to retrieve API data: {get_time_from_secs(perf.completeAPI)}\n\n")

            if library_metadata_errors:
                f.write("The following files had missing/invalid ID3 tag data:\n\n")
                for track in library_metadata_errors:
                    if track.get('error'):
                        f.write(f"\tFile: {track['rel_path']}\n")
                        f.write(f"\t\tError: {track['error']}\n\n")
                f.write("\n")

            if track_not_found:

                artists_not_found = [track['artist'] for track in tracks if track.get('info', '') == 'Artist not found']
                if artists_not_found:
                    f.write("The following artists were not found:\n")
                    for artist in artists_not_found:
                        f.write("\n\t{track['artist']\n")

                f.write("The following tracks were not found:\n")
                for track in track_not_found:
                    f.write(f"\n\tArtist: {track['artist']}\n")
                    f.write(f"\tAlbum: {track['album']}\n")
                    f.write(f"\tTrack: {track['title']}\n")
                    f.write(f"\tFile: {track['rel_path']}\n")
                    if track.get('info'):
                        f.write(f"\tInfo: {track['info']}\n")

================================================
FILE: deemon/core/__init__.py
================================================


================================================
FILE: deemon/core/api.py
================================================
import json
import logging
from datetime import datetime

import deezer.errors
from deezer import Deezer

from deemon.core.config import Config as config

logger = logging.getLogger(__name__)


class PlatformAPI:

    def __init__(self):
        self.max_threads = 2
        self.dz = Deezer()
        self.platform = self.get_platform()
        self.account_type = None
        self.api = self.set_platform()
        
        if config.check_account_status():
            self.account_type = self.get_account_type()

    def debugger(self, message: str, payload = None):
        if config.debug_mode():
            if not payload:
                payload = ""
            logger.debug(f"DEBUG_MODE: {message} {str(payload)}")
            
    def get_platform(self):
        if config.fast_api():
            return "deezer-gw"
        return "deezer-api"

    def set_platform(self):
        if self.platform == "deezer-gw":
                self.max_threads = config.fast_api_threads()
                if self.max_threads > 50:
                    self.max_threads = 50
                if self.max_threads < 1:
                    self.max_threads = 1
                logger.debug("Using GW API, max_threads set "
                             f"to {self.max_threads}")
                return self.dz.gw
        else:
            return self.dz.api
        
    def get_account_type(self):
        logger.info("Verifying ARL, please wait...")
        temp_dz = Deezer()
        temp_dz.login_via_arl(config.arl())
        if temp_dz.get_session()['current_user'].get('can_stream_lossless'):
            logger.debug(f"Deezer account type is \"Hi-Fi\"")
            return "hifi"
        elif temp_dz.get_session()['current_user'].get('can_stream_hq'):
            logger.debug(f"Deezer account type is \"Premium\"")
            return "premium"
        else:
            logger.debug(f"Deezer account type is \"Free\"")
            return "free"

    #TODO GW API appears to ignore limit; must implement afterwards
    def search_artist(self, query: str, limit: int = 5):
        """
        Return a list of dictionaries from API containing {'id': int, 'name': str}
        """
        if self.platform == "deezer-gw":
            api_result = []
            try:
                logger.info(f"Searching for {query}, please wait...")
                result = self.api.search(query=query)['ARTIST']['data'][:limit]
            except json.decoder.JSONDecodeError:
                logger.error(f"   [!] Empty response from API while searching for artist {query}, retrying...")
                try:
                    result = self.api.search(query=query)['ARTIST']['data'][:limit]
                except json.decoder.JSONDecodeError:
                    logger.error(f"   [!] API still sending empty response while searching for artist {query}")
                    return []
            for r in result:
                api_result.app
Download .txt
gitextract_dh1lrv7v/

├── .github/
│   └── workflows/
│       ├── deploy-docker.yml
│       ├── discord-release-msg.yml
│       ├── purge-old-betas.yml
│       └── python-publish.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── README.md
├── deemon/
│   ├── __init__.py
│   ├── __main__.py
│   ├── assets/
│   │   └── index.html
│   ├── cli.py
│   ├── cmd/
│   │   ├── __init__.py
│   │   ├── artistconfig.py
│   │   ├── backup.py
│   │   ├── download.py
│   │   ├── extra.py
│   │   ├── generate.py
│   │   ├── monitor.py
│   │   ├── profile.py
│   │   ├── refresh.py
│   │   ├── rollback.py
│   │   ├── search.py
│   │   ├── show.py
│   │   └── upgradelib.py
│   ├── core/
│   │   ├── __init__.py
│   │   ├── api.py
│   │   ├── common.py
│   │   ├── config.py
│   │   ├── db.py
│   │   ├── dmi.py
│   │   ├── exceptions.py
│   │   ├── logger.py
│   │   └── notifier.py
│   └── utils/
│       ├── __init__.py
│       ├── dataprocessor.py
│       ├── dates.py
│       ├── performance.py
│       ├── startup.py
│       ├── ui.py
│       └── validate.py
├── docs/
│   ├── _config.yml
│   ├── _sass/
│   │   └── custom/
│   │       └── custom.scss
│   ├── docs/
│   │   ├── automations/
│   │   │   ├── automations.md
│   │   │   ├── cron.md
│   │   │   └── task-scheduler.md
│   │   ├── commands/
│   │   │   ├── backup.md
│   │   │   ├── commands.md
│   │   │   ├── config.md
│   │   │   ├── download.md
│   │   │   ├── library.md
│   │   │   ├── monitor.md
│   │   │   ├── profile.md
│   │   │   ├── refresh.md
│   │   │   ├── reset.md
│   │   │   ├── rollback.md
│   │   │   ├── search.md
│   │   │   ├── show.md
│   │   │   └── test.md
│   │   ├── configuration.md
│   │   ├── installation.md
│   │   └── troubleshooting/
│   │       ├── logs.md
│   │       ├── queue.md
│   │       └── troubleshooting.md
│   └── index.md
├── requirements.txt
└── setup.py
Download .txt
SYMBOL INDEX (330 symbols across 28 files)

FILE: deemon/__main__.py
  function main (line 4) | def main():

FILE: deemon/cli.py
  function run (line 39) | def run(whats_new, init, arl, verbose, profile):
  function test (line 132) | def test(email, exclusions):
  function download_command (line 159) | def download_command(artist, artist_id, album_id, url, file, bitrate,
  function monitor_command (line 216) | def monitor_command(artist, im, playlist, include_artists, bitrate, reco...
  function refresh_command (line 285) | def refresh_command(name, playlist, skip_download, time_machine):
  function show_command (line 306) | def show_command():
  function show_artists (line 319) | def show_artists(artist, csv, export, filter, hide_header, backup):
  function show_artists (line 335) | def show_artists(title, playlist_id, csv, filter, hide_header):
  function show_releases (line 347) | def show_releases(n, future):
  function backup_command (line 361) | def backup_command(restore, include_logs):
  function api_test (line 378) | def api_test(artist, artist_id, album_id, playlist_id, limit, raw):
  function reset_db (line 424) | def reset_db():
  function profile_command (line 442) | def profile_command(profile, add, clear, delete, edit):
  function extra_command (line 462) | def extra_command():
  function search (line 469) | def search(query):
  function config_command (line 480) | def config_command(artist):
  function rollback_command (line 489) | def rollback_command(num, view):
  function library_command (line 498) | def library_command():
  function library_upgrade_command (line 509) | def library_upgrade_command(library, output, album_only, allow_exclusions):

FILE: deemon/cmd/artistconfig.py
  function print_header (line 10) | def print_header(message: str = None):
  function get_artist (line 23) | def get_artist(query: str):
  function artist_lookup (line 63) | def artist_lookup(query):

FILE: deemon/cmd/backup.py
  function run (line 16) | def run(include_logs: bool = False):
  function restore (line 33) | def restore():

FILE: deemon/cmd/download.py
  class QueueItem (line 24) | class QueueItem:
    method __init__ (line 26) | def __init__(self, artist=None, album=None, track=None, playlist=None,
  function get_deemix_bitrate (line 82) | def get_deemix_bitrate(bitrate: str):
  function get_plex_server (line 89) | def get_plex_server():
  function refresh_plex (line 108) | def refresh_plex(plexobj):
  class Download (line 120) | class Download:
    method __init__ (line 122) | def __init__(self, active_api=None):
    method set_dates (line 135) | def set_dates(self, from_date: str = None, to_date: str = None) -> None:
    method download_queue (line 149) | def download_queue(self, queue_list: list = None):
    method download (line 250) | def download(self, artist, artist_id, album_id, url,

FILE: deemon/cmd/extra.py
  function debugger (line 13) | def debugger(message: str, payload = None):
  function main (line 20) | def main():

FILE: deemon/cmd/generate.py
  function read_album_ids_from_file (line 7) | def read_album_ids_from_file(filename):
  function clean_absolute_paths (line 19) | def clean_absolute_paths(album_list):
  function clean_year_from_album (line 26) | def clean_year_from_album(album_list, level: int = 5):
  function clean_artist_album_text (line 40) | def clean_artist_album_text(album_list: list):
  function get_artist_album (line 55) | def get_artist_album(filename: str, absolute_path: bool = False):
  function get_api_results (line 66) | def get_api_results(album_list, artist_name: str = None):

FILE: deemon/cmd/monitor.py
  class Monitor (line 17) | class Monitor:
    method __init__ (line 19) | def __init__(self, active_api=None):
    method set_config (line 33) | def set_config(self, bitrate: str, alerts: bool, record_type: str, dow...
    method set_options (line 40) | def set_options(self, remove, dl_all, search):
    method debugger (line 46) | def debugger(self, message: str, payload=None):
    method get_best_result (line 52) | def get_best_result(self, api_result) -> list:
    method prompt_search (line 96) | def prompt_search(self, value, api_result):
    method build_artist_query (line 104) | def build_artist_query(self, api_result: list):
    method build_playlist_query (line 126) | def build_playlist_query(self, api_result: list, include_artists: bool):
    method call_refresh (line 159) | def call_refresh(self):
    method artists (line 164) | def artists(self, names: list) -> None:
    method artist_ids (line 194) | def artist_ids(self, ids: list):
    method importer (line 212) | def importer(self, import_path: str):
    method playlists (line 229) | def playlists(self, playlists: list, include_artists: bool):
    method purge_artists (line 247) | def purge_artists(self, names: list = None, ids: list = None):
    method purge_playlists (line 265) | def purge_playlists(self, titles: list = None, ids: list = None):

FILE: deemon/cmd/profile.py
  class ProfileConfig (line 9) | class ProfileConfig:
    method __init__ (line 10) | def __init__(self, profile_name):
    method print_header (line 17) | def print_header(message: str = None):
    method edit (line 24) | def edit(self):
    method add (line 70) | def add(self):
    method delete (line 121) | def delete(self):
    method show (line 136) | def show(self):
    method clear (line 156) | def clear(self):

FILE: deemon/cmd/refresh.py
  class Refresh (line 17) | class Refresh:
    method __init__ (line 18) | def __init__(self, time_machine: datetime = None, skip_download: bool ...
    method debugger (line 41) | def debugger(message: str, payload = None):
    method remove_existing_releases (line 47) | def remove_existing_releases(self, payload: dict, seen: dict) -> list:
    method filter_artist_releases (line 75) | def filter_artist_releases(self, payload: dict):
    method append_database_release (line 124) | def append_database_release(self, new_release: dict):
    method explicit_id (line 128) | def explicit_id(release_title: str, payload: list):
    method release_too_old (line 134) | def release_too_old(self, release_date: str):
    method is_future_release (line 147) | def is_future_release(release_date: str):
    method allowed_record_type (line 156) | def allowed_record_type(artist_rec_type, release_rec_type: str):
    method queue_release (line 169) | def queue_release(self, release: dict):
    method filter_playlist_releases (line 177) | def filter_playlist_releases(self, payload: dict):
    method waiting_for_refresh (line 193) | def waiting_for_refresh(self):
    method prep_payload (line 199) | def prep_payload(self, p):
    method run (line 206) | def run(self, artists: list = None, playlists: list = None):
    method db_stats (line 302) | def db_stats(self):
    method get_release_data (line 315) | def get_release_data(self, to_refresh: dict) -> dict:
    method create_notification (line 351) | def create_notification(self, release: dict):

FILE: deemon/cmd/rollback.py
  function view_transactions (line 10) | def view_transactions():
  function rollback_last (line 84) | def rollback_last(i: int):

FILE: deemon/cmd/search.py
  class Search (line 15) | class Search:
    method __init__ (line 16) | def __init__(self, active_api=None):
    method truncate_artist (line 39) | def truncate_artist(name: str):
    method get_latest_release (line 44) | def get_latest_release(self, artist_id: int):
    method display_monitored_status (line 53) | def display_monitored_status(self, artist_id: int):
    method has_duplicate_artists (line 59) | def has_duplicate_artists(name: str, artist_dicts: dict):
    method show_mini_queue (line 64) | def show_mini_queue(self):
    method search_menu (line 70) | def search_menu(self, query: str = None):
    method queue_menu_options (line 128) | def queue_menu_options(self):
    method artist_menu (line 132) | def artist_menu(self, query: str, results: dict, artist_only: bool = F...
    method get_filtered_year (line 188) | def get_filtered_year(self):
    method album_menu_header (line 200) | def album_menu_header(self, artist: str):
    method album_menu_options (line 210) | def album_menu_options(self, monitored):
    method explicit_lyrics (line 224) | def explicit_lyrics(is_explicit):
    method item_selected (line 230) | def item_selected(self, id):
    method show_mode (line 239) | def show_mode(self):
    method album_menu (line 244) | def album_menu(self, artist: dict):
    method track_menu_options (line 357) | def track_menu_options(self):
    method track_menu_header (line 361) | def track_menu_header(self, album):
    method track_menu (line 365) | def track_menu(self, album):
    method search_header (line 416) | def search_header(self):
    method queue_menu (line 419) | def queue_menu(self):
    method exit_search (line 453) | def exit_search(self):
    method display_options (line 460) | def display_options(self, filter=None, sort=None, mode=None, options=N...
    method clear (line 475) | def clear():
    method filter_choices (line 482) | def filter_choices(self, choices):
    method start_queue (line 499) | def start_queue(self):
    method send_to_queue (line 510) | def send_to_queue(self, item):

FILE: deemon/cmd/show.py
  class Show (line 14) | class Show:
    method __init__ (line 16) | def __init__(self):
    method monitoring (line 19) | def monitoring(self, artist: bool = True, query: str = None, export_cs...
    method playlists (line 191) | def playlists(self, csv=False):
    method truncate_long_artists (line 197) | def truncate_long_artists(all_artists):
    method releases (line 204) | def releases(self, days, future):

FILE: deemon/cmd/upgradelib.py
  class Performance (line 38) | class Performance:
    method __init__ (line 39) | def __init__(self):
    method start (line 47) | def start(self, module: str):
    method end (line 53) | def end(self, module: str):
  function read_metadata (line 62) | def read_metadata(file):
  function get_time_from_secs (line 84) | def get_time_from_secs(secs):
  function invalid_metadata (line 101) | def invalid_metadata(track: dict) -> bool:
  function get_artist_api (line 108) | def get_artist_api(name: str) -> list:
  function get_artist_discography_api (line 120) | def get_artist_discography_api(artist_name, artist_id) -> list:
  function get_album_tracklist_api (line 166) | def get_album_tracklist_api(album_id: str) -> list:
  function retrieve_track_ids_per_artist (line 172) | def retrieve_track_ids_per_artist(discography: tuple):
  function get_preferred_album (line 275) | def get_preferred_album(api_albums: list, num_tracks: int):
  function get_preferred_track_id (line 293) | def get_preferred_track_id(title: str, tracklist: list):
  function upgrade (line 307) | def upgrade(library, output, albums=False, exclusions=False):

FILE: deemon/core/api.py
  class PlatformAPI (line 13) | class PlatformAPI:
    method __init__ (line 15) | def __init__(self):
    method debugger (line 25) | def debugger(self, message: str, payload = None):
    method get_platform (line 31) | def get_platform(self):
    method set_platform (line 36) | def set_platform(self):
    method get_account_type (line 49) | def get_account_type(self):
    method search_artist (line 64) | def search_artist(self, query: str, limit: int = 5):
    method get_artist_by_id (line 87) | def get_artist_by_id(self, query: int, limit: int = 1):
    method get_album (line 113) | def get_album(self, query: int) -> dict:
    method get_track (line 138) | def get_track(self, query: int) -> dict:
    method get_extra_release_info (line 162) | def get_extra_release_info(self, query: dict):
    method get_artist_albums (line 175) | def get_artist_albums(self, query: dict, limit: int = -1):
    method get_playlist (line 265) | def get_playlist(query: int):
    method get_playlist_tracks (line 285) | def get_playlist_tracks(query: dict):

FILE: deemon/core/common.py
  function exclude_filtered_versions (line 8) | def exclude_filtered_versions(albums: list) -> list:

FILE: deemon/core/config.py
  class Config (line 71) | class Config(object):
    method __init__ (line 75) | def __init__(self):
    method __create_default_config (line 107) | def __create_default_config():
    method __write_modified_config (line 112) | def __write_modified_config():
    method validate (line 117) | def validate():
    method get_config_file (line 305) | def get_config_file() -> Path:
    method get_config (line 309) | def get_config() -> dict:
    method plex_baseurl (line 313) | def plex_baseurl() -> str:
    method plex_token (line 317) | def plex_token() -> str:
    method plex_library (line 321) | def plex_library() -> str:
    method download_path (line 325) | def download_path() -> str:
    method deemix_path (line 329) | def deemix_path() -> str:
    method arl (line 333) | def arl() -> str:
    method release_max_age (line 337) | def release_max_age() -> int:
    method bitrate (line 341) | def bitrate() -> str:
    method alerts (line 345) | def alerts() -> bool:
    method record_type (line 349) | def record_type() -> str:
    method smtp_server (line 353) | def smtp_server() -> str:
    method smtp_port (line 357) | def smtp_port() -> int:
    method smtp_user (line 361) | def smtp_user() -> str:
    method smtp_pass (line 365) | def smtp_pass() -> str:
    method smtp_sender (line 369) | def smtp_sender() -> str:
    method smtp_recipient (line 373) | def smtp_recipient() -> list:
    method smtp_starttls (line 377) | def smtp_starttls() -> bool:
    method check_update (line 381) | def check_update() -> int:
    method debug_mode (line 385) | def debug_mode() -> bool:
    method profile_id (line 389) | def profile_id() -> int:
    method update_available (line 393) | def update_available() -> int:
    method query_limit (line 397) | def query_limit() -> int:
    method prompt_duplicates (line 401) | def prompt_duplicates() -> int:
    method prompt_no_matches (line 405) | def prompt_no_matches() -> bool:
    method allowed_values (line 409) | def allowed_values(prop):
    method release_channel (line 413) | def release_channel() -> str:
    method rollback_view_limit (line 417) | def rollback_view_limit() -> int:
    method transaction_id (line 421) | def transaction_id() -> int:
    method check_account_status (line 425) | def check_account_status() -> bool:
    method fast_api (line 429) | def fast_api() -> bool:
    method fast_api_threads (line 433) | def fast_api_threads() -> int:
    method allow_compilations (line 437) | def allow_compilations() -> bool:
    method allow_featured_in (line 441) | def allow_featured_in() -> bool:
    method allow_unofficial (line 445) | def allow_unofficial() -> bool:
    method enable_exclusions (line 449) | def enable_exclusions() -> bool:
    method exclusion_keywords (line 453) | def exclusion_keywords() -> list:
    method exclusion_patterns (line 460) | def exclusion_patterns() -> list:
    method plex_ssl_verify (line 467) | def plex_ssl_verify() -> bool:
    method halt_download_on_error (line 471) | def halt_download_on_error() -> bool:
    method smart_search (line 475) | def smart_search() -> bool:
    method find_position (line 480) | def find_position(d, property):
    method get (line 490) | def get(property):
    method set (line 494) | def set(property, value, validate=True):
  class LoadProfile (line 544) | class LoadProfile(object):
    method __init__ (line 545) | def __init__(self, profile: dict):

FILE: deemon/core/db.py
  class Database (line 16) | class Database(object):
    method __init__ (line 18) | def __init__(self):
    method __enter__ (line 29) | def __enter__(self):
    method __exit__ (line 32) | def __exit__(self):
    method dict_factory (line 36) | def dict_factory(cursor, row):
    method connect (line 42) | def connect(self):
    method close (line 50) | def close(self):
    method commit (line 55) | def commit(self):
    method commit_and_close (line 58) | def commit_and_close(self):
    method create_new_database (line 62) | def create_new_database(self):
    method get_latest_ver (line 145) | def get_latest_ver(self):
    method get_db_version (line 148) | def get_db_version(self):
    method do_upgrade (line 157) | def do_upgrade(self):
    method query (line 224) | def query(self, query, values=None):
    method reset_future (line 229) | def reset_future(self, album_id):
    method get_all_monitored_artists (line 235) | def get_all_monitored_artists(self):
    method get_monitored_artist_by_id (line 240) | def get_monitored_artist_by_id(self, artist_id: int):
    method get_monitored_artist_by_name (line 245) | def get_monitored_artist_by_name(self, name: str):
    method get_all_monitored_playlist_ids (line 250) | def get_all_monitored_playlist_ids(self):
    method get_all_monitored_playlists (line 255) | def get_all_monitored_playlists(self):
    method get_monitored_playlist_by_id (line 260) | def get_monitored_playlist_by_id(self, playlist_id):
    method get_monitored_playlist_by_name (line 264) | def get_monitored_playlist_by_name(self, title):
    method monitor_artist (line 269) | def monitor_artist(self, artist: dict, artist_config: dict):
    method get_artist_releases (line 284) | def get_artist_releases(self, artist_id=None):
    method get_future_releases (line 292) | def get_future_releases(self):
    method get_playlist_tracks (line 297) | def get_playlist_tracks(self, playlist_id):
    method get_track_from_playlist (line 302) | def get_track_from_playlist(self, playlist_id, track_id):
    method monitor_playlist (line 309) | def monitor_playlist(self, api_result):
    method remove_monitored_artist (line 321) | def remove_monitored_artist(self, id: int = None):
    method remove_monitored_playlists (line 327) | def remove_monitored_playlists(self, id: int = None):
    method get_specified_artist (line 333) | def get_specified_artist(self, artist):
    method set_all_artists_refreshed (line 342) | def set_all_artists_refreshed(self):
    method set_all_playlists_refreshed (line 345) | def set_all_playlists_refreshed(self):
    method add_new_releases (line 348) | def add_new_releases(self, values):
    method add_new_playlist_releases (line 357) | def add_new_playlist_releases(self, values):
    method show_new_releases (line 365) | def show_new_releases(self, from_date_ts, now_ts):
    method get_album_by_id (line 372) | def get_album_by_id(self, album_id):
    method reset_database (line 377) | def reset_database(self):
    method update_artist (line 386) | def update_artist(self, settings: dict):
    method add_playlist_track (line 391) | def add_playlist_track(self, playlist, track):
    method create_profile (line 401) | def create_profile(self, settings: dict):
    method delete_profile (line 407) | def delete_profile(self, profile_name: str):
    method get_all_profiles (line 417) | def get_all_profiles(self):
    method get_profile (line 420) | def get_profile(self, profile_name: str):
    method get_profile_by_id (line 424) | def get_profile_by_id(self, profile_id: int):
    method update_profile (line 428) | def update_profile(self, settings: dict):
    method last_update_check (line 435) | def last_update_check(self):
    method set_last_update_check (line 438) | def set_last_update_check(self):
    method get_next_transaction_id (line 443) | def get_next_transaction_id(self):
    method new_transaction (line 449) | def new_transaction(self):
    method rollback_last_refresh (line 458) | def rollback_last_refresh(self, rollback: int):
    method rollback_refresh (line 470) | def rollback_refresh(self, rollback: int):
    method set_artist_refreshed (line 478) | def set_artist_refreshed(self, id):
    method set_playlist_refreshed (line 482) | def set_playlist_refreshed(self, id):
    method set_latest_version (line 486) | def set_latest_version(self, version):
    method get_release_channel (line 491) | def get_release_channel(self):
    method set_release_channel (line 494) | def set_release_channel(self):
    method get_transactions (line 499) | def get_transactions(self):
    method get_all_monitored_artist_ids (line 528) | def get_all_monitored_artist_ids(self):
    method get_monitored (line 534) | def get_monitored(self):
    method get_unrefreshed_artists (line 540) | def get_unrefreshed_artists(self):
    method get_unrefreshed_playlists (line 544) | def get_unrefreshed_playlists(self):
    method fast_monitor (line 548) | def fast_monitor(self, values):
    method fast_monitor_playlist (line 553) | def fast_monitor_playlist(self, values):
    method insert_multiple (line 558) | def insert_multiple(self, table, values):
    method remove_by_name (line 563) | def remove_by_name(self, values):
    method remove_by_id (line 570) | def remove_by_id(self, values):
    method remove_specific_releases (line 578) | def remove_specific_releases(self, values):
    method add_extra_release_info (line 581) | def add_extra_release_info(self, values):

FILE: deemon/core/dmi.py
  class DeemixLogListener (line 24) | class DeemixLogListener:
    method send (line 26) | def send(cls, key, value=None):
  class DeemixInterface (line 43) | class DeemixInterface:
    method __init__ (line 44) | def __init__(self):
    method download_url (line 59) | def download_url(self, url, bitrate, download_path, override_deemix=Tr...
    method deezer_acct_type (line 85) | def deezer_acct_type(self):
    method verify_arl (line 98) | def verify_arl(self, arl):
    method login (line 109) | def login(self):
    method generatePlaylistItem (line 146) | def generatePlaylistItem(self, dz, link_id, bitrate, playlistAPI=None,...
  class GenerationError (line 211) | class GenerationError(Exception):
    method __init__ (line 212) | def __init__(self, link, message, errid=None):
    method toDict (line 218) | def toDict(self):
  class InvalidID (line 226) | class InvalidID(GenerationError):
    method __init__ (line 227) | def __init__(self, link):
  class NotYourPrivatePlaylist (line 231) | class NotYourPrivatePlaylist(GenerationError):
    method __init__ (line 232) | def __init__(self, link):

FILE: deemon/core/exceptions.py
  class ValueNotAllowed (line 1) | class ValueNotAllowed(Exception):
  class PropertyTypeMismatch (line 5) | class PropertyTypeMismatch(Exception):
  class UnknownValue (line 9) | class UnknownValue(Exception):

FILE: deemon/core/logger.py
  class tqdmStream (line 14) | class tqdmStream(object):
    method write (line 17) | def write(cls, msg):
  function setup_logger (line 21) | def setup_logger(log_level='DEBUG', log_file=None):

FILE: deemon/core/notifier.py
  class Notify (line 19) | class Notify:
    method __init__ (line 21) | def __init__(self, new_releases: list = None):
    method send (line 26) | def send(self, body=None, test=False):
    method construct_header (line 58) | def construct_header(self, is_plain_text=True, subject=None):
    method html_message (line 73) | def html_message(self):
    method test (line 82) | def test(self):
    method expired_arl (line 90) | def expired_arl(self):
    method expired_sub (line 98) | def expired_sub(self):
    method plaintext_message (line 106) | def plaintext_message(self) -> str:
    method html_new_releases (line 119) | def html_new_releases(self):

FILE: deemon/utils/dataprocessor.py
  function read_file_as_csv (line 7) | def read_file_as_csv(file, split_new_line=True):
  function process_input_file (line 25) | def process_input_file(artist_list):
  function csv_to_list (line 55) | def csv_to_list(all_artists) -> list:

FILE: deemon/utils/dates.py
  function get_todays_date (line 8) | def get_todays_date():
  function generate_date_filename (line 14) | def generate_date_filename(prefix: str):
  function get_max_release_date (line 18) | def get_max_release_date(days):
  function get_year (line 26) | def get_year(release_date: str):
  function format_date_string (line 30) | def format_date_string(d: str):
  function ui_date (line 34) | def ui_date(d: datetime):
  function str_to_datetime_obj (line 37) | def str_to_datetime_obj(d: str) -> datetime:
  function get_friendly_date (line 43) | def get_friendly_date(d: int):

FILE: deemon/utils/performance.py
  function timeit (line 7) | def timeit(method):
  function operation_time (line 19) | def operation_time(start_time):

FILE: deemon/utils/startup.py
  function get_appdata_root (line 12) | def get_appdata_root():
  function get_appdata_dir (line 28) | def get_appdata_dir():
  function get_backup_dir (line 35) | def get_backup_dir():
  function init_appdata_dir (line 39) | def init_appdata_dir(appdata):
  function delete_appdata (line 44) | def delete_appdata(appdata):
  function reinit_appdata_dir (line 51) | def reinit_appdata_dir(appdata):
  function get_config (line 59) | def get_config():
  function get_database (line 63) | def get_database():
  function get_log_file (line 67) | def get_log_file():
  function get_latest_version (line 74) | def get_latest_version(release_type):
  function get_changelog (line 96) | def get_changelog(ver: str):

FILE: deemon/utils/ui.py
  function get_progress_bar_size (line 7) | def get_progress_bar_size() -> int:
  function set_progress_bar_text (line 22) | def set_progress_bar_text(msg: str, max_length: int) -> str:

FILE: deemon/utils/validate.py
  function validate_date (line 7) | def validate_date(d):
Condensed preview — 68 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (348K chars).
[
  {
    "path": ".github/workflows/deploy-docker.yml",
    "chars": 961,
    "preview": "name: Deploy Docker\n\non:\n  release:\n    types: [released]\n  workflow_dispatch:\n\njobs:\n  docker:\n    if: \"!github.event.r"
  },
  {
    "path": ".github/workflows/discord-release-msg.yml",
    "chars": 423,
    "preview": "\nname: Release messages to discord announcement channel\n\non: \n  release:\n    types:\n      - created\n  workflow_dispatch:"
  },
  {
    "path": ".github/workflows/purge-old-betas.yml",
    "chars": 368,
    "preview": "name: Delete old beta releases\non:\n  workflow_dispatch:\n\njobs:\n  deploy:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - u"
  },
  {
    "path": ".github/workflows/python-publish.yml",
    "chars": 895,
    "preview": "# This workflow will upload a Python Package using Twine when a release is created\n# For more information see: https://h"
  },
  {
    "path": ".gitignore",
    "chars": 188,
    "preview": "__pycache__/\n.idea/\nbuild\ndeemon.egg-info\ndist\ntest.txt\nvenv\n.cache\ntests.py\n**/.DS_Store\nartists.txt\n/deemon/tests/\n.vs"
  },
  {
    "path": "Dockerfile",
    "chars": 450,
    "preview": "FROM ubuntu:22.04\n\nRUN apt-get update -y && \\\napt-get install -y python3-pip\n\nCOPY ./requirements.txt /requirements.txt\n"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "MANIFEST.in",
    "chars": 93,
    "preview": "recursive-include deemon/assets *\ninclude README.md\ninclude LICENSE\ninclude requirements.txt\n"
  },
  {
    "path": "README.md",
    "chars": 3667,
    "preview": "<img src=\"deemon/assets/images/deemon.png\" alt=\"deemon\" width=\"300\">\n\n[About](#about) | [Installation](#installation) | "
  },
  {
    "path": "deemon/__init__.py",
    "chars": 171,
    "preview": "#!/usr/bin/env python3\nfrom deemon.utils import startup\n\n__version__ = '2.22'\n__dbversion__ = '3.7'\n\nappdata = startup.g"
  },
  {
    "path": "deemon/__main__.py",
    "chars": 91,
    "preview": "from deemon import cli\n\n\ndef main():\n    cli.run()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "deemon/assets/index.html",
    "chars": 4837,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-wid"
  },
  {
    "path": "deemon/cli.py",
    "chars": 21081,
    "preview": "import logging\nimport platform\nimport sys\nimport time\nfrom pathlib import Path\n\nimport click\nfrom packaging.version impo"
  },
  {
    "path": "deemon/cmd/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "deemon/cmd/artistconfig.py",
    "chars": 3507,
    "preview": "import logging\n\nfrom deemon.core.config import Config as config\nfrom deemon.core.db import Database\n\nlogger = logging.ge"
  },
  {
    "path": "deemon/cmd/backup.py",
    "chars": 5150,
    "preview": "import logging\nimport os\nimport tarfile\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom packaging.version i"
  },
  {
    "path": "deemon/cmd/download.py",
    "chars": 23022,
    "preview": "import logging\nimport os\nimport sys\n\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib impo"
  },
  {
    "path": "deemon/cmd/extra.py",
    "chars": 1499,
    "preview": "from concurrent.futures import ThreadPoolExecutor\nimport logging\nfrom tqdm import tqdm\nfrom deemon.core import db as dba"
  },
  {
    "path": "deemon/cmd/generate.py",
    "chars": 5155,
    "preview": "from pathlib import Path\n\nimport tqdm as tqdm\nfrom deezer import Deezer\n\n\ndef read_album_ids_from_file(filename):\n    if"
  },
  {
    "path": "deemon/cmd/monitor.py",
    "chars": 11467,
    "preview": "import logging\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\n\nfrom tqdm import tqdm\n\nfrom d"
  },
  {
    "path": "deemon/cmd/profile.py",
    "chars": 7208,
    "preview": "import logging\n\nfrom deemon.core.config import Config as config\nfrom deemon.core.db import Database\n\nlogger = logging.ge"
  },
  {
    "path": "deemon/cmd/refresh.py",
    "chars": 16932,
    "preview": "import logging\nimport re\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import datetime, ti"
  },
  {
    "path": "deemon/cmd/rollback.py",
    "chars": 3352,
    "preview": "import logging\n\nfrom deemon.core.db import Database\nfrom deemon.utils import dates\n\nlogger = logging.getLogger(__name__)"
  },
  {
    "path": "deemon/cmd/search.py",
    "chars": 21193,
    "preview": "import logging\nimport sys\n\nfrom deezer import Deezer\n\nfrom deemon.cmd import download\nfrom deemon.cmd import monitor as "
  },
  {
    "path": "deemon/cmd/show.py",
    "chars": 10314,
    "preview": "import csv\nimport logging\nimport os\nimport time\nfrom pathlib import Path\nfrom typing import Union\n\nfrom deemon.core.db i"
  },
  {
    "path": "deemon/cmd/upgradelib.py",
    "chars": 16309,
    "preview": "import sys\nimport time\nimport logging\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom mutagen.easyid3 impor"
  },
  {
    "path": "deemon/core/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "deemon/core/api.py",
    "chars": 14515,
    "preview": "import json\nimport logging\nfrom datetime import datetime\n\nimport deezer.errors\nfrom deezer import Deezer\n\nfrom deemon.co"
  },
  {
    "path": "deemon/core/common.py",
    "chars": 1184,
    "preview": "import re\nimport logging\nfrom deemon.core.config import Config as config\n\nlogger = logging.getLogger(__name__)\n\n\ndef exc"
  },
  {
    "path": "deemon/core/config.py",
    "chars": 21162,
    "preview": "import json\nimport logging\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Optional\n\nfrom deemon.c"
  },
  {
    "path": "deemon/core/db.py",
    "chars": 28867,
    "preview": "import logging\nimport sqlite3\nimport time\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom packaging.version"
  },
  {
    "path": "deemon/core/dmi.py",
    "chars": 9120,
    "preview": "import logging\nimport sys\nfrom pathlib import Path\n\nimport deemix\nimport deemix.utils.localpaths as localpaths\nfrom deem"
  },
  {
    "path": "deemon/core/exceptions.py",
    "chars": 135,
    "preview": "class ValueNotAllowed(Exception):\n    pass\n\n\nclass PropertyTypeMismatch(Exception):\n    pass\n\n\nclass UnknownValue(Except"
  },
  {
    "path": "deemon/core/logger.py",
    "chars": 1320,
    "preview": "import logging\nfrom logging.handlers import RotatingFileHandler\n\nimport tqdm\n\nLOG_FORMATS = {\n    'DEBUG': '%(asctime)s "
  },
  {
    "path": "deemon/core/notifier.py",
    "chars": 7345,
    "preview": "import logging\nimport platform\nimport smtplib\nimport ssl\nfrom datetime import datetime\nfrom email.message import EmailMe"
  },
  {
    "path": "deemon/utils/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "deemon/utils/dataprocessor.py",
    "chars": 2557,
    "preview": "import logging\nfrom csv import reader\n\nlogger = logging.getLogger(__name__)\n\n\ndef read_file_as_csv(file, split_new_line="
  },
  {
    "path": "deemon/utils/dates.py",
    "chars": 2255,
    "preview": "import logging\nimport time\nfrom datetime import datetime, date\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_todays_da"
  },
  {
    "path": "deemon/utils/performance.py",
    "chars": 541,
    "preview": "import logging\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\ndef timeit(method):\n    def timed(*args, **kwargs):\n "
  },
  {
    "path": "deemon/utils/startup.py",
    "chars": 2822,
    "preview": "import logging\nimport os\nimport sys\nfrom pathlib import Path\n\nimport requests\nfrom packaging.version import parse as par"
  },
  {
    "path": "deemon/utils/ui.py",
    "chars": 697,
    "preview": "import os\n\n\nTQDM_FORMAT = \":: {desc} {percentage:3.0f}%\"\n\n\ndef get_progress_bar_size() -> int:\n    try:\n        screen_s"
  },
  {
    "path": "deemon/utils/validate.py",
    "chars": 208,
    "preview": "import logging\nfrom datetime import datetime\n\nlogger = logging.getLogger(__name__)\n\n\ndef validate_date(d):\n    try:\n    "
  },
  {
    "path": "docs/_config.yml",
    "chars": 39,
    "preview": "remote_theme: pmarsceill/just-the-docs\n"
  },
  {
    "path": "docs/_sass/custom/custom.scss",
    "chars": 171,
    "preview": "@import url('https://fonts.googleapis.com/css2?family=Baloo+Tammudu+2:wght@500&display=swap');\n\n.site-title {\n\tfont-fami"
  },
  {
    "path": "docs/docs/automations/automations.md",
    "chars": 104,
    "preview": "---\nlayout: default\ntitle: Automations\nnav_order: 5\nhas_children: true\npermalink: /docs/automations\n---\n"
  },
  {
    "path": "docs/docs/automations/cron.md",
    "chars": 419,
    "preview": "---\nlayout: default\ntitle: cron (Linux/macOS)\nparent: Automations\nnav_order: 1\n---\n\n# cron\n{: .no_toc }\n\n## Table of con"
  },
  {
    "path": "docs/docs/automations/task-scheduler.md",
    "chars": 2068,
    "preview": "---\nlayout: default\ntitle: Task Scheduler (Windows)\nparent: Automations\n---\n\n# Task Scheduler\n{: .no_toc }\n\n## Table of "
  },
  {
    "path": "docs/docs/commands/backup.md",
    "chars": 1316,
    "preview": "---\nlayout: default\ntitle: backup\nparent: Commands\n---\n\n# backup\n{: .no_toc }\n\n---\n\nIntroduced in version 1.0, you can n"
  },
  {
    "path": "docs/docs/commands/commands.md",
    "chars": 638,
    "preview": "---\nlayout: default\ntitle: Commands\nnav_order: 4\nhas_children: true\npermalink: /docs/commands\n---\n\n# arguments\n{: .no_to"
  },
  {
    "path": "docs/docs/commands/config.md",
    "chars": 690,
    "preview": "---\nlayout: default\ntitle: config\nparent: Commands\n---\n\n# config\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-del"
  },
  {
    "path": "docs/docs/commands/download.md",
    "chars": 1690,
    "preview": "---\nlayout: default\ntitle: download\nparent: Commands\n---\n\n# download\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text"
  },
  {
    "path": "docs/docs/commands/library.md",
    "chars": 1611,
    "preview": "---\nlayout: default\ntitle: library\nparent: Commands\n---\n\n# library\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-d"
  },
  {
    "path": "docs/docs/commands/monitor.md",
    "chars": 3827,
    "preview": "---\nlayout: default\ntitle: monitor\nparent: Commands\n---\n\n# monitor\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-d"
  },
  {
    "path": "docs/docs/commands/profile.md",
    "chars": 1976,
    "preview": "---\nlayout: default\ntitle: profile\nparent: Commands\n---\n\n# profile\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-d"
  },
  {
    "path": "docs/docs/commands/refresh.md",
    "chars": 2319,
    "preview": "---\nlayout: default\ntitle: refresh\nparent: Commands\n---\n\n# refresh\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-d"
  },
  {
    "path": "docs/docs/commands/reset.md",
    "chars": 486,
    "preview": "---\nlayout: default\ntitle: reset\nparent: Commands\n---\n\n# reset\n{: .no_toc }\n\n---\n\nThe `reset` command allows you to remo"
  },
  {
    "path": "docs/docs/commands/rollback.md",
    "chars": 1076,
    "preview": "---\nlayout: default\ntitle: rollback\nparent: Commands\n---\n\n# reset\n{: .no_toc }\n\n---\n\nThe `rollback` command allows you t"
  },
  {
    "path": "docs/docs/commands/search.md",
    "chars": 4571,
    "preview": "---\nlayout: default\ntitle: search\nparent: Commands\n---\n\n# deemon Interactive Search Client (dISC)\n{: .no_toc }\n\n## Table"
  },
  {
    "path": "docs/docs/commands/show.md",
    "chars": 3328,
    "preview": "---\nlayout: default\ntitle: show\nparent: Commands\n---\n\n# show\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }"
  },
  {
    "path": "docs/docs/commands/test.md",
    "chars": 991,
    "preview": "---\nlayout: default\ntitle: test\nparent: Commands\n---\n\n# test\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-delta }"
  },
  {
    "path": "docs/docs/configuration.md",
    "chars": 13281,
    "preview": "---\nlayout: default\ntitle: Configuration\nnav_order: 3\n---\n\n# Configuration\n{: .no_toc }\n\n\ndeemon has some specific confi"
  },
  {
    "path": "docs/docs/installation.md",
    "chars": 1366,
    "preview": "---\nlayout: default\ntitle: Installation\nnav_order: 2\n---\n\n# Installation\n{: .no_toc }\n\n## Table of contents\n{: .no_toc ."
  },
  {
    "path": "docs/docs/troubleshooting/logs.md",
    "chars": 465,
    "preview": "---\nlayout: default\ntitle: Logs\nparent: Troubleshooting\n---\n\n# Logs\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .text-"
  },
  {
    "path": "docs/docs/troubleshooting/queue.md",
    "chars": 539,
    "preview": "---\nlayout: default\ntitle: Queue\nparent: Troubleshooting\n---\n\n# Queue\n{: .no_toc }\n\n## Table of contents\n{: .no_toc .tex"
  },
  {
    "path": "docs/docs/troubleshooting/troubleshooting.md",
    "chars": 112,
    "preview": "---\nlayout: default\ntitle: Troubleshooting\nnav_order: 6\nhas_children: true\npermalink: /docs/troubleshooting\n---\n"
  },
  {
    "path": "docs/index.md",
    "chars": 1625,
    "preview": "---\nlayout: default\ntitle: Home\nnav_order: 1\ndescription: \"deemon is a monitoring utility for new artist releases that c"
  },
  {
    "path": "requirements.txt",
    "chars": 150,
    "preview": "deemix~=3.6\npackaging~=23.0\nrequests~=2.28.0\nclick~=8.1.0\nsetuptools~=66.1.0\nwheel~=0.43.0\nPlexAPI~=4.5.2\ntqdm~=4.61.0\nm"
  },
  {
    "path": "setup.py",
    "chars": 1015,
    "preview": "from pathlib import Path\nfrom setuptools import setup, find_packages\nfrom deemon import __version__\n\nwith open('requirem"
  }
]

About this extraction

This page contains the full source code of the digitalec/deemon GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 68 files (324.3 KB), approximately 73.8k tokens, and a symbol index with 330 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!