├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── pylint.yml │ └── pypi-publish.yml ├── .gitignore ├── CHANGELOG.md ├── COMMON_ERRORS.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── clspotify1.png ├── requirements.txt ├── setup.py └── zspotify ├── __main__.py ├── album.py ├── app.py ├── config.py ├── const.py ├── loader.py ├── playlist.py ├── podcast.py ├── termoutput.py ├── track.py ├── utils.py └── zspotify.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Enter `python zspotify -...` 16 | 2. Enter '....' 17 | 3. See error 18 | 19 | **Expected behavior** 20 | A clear and concise description of what you expected to happen. 21 | 22 | **Screenshots** 23 | If applicable, add screenshots to help explain your problem. 24 | 25 | **System Info:** 26 | - OS: [e.g. Windows 11, Ubuntu 20.04] 27 | - Release: [e.g. exe, docker, source] 28 | - Version (If using a binary release) 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.github/workflows/pylint.yml: -------------------------------------------------------------------------------- 1 | name: Pylint 2 | 3 | # yamllint disable-line rule:truthy 4 | on: [push, pull_request] 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Setup Python 13 | uses: actions/setup-python@v2 14 | with: 15 | python-version: 3.9 16 | - name: Setup Pylint 17 | run: | 18 | python -m pip install --upgrade pip 19 | pip install pylint pylint-exit 20 | pip install -r requirements.txt 21 | - name: Run Pylint 22 | run: | 23 | pylint $(git ls-files '*.py') || pylint-exit $? 24 | -------------------------------------------------------------------------------- /.github/workflows/pypi-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: PyPi Upload 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 28 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | src/__pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | cover/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | .pybuilder/ 77 | target/ 78 | 79 | # Jupyter Notebook 80 | .ipynb_checkpoints 81 | 82 | # IPython 83 | profile_default/ 84 | ipython_config.py 85 | 86 | # pyenv 87 | # For a library or package, you might want to ignore these files since the code is 88 | # intended to run in multiple environments; otherwise, check them in: 89 | # .python-version 90 | 91 | # pipenv 92 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 93 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 94 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 95 | # install all needed dependencies. 96 | #Pipfile.lock 97 | 98 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 99 | __pypackages__/ 100 | 101 | # Celery stuff 102 | celerybeat-schedule 103 | celerybeat.pid 104 | 105 | # SageMath parsed files 106 | *.sage.py 107 | 108 | # Environments 109 | .env 110 | .venv 111 | env/ 112 | venv/ 113 | ENV/ 114 | env.bak/ 115 | venv.bak/ 116 | 117 | # Spyder project settings 118 | .spyderproject 119 | .spyproject 120 | 121 | # Rope project settings 122 | .ropeproject 123 | 124 | # mkdocs documentation 125 | /site 126 | 127 | # mypy 128 | .mypy_cache/ 129 | .dmypy.json 130 | dmypy.json 131 | 132 | # Pyre type checker 133 | .pyre/ 134 | 135 | # pytype static type analyzer 136 | .pytype/ 137 | 138 | # Cython debug symbols 139 | cython_debug/ 140 | 141 | # VSCode settings 142 | .vscode/ 143 | 144 | # Spotify Credentials 145 | credentials.json 146 | src/credentials.json 147 | 148 | #Download Folder 149 | ZSpotify\ Music/ 150 | ZSpotify\ Podcasts/ 151 | 152 | # Intellij 153 | .idea 154 | 155 | # Config file 156 | zs_config.json 157 | 158 | # MacOS file 159 | .DS_Store 160 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog: 2 | ### v0.5.2 - We're bad at counting (27 Nov 2021): 3 | **General changes:** 4 | - Fixed filenaming on Windows 5 | - Fixed removal of special characters metadata 6 | - Can now download different songs with the same name 7 | - Real-time downloads now work correctly 8 | - Removed some debug messages 9 | - Added album_artist metadata 10 | - Added global song archive 11 | - Added SONG_ARCHIVE config value 12 | - Added CREDENTIALS_LOCATION config value 13 | - Added `--download` argument 14 | - Added `--config-location` argument 15 | - Added `--output` for output templating 16 | - Save extra data in .song_ids 17 | - Added options to regulate terminal output 18 | - Direct download support for certain podcasts 19 | 20 | **Docker images:** 21 | - Remember credentials between container starts 22 | - Use same uid/gid in container as on host 23 | 24 | **Windows installer:** 25 | - Now comes with full installer 26 | - Dependencies are installed if not found 27 | 28 | ### v0.2.4 (27 Oct 2021): 29 | - Added realtime downloading support to avoid account suspensions. 30 | - Fix for downloading by artist. 31 | - Replace audio conversion method for better quality. 32 | - Fix bug when automatically setting audio bitrate. 33 | 34 | ### v0.2.3 (25 Oct 2021): 35 | - Moved changelog to seperate file. 36 | - Added argument parsing in search function (query results limit and query result types). 37 | - Fixed spelling errors. 38 | - Added mac specific install guide stuff. 39 | - Fixed infinite loop. 40 | - Fixed issue where zspotify could'nt run on python 3.8/3.9. 41 | - Changed it so you can just run zspotify from the root folder again. 42 | - Added function to auto generate config file if it doesnt exist. 43 | - Fixed issue where if you enabled splitting discs into seperate folders downloading would fail. 44 | - Added playlist file(m3u) creation for playlist download. 45 | 46 | ### v0.2.2 (24 Oct 2021): 47 | - Added basic support for downloading an entire podcast series. 48 | - Split code into multiple files for easier maintenance. 49 | - Changed initial launch script to app.py 50 | - Simplified audio formats. 51 | - Added prebuild exe for Windows users. 52 | - Added Docker file. 53 | - Added CONTRIBUTING.md. 54 | - Fixed artist names getting cutoff in metadata. 55 | - Removed data sanitization of metadata tags. 56 | 57 | ### v0.2.1 (23 Oct 2021): 58 | - Moved configuration from hard-coded values to separate zs_config.json file. 59 | - Add subfolders for each disc. 60 | - Can now search and download all songs by artist. 61 | - Show single progress bar for entire album. 62 | - Added song number at start of track name in albums. 63 | 64 | ### v0.2.0 (22 Oct 2021): 65 | - Added progress bar for downloads. 66 | - Added multi-select support for all results when searching. 67 | - Added GPLv3 Licence. 68 | - Changed welcome banner and removed unnecessary debug print statements. 69 | 70 | ### v0.1.9 (22 Oct 2021): 71 | - Added Gitea mirror for when the Spotify Glowies come to DMCA the shit out of this. 72 | - Changed the discord server invite to a matrix server so that won't get swatted either. 73 | - Added option to select multiple of our saved playlists to download at once. 74 | - Added support for downloading an entire show at once. 75 | 76 | ### v0.1.8 (21 Oct 2021): 77 | - Improved podcast downloading a bit. 78 | - Simplified the code that catches crashes while downloading. 79 | - Cleaned up code using linter again. 80 | - Added option to just paste a url in the search bar to download it. 81 | - Added a small delay between downloading each track when downloading in bulk to help with downloading issues and potential bans. 82 | 83 | ### v0.1.7 (21 Oct 2021): 84 | - Rewrote README.md to look a lot more professional. 85 | - Added patch to fix edge case crash when downloading liked songs. 86 | - Made premium account check a lot more reliable. 87 | - Added experimental podcast support for specific episodes! 88 | 89 | ### v0.1.6 (20 Oct 2021): 90 | - Added Pillow to requirements.txt. 91 | - Removed websocket-client from requirements.txt because librespot-python added it to their dependency list. 92 | - Made it hide your password when you type it in. 93 | - Added manual override to force premium quality if zspotify cannot auto detect it. 94 | - Added option to just download the raw audio with no re-encoding at all. 95 | - Added Shebang line so it runs smoother on Linux. 96 | - Made it download the entire track at once now so it is more efficient and fixed a bug users encountered. 97 | 98 | ### v0.1.5 (19 Oct 2021): 99 | - Made downloading a lot more efficient and probably faster. 100 | - Made the sanitizer more efficient. 101 | - Formatted and linted all the code. 102 | 103 | ### v0.1.4 (19 Oct 2021): 104 | - Added option to encode the downloaded tracks in the "ogg" format rather than "mp3". 105 | - Added small improvement to sanitation function so it catches another edge case. 106 | 107 | ### v0.1.3 (19 Oct 2021): 108 | - Added auto detection about if the current account is premium or not. If it is a premium account it automatically sets the quality to VERY_HIGH and otherwise HIGH if we are using a free account. 109 | - Fixed conversion function so it now exports to the correct bitrate. 110 | - Added sanitation to playlist names to help catch an edge case crash. 111 | - Added option to download all your liked songs into a sub-folder. 112 | 113 | ### v0.1.2 (18 Oct 2021): 114 | - Added .gitignore. 115 | - Replaced dependency list in README.md with a proper requirements.txt file. 116 | - Improved the readability of README.md. 117 | 118 | ### v0.1.1 (16 Oct 2021): 119 | - Added try/except to help catch crashes where a very few specific tracks would crash either the downloading or conversion part. 120 | 121 | ### v0.1.0 (14 Oct 2021): 122 | - Adjusted some functions so it runs again with the newer version of librespot-python. 123 | - Improved my sanitization function so it catches more edge cases. 124 | - Fixed an issue where sometimes spotify wouldn't provide a song id for a track we are trying to download. It will now detect and skip these invalid tracks. 125 | - Added additional check for tracks that cannot be "played" due to licence(and similar) issues. These tracks will be skipped. 126 | 127 | ### v0.0.9 (13 Oct 2021): 128 | - Initial upload, needs adjustments to get working again after backend rewrite. 129 | -------------------------------------------------------------------------------- /COMMON_ERRORS.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Below will contain sets of errors that you might get running zspotify. Below will also contain possible fixes to these errors. It is advisable that you read this before posting your error in any support channel. 4 | 5 | ## AttributeError: module 'google.protobuf.descriptor' has no attribute '\_internal_create_key 6 | 7 | _Answer(s):_ 8 | 9 | `pip install --upgrade protobuf` 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | ### Thank you for contributing 4 | 5 | Without people like you this project wouldn't be anywhere near as polished and feature-rich as it is now. 6 | 7 | ### Guidelines 8 | 9 | Following these guidelines helps show that you respect the the time and effort spent by the developers and your fellow contributors making this project. 10 | 11 | ### What we are looking for 12 | 13 | ClSpotify is a community-driven project. There are many different ways to contribute. From providing tutorials and examples to help new users, reporting bugs, requesting new features, writing new code that can be added to the project, or even writing documentation. 14 | 15 | ### What we aren't looking for 16 | 17 | Please don't use the issues section to request help installing or setting up the project. It should be reserved for bugs when running the code, and feature requests. Instead use the support channel in our Matrix server. 18 | Please do not make a new pull request just to fix a typo or any small issue like that. We'd rather you just make an issue reporting it and we will fix it in the next commit. This helps to prevent commit spamming. 19 | 20 | # Ground rules 21 | 22 | ### Expectations 23 | * Ensure all code is linted with pylint before pushing. 24 | * Ensure all code passes the [testing criteria](#testing-criteria). 25 | * If you're planning on contributing a new feature, join the Discord or Matrix and discuss it with the Dev Team. 26 | * Please don't commit multiple new features at once. 27 | * Follow the [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/) 28 | 29 | # Your first contribution 30 | 31 | Unsure where to start? Have a look for any issues tagged "good first issue". They should be minor bugs that only require a few lines to fix. 32 | Here are a couple of friendly tutorials on making pull requests: http://makeapullrequest.com/ and http://www.firsttimersonly.com/ 33 | 34 | # Code review process 35 | 36 | The dev team looks at Pull Requests around once per day. After feedback has been given we expect responses within one week. After a week we may close the pull request if it isn't showing any activity. 37 | > ClSpotify updates very frequently, often multiple times per day. If a maintainer asks you to "rebase" your PR, they're saying that a lot of code has changed, and that you need to update your branch so it's easier to merge. 38 | 39 | # Community 40 | 41 | Come and chat with us on Discord or Matrix. Devs try to respond to mentions at least once per day. -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine as base 2 | 3 | RUN apk --update add git ffmpeg 4 | 5 | FROM base as builder 6 | RUN mkdir /install 7 | WORKDIR /install 8 | COPY requirements.txt /requirements.txt 9 | RUN apk add gcc libc-dev zlib zlib-dev jpeg-dev \ 10 | && pip install --prefix="/install" -r /requirements.txt 11 | 12 | 13 | FROM base 14 | 15 | COPY --from=builder /install /usr/local 16 | COPY zspotify /app 17 | WORKDIR /app 18 | ENTRYPOINT ["/usr/local/bin/python", "__main__.py"] 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Stars](https://img.shields.io/github/stars/agent255/ClSpotify.svg) 2 | ![Forks](https://img.shields.io/github/forks/agent255/ClSpotify.svg) 3 | ![Size](https://img.shields.io/github/repo-size/agent255/ClSpotify) 4 | 5 | # ClSpotify 6 | 7 | ### A Spotify downloader needing only a python interpreter and ffmpeg. 8 | 9 |

10 | 11 |

12 | 13 | [Matrix Server](https://matrix.to/#/#clspotify:matrix.org) - [NotABug Mirror](https://notabug.org/proprietary-is-bad/clspotify) - [Main Site](https://agent255.github.io/clspotifyweb/) 14 | 15 | ``` 16 | Requirements: 17 | 18 | Binaries 19 | 20 | - Python 3.9 or greater 21 | - ffmpeg* 22 | - Git** 23 | 24 | Python packages: 25 | 26 | - pip install -r requirements.txt 27 | 28 | ``` 29 | 30 | \*ffmpeg can be installed via apt for Debian-based distros or by downloading the binaries from [ffmpeg.org](https://ffmpeg.org) and placing them in your %PATH% in Windows. Mac users can install it with [Homebrew](https://brew.sh) by running `brew install ffmpeg`. 31 | 32 | \*\*Git can be installed via apt for Debian-based distros or by downloading the binaries from [git-scm.com](https://git-scm.com/download/win) for Windows. 33 | 34 | ### Command line usage: 35 | 36 | ``` 37 | Basic command line usage: 38 | python zpotify Downloads the track, album, playlist or podcast episode specified as a command line argument. If an artist url is given, all albums by specified artist will be downloaded. Can take multiple urls. 39 | 40 | Different usage modes: 41 | (nothing) Download the tracks/alumbs/playlists URLs from the parameter 42 | -d, --download Download all tracks/alumbs/playlists URLs from the specified file 43 | -p, --playlist Downloads a saved playlist from your account 44 | -ls, --liked-songs Downloads all the liked songs from your account 45 | -s, --search Loads search prompt to find then download a specific track, album or playlist 46 | 47 | Extra command line options: 48 | -ns, --no-splash Suppress the splash screen when loading. 49 | --config-location Use a different zs_config.json, defaults to the one in the program directory 50 | ``` 51 | 52 | ### Options: 53 | 54 | All these options can either be configured in the zs_config or via the commandline, in case of both the commandline-option has higher priority. 55 | Be aware you have to set boolean values in the commandline like this: `--download-real-time=True` 56 | 57 | | Key (zs-config) | commandline parameter | Description 58 | |------------------------------|----------------------------------|---------------------------------------------------------------------| 59 | | ROOT_PATH | --root-path | directory where ZSpotify saves the music 60 | | ROOT_PODCAST_PATH | --root-podcast-path | directory where ZSpotify saves the podcasts 61 | | SKIP_EXISTING_FILES | --skip-existing-files | Skip songs with the same name 62 | | SKIP_PREVIOUSLY_DOWNLOADED | --skip-previously-downloaded | Create a .song_archive file and skip previously downloaded songs 63 | | DOWNLOAD_FORMAT | --download-format | The download audio format (aac, fdk_aac, m4a, mp3, ogg, opus, vorbis) 64 | | FORCE_PREMIUM | --force-premium | Force the use of high quality downloads (only with premium accounts) 65 | | ANTI_BAN_WAIT_TIME | --anti-ban-wait-time | The wait time between bulk downloads 66 | | OVERRIDE_AUTO_WAIT | --override-auto-wait | Totally disable wait time between songs with the risk of instability 67 | | CHUNK_SIZE | --chunk-size | chunk size for downloading 68 | | SPLIT_ALBUM_DISCS | --split-album-discs | split downloaded albums by disc 69 | | DOWNLOAD_REAL_TIME | --download-real-time | only downloads songs as fast as they would be played, can prevent account bans 70 | | LANGUAGE | --language | Language for spotify metadata 71 | | BITRATE | --bitrate | Overwrite the bitrate for ffmpeg encoding 72 | | SONG_ARCHIVE | --song-archive | The song_archive file for SKIP_PREVIOUSLY_DOWNLOADED 73 | | CREDENTIALS_LOCATION | --credentials-location | The location of the credentials.json 74 | | OUTPUT | --output | The output location/format (see below) 75 | | PRINT_SPLASH | --print-splash | Print the splash message 76 | | PRINT_SKIPS | --print-skips | Print messages if a song is being skipped 77 | | PRINT_DOWNLOAD_PROGRESS | --print-download-progress | Print the download/playlist progress bars 78 | | PRINT_ERRORS | --print-errors | Print errors 79 | | PRINT_DOWNLOADS | --print-downloads | Print messages when a song is finished downloading 80 | | TEMP_DOWNLOAD_DIR | --temp-download-dir | Download tracks to a temporary directory first 81 | 82 | ### Output format: 83 | 84 | With the option `OUTPUT` (or the commandline parameter `--output`) you can specify the output location and format. 85 | The value is relative to the `ROOT_PATH`/`ROOT_PODCAST_PATH` directory and can contain the following placeholder: 86 | 87 | | Placeholder | Description 88 | |-----------------|-------------------------------- 89 | | {artist} | The song artist 90 | | {album} | The song album 91 | | {song_name} | The song name 92 | | {release_year} | The song release year 93 | | {disc_number} | The disc number 94 | | {track_number} | The track_number 95 | | {id} | The song id 96 | | {track_id} | The track id 97 | | {ext} | The file extension 98 | | {album_id} | (only when downloading albums) ID of the album 99 | | {album_num} | (only when downloading albums) Incrementing track number 100 | | {playlist} | (only when downloading playlists) Name of the playlist 101 | | {playlist_num} | (only when downloading playlists) Incrementing track number 102 | | {podcast} | (only when downloading podcasts) Name of the podcast 103 | | {episode_name} | (only when downloading podcasts) Name of the episode 104 | | {release_date} | (only when downloading podcasts) Release date of the episode 105 | 106 | Example values could be: 107 | ~~~~ 108 | {playlist}/{artist} - {song_name}.{ext} 109 | {playlist}/{playlist_num} - {artist} - {song_name}.{ext} 110 | Liked Songs/{artist} - {song_name}.{ext} 111 | {artist} - {song_name}.{ext} 112 | {artist}/{album}/{album_num} - {artist} - {song_name}.{ext} 113 | /home/user/downloads/{artist} - {song_name} [{id}].{ext} 114 | ~~~~ 115 | 116 | 117 | 118 | ### Will my account get banned if I use this tool? 119 | 120 | 121 | **There have been 2-3 reports from users who received account bans from Spotify for using this tool**. 122 | 123 | We recommend using ClSpotify with a burner account. 124 | Alternatively, there is a configuration option labled ```DOWNLOAD_REAL_TIME```, this limits the download speed to the duration of the song being downloaded thus not appearing suspicious to Spotify. 125 | This option is much slower and is only recommended for premium users who wish to download songs in 320kbps without buying premium on a burner account. 126 | 127 | **Use ClSpotify at your own risk**, the developers of ClSpotify are not responsible if your account gets banned. 128 | 129 | ### What do I do if I see "Your session has been terminated"? 130 | 131 | If you see this, don't worry! Just try logging back in. If you see the incorrect username or password error, reset your password and you should be able to log back in and continue using Spotify. 132 | 133 | 134 | # Credits 135 | Forked from: [ZSpotify](https://github.com/THIS-IS-NOT-A-BACKUP/zspotify) (Original was taken down) 136 | 137 | Main library used: [LibreSpot](https://github.com/librespot-org/librespot#:~:text=librespot%20is%20an%20open%20source,now%20deprecated%20closed%2Dsource%20libspotify%20.) 138 | 139 | Original author: [FootsieFat](https://github.com/footsiefat) 140 | 141 | 142 | 143 | 144 | ### Contributing 145 | 146 | Please refer to [CONTRIBUTING](CONTRIBUTING.md) 147 | 148 | ### Changelog 149 | 150 | Please refer to [CHANGELOG](CHANGELOG.md) 151 | 152 | ### Common Errors 153 | 154 | Please refer to [COMMON_ERRORS](COMMON_ERRORS.md) 155 | -------------------------------------------------------------------------------- /clspotify1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/agent255/clspotify/e48f13bc3a5d120decea57375dc96685abd96555/clspotify1.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ffmpy 2 | https://github.com/kokarare1212/librespot-python/archive/refs/heads/rewrite.zip 3 | music_tag 4 | Pillow 5 | protobuf 6 | tabulate 7 | tqdm 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | from setuptools import setup 3 | import setuptools 4 | 5 | 6 | 7 | # The directory containing this file 8 | HERE = pathlib.Path(__file__).parent 9 | 10 | # The text of the README file 11 | README = (HERE / "README.md").read_text() 12 | 13 | # This call to setup() does all the work 14 | setup( 15 | name="clspotify", 16 | version="0.5.3", 17 | description="A spotify downloader.", 18 | long_description=README, 19 | long_description_content_type="text/markdown", 20 | url="https://github.com/agent255/clspotify.git", 21 | author="hr", 22 | author_email="hemagna.rao@gmail.com", 23 | license="GPLv3", 24 | classifiers=[ 25 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 26 | "Programming Language :: Python :: 3.9", 27 | ], 28 | packages=['zspotify'], 29 | install_requires=['ffmpy', 'music_tag', 'Pillow', 'protobuf', 'tabulate', 'tqdm', 30 | 'librespot @ https://github.com/kokarare1212/librespot-python/archive/refs/heads/rewrite.zip'], 31 | include_package_data=True, 32 | ) 33 | -------------------------------------------------------------------------------- /zspotify/__main__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | 3 | """ 4 | ClSpotify 5 | It's like youtube-dl, but for Spotify. 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, version 3 of the License. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import argparse 21 | 22 | from app import client 23 | from config import CONFIG_VALUES 24 | 25 | if __name__ == '__main__': 26 | parser = argparse.ArgumentParser(prog='zspotify', 27 | description='A Spotify downloader needing only a python interpreter and ffmpeg.') 28 | parser.add_argument('-ns', '--no-splash', 29 | action='store_true', 30 | help='Suppress the splash screen when loading.') 31 | parser.add_argument('--config-location', 32 | type=str, 33 | help='Specify the zs_config.json location') 34 | group = parser.add_mutually_exclusive_group(required=True) 35 | group.add_argument('urls', 36 | type=str, 37 | # action='extend', 38 | default='', 39 | nargs='*', 40 | help='Downloads the track, album, playlist, podcast episode, or all albums by an artist from a url. Can take multiple urls.') 41 | group.add_argument('-ls', '--liked-songs', 42 | dest='liked_songs', 43 | action='store_true', 44 | help='Downloads all the liked songs from your account.') 45 | group.add_argument('-p', '--playlist', 46 | action='store_true', 47 | help='Downloads a saved playlist from your account.') 48 | group.add_argument('-s', '--search', 49 | dest='search_spotify', 50 | action='store_true', 51 | help='Loads search prompt to find then download a specific track, album or playlist') 52 | group.add_argument('-d', '--download', 53 | type=str, 54 | help='Downloads tracks, playlists and albums from the URLs written in the file passed.') 55 | 56 | for configkey in CONFIG_VALUES: 57 | parser.add_argument(CONFIG_VALUES[configkey]['arg'], 58 | type=str, 59 | default=None, 60 | help='Specify the value of the ['+configkey+'] config value') 61 | 62 | parser.set_defaults(func=client) 63 | 64 | args = parser.parse_args() 65 | args.func(args) 66 | -------------------------------------------------------------------------------- /zspotify/album.py: -------------------------------------------------------------------------------- 1 | from const import ITEMS, ARTISTS, NAME, ID 2 | from termoutput import Printer 3 | from track import download_track 4 | from utils import fix_filename 5 | from zspotify import ZSpotify 6 | 7 | ALBUM_URL = 'https://api.spotify.com/v1/albums' 8 | ARTIST_URL = 'https://api.spotify.com/v1/artists' 9 | 10 | 11 | def get_album_tracks(album_id): 12 | """ Returns album tracklist """ 13 | songs = [] 14 | offset = 0 15 | limit = 50 16 | 17 | while True: 18 | resp = ZSpotify.invoke_url_with_params(f'{ALBUM_URL}/{album_id}/tracks', limit=limit, offset=offset) 19 | offset += limit 20 | songs.extend(resp[ITEMS]) 21 | if len(resp[ITEMS]) < limit: 22 | break 23 | 24 | return songs 25 | 26 | 27 | def get_album_name(album_id): 28 | """ Returns album name """ 29 | (raw, resp) = ZSpotify.invoke_url(f'{ALBUM_URL}/{album_id}') 30 | return resp[ARTISTS][0][NAME], fix_filename(resp[NAME]) 31 | 32 | 33 | def get_artist_albums(artist_id): 34 | """ Returns artist's albums """ 35 | (raw, resp) = ZSpotify.invoke_url(f'{ARTIST_URL}/{artist_id}/albums?include_groups=album%2Csingle') 36 | # Return a list each album's id 37 | album_ids = [resp[ITEMS][i][ID] for i in range(len(resp[ITEMS]))] 38 | # Recursive requests to get all albums including singles an EPs 39 | while resp['next'] is not None: 40 | (raw, resp) = ZSpotify.invoke_url(resp['next']) 41 | album_ids.extend([resp[ITEMS][i][ID] for i in range(len(resp[ITEMS]))]) 42 | 43 | return album_ids 44 | 45 | 46 | def download_album(album): 47 | """ Downloads songs from an album """ 48 | artist, album_name = get_album_name(album) 49 | tracks = get_album_tracks(album) 50 | for n, track in Printer.progress(enumerate(tracks, start=1), unit_scale=True, unit='Song', total=len(tracks)): 51 | download_track('album', track[ID], extra_keys={'album_num': str(n).zfill(2), 'artist': artist, 'album': album_name, 'album_id': album}, disable_progressbar=True) 52 | 53 | 54 | def download_artist_albums(artist): 55 | """ Downloads albums of an artist """ 56 | albums = get_artist_albums(artist) 57 | for album_id in albums: 58 | download_album(album_id) 59 | -------------------------------------------------------------------------------- /zspotify/app.py: -------------------------------------------------------------------------------- 1 | from librespot.audio.decoders import AudioQuality 2 | from tabulate import tabulate 3 | import os 4 | 5 | from album import download_album, download_artist_albums 6 | from const import TRACK, NAME, ID, ARTIST, ARTISTS, ITEMS, TRACKS, EXPLICIT, ALBUM, ALBUMS, \ 7 | OWNER, PLAYLIST, PLAYLISTS, DISPLAY_NAME 8 | from playlist import get_playlist_songs, get_playlist_info, download_from_user_playlist, download_playlist 9 | from podcast import download_episode, get_show_episodes 10 | from termoutput import Printer, PrintChannel 11 | from track import download_track, get_saved_tracks 12 | from utils import splash, split_input, regex_input_for_urls 13 | from zspotify import ZSpotify 14 | 15 | SEARCH_URL = 'https://api.spotify.com/v1/search' 16 | 17 | 18 | def client(args) -> None: 19 | """ Connects to spotify to perform query's and get songs to download """ 20 | ZSpotify(args) 21 | 22 | Printer.print(PrintChannel.SPLASH, splash()) 23 | 24 | if ZSpotify.check_premium(): 25 | Printer.print(PrintChannel.SPLASH, '[ DETECTED PREMIUM ACCOUNT - USING VERY_HIGH QUALITY ]\n\n') 26 | ZSpotify.DOWNLOAD_QUALITY = AudioQuality.VERY_HIGH 27 | else: 28 | Printer.print(PrintChannel.SPLASH, '[ DETECTED FREE ACCOUNT - USING HIGH QUALITY ]\n\n') 29 | ZSpotify.DOWNLOAD_QUALITY = AudioQuality.HIGH 30 | 31 | if args.download: 32 | urls = [] 33 | filename = args.download 34 | if os.path.exists(filename): 35 | with open(filename, 'r', encoding='utf-8') as file: 36 | urls.extend([line.strip() for line in file.readlines()]) 37 | 38 | download_from_urls(urls) 39 | 40 | else: 41 | Printer.print(PrintChannel.ERRORS, f'File {filename} not found.\n') 42 | 43 | if args.urls: 44 | download_from_urls(args.urls) 45 | 46 | if args.playlist: 47 | download_from_user_playlist() 48 | 49 | if args.liked_songs: 50 | liked_songs_list = [] 51 | resp_json = ZSpotify.invoke_url('https://api.spotify.com/v1/me')[1] 52 | name_id = '_'.join([resp_json[DISPLAY_NAME], resp_json[ID]]) 53 | for song in get_saved_tracks(): 54 | if not song[TRACK][NAME] or not song[TRACK][ID]: 55 | Printer.print(PrintChannel.SKIPS, '### SKIPPING: SONG DOES NOT EXIST ON SPOTIFY ANYMORE ###' + "\n") 56 | else: 57 | filename = download_track('liked', song[TRACK][ID]) 58 | # Use relative path for m3u file 59 | liked_songs_list.append('./' + filename[len(ZSpotify.CONFIG.get_root_path()):].lstrip('../')) 60 | try: 61 | with open(f'{ZSpotify.CONFIG.get_root_path()}/{name_id}_liked_songs.m3u', 'w', encoding='utf-8') as file: 62 | file.write('\n'.join(liked_songs_list)) 63 | except OSError: 64 | Printer.print(PrintChannel.ERRORS, '### ERROR: COULD NOT WRITE LIKED SONGS M3U FILE ###' + "\n") 65 | 66 | if args.search_spotify: 67 | search_text = '' 68 | while len(search_text) == 0: 69 | search_text = input('Enter search or URL: ') 70 | 71 | if not download_from_urls([search_text]): 72 | search(search_text) 73 | 74 | def download_from_urls(urls: list[str]) -> bool: 75 | """ Downloads from a list of spotify urls """ 76 | download = False 77 | 78 | for spotify_url in urls: 79 | track_id, album_id, playlist_id, episode_id, show_id, artist_id = regex_input_for_urls( 80 | spotify_url) 81 | 82 | if track_id is not None: 83 | download = True 84 | download_track('single', track_id) 85 | elif artist_id is not None: 86 | download = True 87 | download_artist_albums(artist_id) 88 | elif album_id is not None: 89 | download = True 90 | download_album(album_id) 91 | elif playlist_id is not None: 92 | download = True 93 | playlist_songs = get_playlist_songs(playlist_id) 94 | name, owner = get_playlist_info(playlist_id) 95 | enum = 1 96 | char_num = len(str(len(playlist_songs))) 97 | playlist_songlist = [] 98 | for song in playlist_songs: 99 | if not song[TRACK][NAME] or not song[TRACK][ID]: 100 | Printer.print(PrintChannel.SKIPS, '### SKIPPING: SONG DOES NOT EXIST ON SPOTIFY ANYMORE ###' + "\n") 101 | else: 102 | filename = download_track('playlist', song[TRACK][ID], extra_keys= 103 | { 104 | 'playlist_song_name': song[TRACK][NAME], 105 | 'playlist': name, 106 | 'playlist_num': str(enum).zfill(char_num), 107 | 'playlist_id': playlist_id, 108 | 'playlist_track_id': song[TRACK][ID] 109 | }) 110 | playlist_songlist.append('./' + filename[len(ZSpotify.CONFIG.get_root_path()):].lstrip('../')) 111 | enum += 1 112 | try: 113 | with open(f'{ZSpotify.CONFIG.get_root_path()}/{owner}_{name}.m3u', 'w', encoding='utf-8') as file: 114 | file.write('\n'.join(playlist_songlist)) 115 | except OSError: 116 | Printer.print(PrintChannel.ERRORS, '### ERROR: COULD NOT WRITE M3U FILE ###' + "\n") 117 | elif episode_id is not None: 118 | download = True 119 | download_episode(episode_id) 120 | elif show_id is not None: 121 | download = True 122 | for episode in get_show_episodes(show_id): 123 | download_episode(episode) 124 | 125 | return download 126 | 127 | 128 | def search(search_term): 129 | """ Searches Spotify's API for relevant data """ 130 | params = {'limit': '10', 131 | 'offset': '0', 132 | 'q': search_term, 133 | 'type': 'track,album,artist,playlist'} 134 | 135 | # Parse args 136 | splits = search_term.split() 137 | for split in splits: 138 | index = splits.index(split) 139 | 140 | if split[0] == '-' and len(split) > 1: 141 | if len(splits)-1 == index: 142 | raise IndexError('No parameters passed after option: {}\n'. 143 | format(split)) 144 | 145 | if split == '-l' or split == '-limit': 146 | try: 147 | int(splits[index+1]) 148 | except ValueError: 149 | raise ValueError('Paramater passed after {} option must be an integer.\n'. 150 | format(split)) 151 | if int(splits[index+1]) > 50: 152 | raise ValueError('Invalid limit passed. Max is 50.\n') 153 | params['limit'] = splits[index+1] 154 | 155 | if split == '-t' or split == '-type': 156 | 157 | allowed_types = ['track', 'playlist', 'album', 'artist'] 158 | passed_types = [] 159 | for i in range(index+1, len(splits)): 160 | if splits[i][0] == '-': 161 | break 162 | 163 | if splits[i] not in allowed_types: 164 | raise ValueError('Parameters passed after {} option must be from this list:\n{}'. 165 | format(split, '\n'.join(allowed_types))) 166 | 167 | passed_types.append(splits[i]) 168 | params['type'] = ','.join(passed_types) 169 | 170 | if len(params['type']) == 0: 171 | params['type'] = 'track,album,artist,playlist' 172 | 173 | # Clean search term 174 | search_term_list = [] 175 | for split in splits: 176 | if split[0] == "-": 177 | break 178 | search_term_list.append(split) 179 | if not search_term_list: 180 | raise ValueError("Invalid query.") 181 | params["q"] = ' '.join(search_term_list) 182 | 183 | resp = ZSpotify.invoke_url_with_params(SEARCH_URL, **params) 184 | 185 | counter = 1 186 | dics = [] 187 | 188 | total_tracks = 0 189 | if TRACK in params['type'].split(','): 190 | tracks = resp[TRACKS][ITEMS] 191 | if len(tracks) > 0: 192 | print('### TRACKS ###') 193 | track_data = [] 194 | for track in tracks: 195 | if track[EXPLICIT]: 196 | explicit = '[E]' 197 | else: 198 | explicit = '' 199 | 200 | track_data.append([counter, f'{track[NAME]} {explicit}', 201 | ','.join([artist[NAME] for artist in track[ARTISTS]])]) 202 | dics.append({ 203 | ID: track[ID], 204 | NAME: track[NAME], 205 | 'type': TRACK, 206 | }) 207 | 208 | counter += 1 209 | total_tracks = counter - 1 210 | print(tabulate(track_data, headers=[ 211 | 'S.NO', 'Name', 'Artists'], tablefmt='pretty')) 212 | print('\n') 213 | del tracks 214 | del track_data 215 | 216 | total_albums = 0 217 | if ALBUM in params['type'].split(','): 218 | albums = resp[ALBUMS][ITEMS] 219 | if len(albums) > 0: 220 | print('### ALBUMS ###') 221 | album_data = [] 222 | for album in albums: 223 | album_data.append([counter, album[NAME], 224 | ','.join([artist[NAME] for artist in album[ARTISTS]])]) 225 | dics.append({ 226 | ID: album[ID], 227 | NAME: album[NAME], 228 | 'type': ALBUM, 229 | }) 230 | 231 | counter += 1 232 | total_albums = counter - total_tracks - 1 233 | print(tabulate(album_data, headers=[ 234 | 'S.NO', 'Album', 'Artists'], tablefmt='pretty')) 235 | print('\n') 236 | del albums 237 | del album_data 238 | 239 | total_artists = 0 240 | if ARTIST in params['type'].split(','): 241 | artists = resp[ARTISTS][ITEMS] 242 | if len(artists) > 0: 243 | print('### ARTISTS ###') 244 | artist_data = [] 245 | for artist in artists: 246 | artist_data.append([counter, artist[NAME]]) 247 | dics.append({ 248 | ID: artist[ID], 249 | NAME: artist[NAME], 250 | 'type': ARTIST, 251 | }) 252 | counter += 1 253 | total_artists = counter - total_tracks - total_albums - 1 254 | print(tabulate(artist_data, headers=[ 255 | 'S.NO', 'Name'], tablefmt='pretty')) 256 | print('\n') 257 | del artists 258 | del artist_data 259 | 260 | total_playlists = 0 261 | if PLAYLIST in params['type'].split(','): 262 | playlists = resp[PLAYLISTS][ITEMS] 263 | if len(playlists) > 0: 264 | print('### PLAYLISTS ###') 265 | playlist_data = [] 266 | for playlist in playlists: 267 | playlist_data.append( 268 | [counter, playlist[NAME], playlist[OWNER][DISPLAY_NAME]]) 269 | dics.append({ 270 | ID: playlist[ID], 271 | NAME: playlist[NAME], 272 | 'type': PLAYLIST, 273 | }) 274 | counter += 1 275 | total_playlists = counter - total_artists - total_tracks - total_albums - 1 276 | print(tabulate(playlist_data, headers=[ 277 | 'S.NO', 'Name', 'Owner'], tablefmt='pretty')) 278 | print('\n') 279 | del playlists 280 | del playlist_data 281 | 282 | if total_tracks + total_albums + total_artists + total_playlists == 0: 283 | print('NO RESULTS FOUND - EXITING...') 284 | else: 285 | selection = '' 286 | print('> SELECT A DOWNLOAD OPTION BY ID') 287 | print('> SELECT A RANGE BY ADDING A DASH BETWEEN BOTH ID\'s') 288 | print('> OR PARTICULAR OPTIONS BY ADDING A COMMA BETWEEN ID\'s\n') 289 | while len(selection) == 0: 290 | selection = str(input('ID(s): ')) 291 | inputs = split_input(selection) 292 | for pos in inputs: 293 | position = int(pos) 294 | for dic in dics: 295 | print_pos = dics.index(dic) + 1 296 | if print_pos == position: 297 | if dic['type'] == TRACK: 298 | download_track('single', dic[ID]) 299 | elif dic['type'] == ALBUM: 300 | download_album(dic[ID]) 301 | elif dic['type'] == ARTIST: 302 | download_artist_albums(dic[ID]) 303 | else: 304 | download_playlist(dic) 305 | -------------------------------------------------------------------------------- /zspotify/config.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from typing import Any 4 | 5 | CONFIG_FILE_PATH = '../zs_config.json' 6 | 7 | ROOT_PATH = 'ROOT_PATH' 8 | ROOT_PODCAST_PATH = 'ROOT_PODCAST_PATH' 9 | SKIP_EXISTING_FILES = 'SKIP_EXISTING_FILES' 10 | SKIP_PREVIOUSLY_DOWNLOADED = 'SKIP_PREVIOUSLY_DOWNLOADED' 11 | SKIP_EXISTING_ANY_ORIGIN = 'SKIP_EXISTING_ANY_ORIGIN' 12 | DOWNLOAD_FORMAT = 'DOWNLOAD_FORMAT' 13 | FORCE_PREMIUM = 'FORCE_PREMIUM' 14 | ANTI_BAN_WAIT_TIME = 'ANTI_BAN_WAIT_TIME' 15 | OVERRIDE_AUTO_WAIT = 'OVERRIDE_AUTO_WAIT' 16 | CHUNK_SIZE = 'CHUNK_SIZE' 17 | SPLIT_ALBUM_DISCS = 'SPLIT_ALBUM_DISCS' 18 | DOWNLOAD_REAL_TIME = 'DOWNLOAD_REAL_TIME' 19 | LANGUAGE = 'LANGUAGE' 20 | BITRATE = 'BITRATE' 21 | SONG_ARCHIVE = 'SONG_ARCHIVE' 22 | CREDENTIALS_LOCATION = 'CREDENTIALS_LOCATION' 23 | OUTPUT = 'OUTPUT' 24 | PRINT_SPLASH = 'PRINT_SPLASH' 25 | PRINT_SKIPS = 'PRINT_SKIPS' 26 | PRINT_DOWNLOAD_PROGRESS = 'PRINT_DOWNLOAD_PROGRESS' 27 | PRINT_ERRORS = 'PRINT_ERRORS' 28 | PRINT_DOWNLOADS = 'PRINT_DOWNLOADS' 29 | PRINT_API_ERRORS = 'PRINT_API_ERRORS' 30 | TEMP_DOWNLOAD_DIR = 'TEMP_DOWNLOAD_DIR' 31 | MD_ALLGENRES = 'MD_ALLGENRES' 32 | MD_GENREDELIMITER = 'MD_GENREDELIMITER' 33 | PRINT_PROGRESS_INFO = 'PRINT_PROGRESS_INFO' 34 | PRINT_WARNINGS = 'PRINT_WARNINGS' 35 | RETRY_ATTEMPTS = 'RETRY_ATTEMPTS' 36 | 37 | CONFIG_VALUES = { 38 | ROOT_PATH: { 'default': '../ZSpotify Music/', 'type': str, 'arg': '--root-path' }, 39 | ROOT_PODCAST_PATH: { 'default': '../ZSpotify Podcasts/', 'type': str, 'arg': '--root-podcast-path' }, 40 | SKIP_EXISTING_FILES: { 'default': 'True', 'type': bool, 'arg': '--skip-existing-files' }, 41 | SKIP_PREVIOUSLY_DOWNLOADED: { 'default': 'False', 'type': bool, 'arg': '--skip-previously-downloaded' }, 42 | SKIP_EXISTING_ANY_ORIGIN: {'default': 'True', 'type': bool, 'arg': '--skip-existing-any-origin'}, 43 | RETRY_ATTEMPTS: { 'default': '5', 'type': int, 'arg': '--retry-attemps' }, 44 | DOWNLOAD_FORMAT: { 'default': 'ogg', 'type': str, 'arg': '--download-format' }, 45 | FORCE_PREMIUM: { 'default': 'False', 'type': bool, 'arg': '--force-premium' }, 46 | ANTI_BAN_WAIT_TIME: { 'default': '1', 'type': int, 'arg': '--anti-ban-wait-time' }, 47 | OVERRIDE_AUTO_WAIT: { 'default': 'False', 'type': bool, 'arg': '--override-auto-wait' }, 48 | CHUNK_SIZE: { 'default': '50000', 'type': int, 'arg': '--chunk-size' }, 49 | SPLIT_ALBUM_DISCS: { 'default': 'False', 'type': bool, 'arg': '--split-album-discs' }, 50 | DOWNLOAD_REAL_TIME: { 'default': 'False', 'type': bool, 'arg': '--download-real-time' }, 51 | LANGUAGE: { 'default': 'en', 'type': str, 'arg': '--language' }, 52 | BITRATE: { 'default': '', 'type': str, 'arg': '--bitrate' }, 53 | SONG_ARCHIVE: { 'default': '.song_archive', 'type': str, 'arg': '--song-archive' }, 54 | CREDENTIALS_LOCATION: { 'default': 'credentials.json', 'type': str, 'arg': '--credentials-location' }, 55 | OUTPUT: { 'default': '', 'type': str, 'arg': '--output' }, 56 | PRINT_SPLASH: { 'default': 'False', 'type': bool, 'arg': '--print-splash' }, 57 | PRINT_SKIPS: { 'default': 'True', 'type': bool, 'arg': '--print-skips' }, 58 | PRINT_DOWNLOAD_PROGRESS: { 'default': 'True', 'type': bool, 'arg': '--print-download-progress' }, 59 | PRINT_ERRORS: { 'default': 'True', 'type': bool, 'arg': '--print-errors' }, 60 | PRINT_DOWNLOADS: { 'default': 'False', 'type': bool, 'arg': '--print-downloads' }, 61 | PRINT_API_ERRORS: { 'default': 'False', 'type': bool, 'arg': '--print-api-errors' }, 62 | PRINT_PROGRESS_INFO: { 'default': 'True', 'type': bool, 'arg': '--print-progress-info' }, 63 | PRINT_WARNINGS: { 'default': 'True', 'type': bool, 'arg': '--print-warnings' }, 64 | MD_ALLGENRES: { 'default': 'False', 'type': bool, 'arg': '--md-allgenres' }, 65 | MD_GENREDELIMITER: { 'default': ';', 'type': str, 'arg': '--md-genredelimiter' }, 66 | TEMP_DOWNLOAD_DIR: { 'default': '', 'type': str, 'arg': '--temp-download-dir' } 67 | } 68 | 69 | OUTPUT_DEFAULT_PLAYLIST = '{playlist}/{artist} - {song_name}.{ext}' 70 | OUTPUT_DEFAULT_PLAYLIST_EXT = '{playlist}/{playlist_num} - {artist} - {song_name}.{ext}' 71 | OUTPUT_DEFAULT_LIKED_SONGS = 'Liked Songs/{artist} - {song_name}.{ext}' 72 | OUTPUT_DEFAULT_SINGLE = '{artist} - {song_name}.{ext}' 73 | OUTPUT_DEFAULT_ALBUM = '{artist}/{album}/{album_num} - {artist} - {song_name}.{ext}' 74 | OUTPUT_DEFAULT_PODCAST = '{podcast}/{episode_name}.{ext}' 75 | 76 | 77 | class Config: 78 | Values = {} 79 | 80 | @classmethod 81 | def load(cls, args) -> None: 82 | app_dir = os.path.dirname(__file__) 83 | 84 | config_fp = CONFIG_FILE_PATH 85 | if args.config_location: 86 | config_fp = args.config_location 87 | 88 | true_config_file_path = os.path.join(app_dir, config_fp) 89 | 90 | # Load config from zs_config.json 91 | 92 | if not os.path.exists(true_config_file_path): 93 | with open(true_config_file_path, 'w', encoding='utf-8') as config_file: 94 | json.dump(cls.get_default_json(), config_file, indent=4) 95 | cls.Values = cls.get_default_json() 96 | else: 97 | with open(true_config_file_path, encoding='utf-8') as config_file: 98 | jsonvalues = json.load(config_file) 99 | cls.Values = {} 100 | for key in CONFIG_VALUES: 101 | if key in jsonvalues: 102 | cls.Values[key] = cls.parse_arg_value(key, jsonvalues[key]) 103 | 104 | # Add default values for missing keys 105 | 106 | for key in CONFIG_VALUES: 107 | if key not in cls.Values: 108 | cls.Values[key] = cls.parse_arg_value(key, CONFIG_VALUES[key]['default']) 109 | 110 | # Override config from commandline arguments 111 | 112 | for key in CONFIG_VALUES: 113 | if key.lower() in vars(args) and vars(args)[key.lower()] is not None: 114 | cls.Values[key] = cls.parse_arg_value(key, vars(args)[key.lower()]) 115 | 116 | if args.no_splash: 117 | cls.Values[PRINT_SPLASH] = False 118 | 119 | @classmethod 120 | def get_default_json(cls) -> Any: 121 | r = {} 122 | for key in CONFIG_VALUES: 123 | r[key] = CONFIG_VALUES[key]['default'] 124 | return r 125 | 126 | @classmethod 127 | def parse_arg_value(cls, key: str, value: Any) -> Any: 128 | if type(value) == CONFIG_VALUES[key]['type']: 129 | return value 130 | if CONFIG_VALUES[key]['type'] == str: 131 | return str(value) 132 | if CONFIG_VALUES[key]['type'] == int: 133 | return int(value) 134 | if CONFIG_VALUES[key]['type'] == bool: 135 | if str(value).lower() in ['yes', 'true', '1']: 136 | return True 137 | if str(value).lower() in ['no', 'false', '0']: 138 | return False 139 | raise ValueError("Not a boolean: " + value) 140 | raise ValueError("Unknown Type: " + value) 141 | 142 | @classmethod 143 | def get(cls, key: str) -> Any: 144 | return cls.Values.get(key) 145 | 146 | @classmethod 147 | def get_root_path(cls) -> str: 148 | return os.path.join(os.path.dirname(__file__), cls.get(ROOT_PATH)) 149 | 150 | @classmethod 151 | def get_root_podcast_path(cls) -> str: 152 | return os.path.join(os.path.dirname(__file__), cls.get(ROOT_PODCAST_PATH)) 153 | 154 | @classmethod 155 | def get_skip_existing_files(cls) -> bool: 156 | return cls.get(SKIP_EXISTING_FILES) 157 | 158 | @classmethod 159 | def get_skip_previously_downloaded(cls) -> bool: 160 | return cls.get(SKIP_PREVIOUSLY_DOWNLOADED) 161 | 162 | @classmethod 163 | def get_skip_existing_any_origin(cls) -> bool: 164 | return cls.get(SKIP_EXISTING_ANY_ORIGIN) 165 | 166 | @classmethod 167 | def get_split_album_discs(cls) -> bool: 168 | return cls.get(SPLIT_ALBUM_DISCS) 169 | 170 | @classmethod 171 | def get_chunk_size(cls) -> int: 172 | return cls.get(CHUNK_SIZE) 173 | 174 | @classmethod 175 | def get_override_auto_wait(cls) -> bool: 176 | return cls.get(OVERRIDE_AUTO_WAIT) 177 | 178 | @classmethod 179 | def get_force_premium(cls) -> bool: 180 | return cls.get(FORCE_PREMIUM) 181 | 182 | @classmethod 183 | def get_download_format(cls) -> str: 184 | return cls.get(DOWNLOAD_FORMAT) 185 | 186 | @classmethod 187 | def get_anti_ban_wait_time(cls) -> int: 188 | return cls.get(ANTI_BAN_WAIT_TIME) 189 | 190 | @classmethod 191 | def get_language(cls) -> str: 192 | return cls.get(LANGUAGE) 193 | 194 | @classmethod 195 | def get_download_real_time(cls) -> bool: 196 | return cls.get(DOWNLOAD_REAL_TIME) 197 | 198 | @classmethod 199 | def get_bitrate(cls) -> str: 200 | return cls.get(BITRATE) 201 | 202 | @classmethod 203 | def get_song_archive(cls) -> str: 204 | return os.path.join(cls.get_root_path(), cls.get(SONG_ARCHIVE)) 205 | 206 | @classmethod 207 | def get_credentials_location(cls) -> str: 208 | return os.path.join(os.getcwd(), cls.get(CREDENTIALS_LOCATION)) 209 | 210 | @classmethod 211 | def get_temp_download_dir(cls) -> str: 212 | if cls.get(TEMP_DOWNLOAD_DIR) == '': 213 | return '' 214 | return os.path.join(cls.get_root_path(), cls.get(TEMP_DOWNLOAD_DIR)) 215 | 216 | @classmethod 217 | def get_all_genres(cls) -> bool: 218 | return cls.get(MD_ALLGENRES) 219 | 220 | @classmethod 221 | def get_all_genres_delimiter(cls) -> bool: 222 | return cls.get(MD_GENREDELIMITER) 223 | 224 | @classmethod 225 | def get_output(cls, mode: str) -> str: 226 | v = cls.get(OUTPUT) 227 | if v: 228 | return v 229 | if mode == 'playlist': 230 | if cls.get_split_album_discs(): 231 | split = os.path.split(OUTPUT_DEFAULT_PLAYLIST) 232 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 233 | return OUTPUT_DEFAULT_PLAYLIST 234 | if mode == 'extplaylist': 235 | if cls.get_split_album_discs(): 236 | split = os.path.split(OUTPUT_DEFAULT_PLAYLIST_EXT) 237 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 238 | return OUTPUT_DEFAULT_PLAYLIST_EXT 239 | if mode == 'liked': 240 | if cls.get_split_album_discs(): 241 | split = os.path.split(OUTPUT_DEFAULT_LIKED_SONGS) 242 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 243 | return OUTPUT_DEFAULT_LIKED_SONGS 244 | if mode == 'single': 245 | if cls.get_split_album_discs(): 246 | split = os.path.split(OUTPUT_DEFAULT_SINGLE) 247 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 248 | return OUTPUT_DEFAULT_SINGLE 249 | if mode == 'album': 250 | if cls.get_split_album_discs(): 251 | split = os.path.split(OUTPUT_DEFAULT_ALBUM) 252 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 253 | return OUTPUT_DEFAULT_ALBUM 254 | if mode == 'podcast': 255 | if cls.get_split_album_discs(): 256 | split = os.path.split(OUTPUT_DEFAULT_PODCAST) 257 | return os.path.join(split[0], 'Disc {disc_number}', split[0]) 258 | return OUTPUT_DEFAULT_PODCAST 259 | raise ValueError() 260 | 261 | @classmethod 262 | def get_retry_attempts(cls) -> int: 263 | return cls.get(RETRY_ATTEMPTS) -------------------------------------------------------------------------------- /zspotify/const.py: -------------------------------------------------------------------------------- 1 | SAVED_TRACKS_URL = 'https://api.spotify.com/v1/me/tracks' 2 | 3 | TRACKS_URL = 'https://api.spotify.com/v1/tracks' 4 | 5 | TRACK_STATS_URL = 'https://api.spotify.com/v1/audio-features/' 6 | 7 | TRACKNUMBER = 'tracknumber' 8 | 9 | DISCNUMBER = 'discnumber' 10 | 11 | YEAR = 'year' 12 | 13 | ALBUM = 'album' 14 | 15 | TRACKTITLE = 'tracktitle' 16 | 17 | ARTIST = 'artist' 18 | 19 | ARTISTS = 'artists' 20 | 21 | ALBUMARTIST = 'albumartist' 22 | 23 | GENRES = 'genres' 24 | 25 | GENRE = 'genre' 26 | 27 | ARTWORK = 'artwork' 28 | 29 | TRACKS = 'tracks' 30 | 31 | TRACK = 'track' 32 | 33 | ITEMS = 'items' 34 | 35 | NAME = 'name' 36 | 37 | HREF = 'href' 38 | 39 | ID = 'id' 40 | 41 | URL = 'url' 42 | 43 | RELEASE_DATE = 'release_date' 44 | 45 | IMAGES = 'images' 46 | 47 | LIMIT = 'limit' 48 | 49 | OFFSET = 'offset' 50 | 51 | AUTHORIZATION = 'Authorization' 52 | 53 | IS_PLAYABLE = 'is_playable' 54 | 55 | DURATION_MS = 'duration_ms' 56 | 57 | TRACK_NUMBER = 'track_number' 58 | 59 | DISC_NUMBER = 'disc_number' 60 | 61 | SHOW = 'show' 62 | 63 | ERROR = 'error' 64 | 65 | EXPLICIT = 'explicit' 66 | 67 | PLAYLIST = 'playlist' 68 | 69 | PLAYLISTS = 'playlists' 70 | 71 | OWNER = 'owner' 72 | 73 | DISPLAY_NAME = 'display_name' 74 | 75 | ALBUMS = 'albums' 76 | 77 | TYPE = 'type' 78 | 79 | PREMIUM = 'premium' 80 | 81 | USER_READ_EMAIL = 'user-read-email' 82 | 83 | PLAYLIST_READ_PRIVATE = 'playlist-read-private' 84 | 85 | USER_LIBRARY_READ = 'user-library-read' 86 | 87 | WINDOWS_SYSTEM = 'Windows' 88 | 89 | CODEC_MAP = { 90 | 'aac': 'aac', 91 | 'fdk_aac': 'libfdk_aac', 92 | 'm4a': 'aac', 93 | 'mp3': 'libmp3lame', 94 | 'ogg': 'copy', 95 | 'opus': 'libopus', 96 | 'vorbis': 'copy', 97 | } 98 | 99 | EXT_MAP = { 100 | 'aac': 'm4a', 101 | 'fdk_aac': 'm4a', 102 | 'm4a': 'm4a', 103 | 'mp3': 'mp3', 104 | 'ogg': 'ogg', 105 | 'opus': 'ogg', 106 | 'vorbis': 'ogg', 107 | } 108 | -------------------------------------------------------------------------------- /zspotify/loader.py: -------------------------------------------------------------------------------- 1 | # load symbol from: 2 | # https://stackoverflow.com/questions/22029562/python-how-to-make-simple-animated-loading-while-process-is-running 3 | 4 | # imports 5 | from itertools import cycle 6 | from shutil import get_terminal_size 7 | from threading import Thread 8 | from time import sleep 9 | 10 | from termoutput import Printer 11 | 12 | 13 | class Loader: 14 | """Busy symbol. 15 | 16 | Can be called inside a context: 17 | 18 | with Loader("This take some Time..."): 19 | # do something 20 | pass 21 | """ 22 | def __init__(self, chan, desc="Loading...", end='', timeout=0.1, mode='std1'): 23 | """ 24 | A loader-like context manager 25 | 26 | Args: 27 | desc (str, optional): The loader's description. Defaults to "Loading...". 28 | end (str, optional): Final print. Defaults to "". 29 | timeout (float, optional): Sleep time between prints. Defaults to 0.1. 30 | """ 31 | self.desc = desc 32 | self.end = end 33 | self.timeout = timeout 34 | self.channel = chan 35 | 36 | self._thread = Thread(target=self._animate, daemon=True) 37 | if mode == 'std1': 38 | self.steps = ["⢿", "⣻", "⣽", "⣾", "⣷", "⣯", "⣟", "⡿"] 39 | elif mode == 'std2': 40 | self.steps = ["◜","◝","◞","◟"] 41 | elif mode == 'std3': 42 | self.steps = ["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ ","\u3000 ","\u3000 ","\u3000 "] 43 | elif mode == 'prog': 44 | self.steps = ["[∙∙∙]","[●∙∙]","[∙●∙]","[∙∙●]","[∙∙∙]"] 45 | 46 | self.done = False 47 | 48 | def start(self): 49 | self._thread.start() 50 | return self 51 | 52 | def _animate(self): 53 | for c in cycle(self.steps): 54 | if self.done: 55 | break 56 | Printer.print_loader(self.channel, f"\r\t{c} {self.desc} ") 57 | sleep(self.timeout) 58 | 59 | def __enter__(self): 60 | self.start() 61 | 62 | def stop(self): 63 | self.done = True 64 | cols = get_terminal_size((80, 20)).columns 65 | Printer.print_loader(self.channel, "\r" + " " * cols) 66 | 67 | if self.end != "": 68 | Printer.print_loader(self.channel, f"\r{self.end}") 69 | 70 | def __exit__(self, exc_type, exc_value, tb): 71 | # handle exceptions with those variables ^ 72 | self.stop() 73 | -------------------------------------------------------------------------------- /zspotify/playlist.py: -------------------------------------------------------------------------------- 1 | from const import ITEMS, ID, TRACK, NAME 2 | from termoutput import Printer 3 | from track import download_track 4 | from utils import split_input 5 | from zspotify import ZSpotify 6 | 7 | MY_PLAYLISTS_URL = 'https://api.spotify.com/v1/me/playlists' 8 | PLAYLISTS_URL = 'https://api.spotify.com/v1/playlists' 9 | 10 | 11 | def get_all_playlists(): 12 | """ Returns list of users playlists """ 13 | playlists = [] 14 | limit = 50 15 | offset = 0 16 | 17 | while True: 18 | resp = ZSpotify.invoke_url_with_params(MY_PLAYLISTS_URL, limit=limit, offset=offset) 19 | offset += limit 20 | playlists.extend(resp[ITEMS]) 21 | if len(resp[ITEMS]) < limit: 22 | break 23 | 24 | return playlists 25 | 26 | 27 | def get_playlist_songs(playlist_id): 28 | """ returns list of songs in a playlist """ 29 | songs = [] 30 | offset = 0 31 | limit = 100 32 | 33 | while True: 34 | resp = ZSpotify.invoke_url_with_params(f'{PLAYLISTS_URL}/{playlist_id}/tracks', limit=limit, offset=offset) 35 | offset += limit 36 | songs.extend(resp[ITEMS]) 37 | if len(resp[ITEMS]) < limit: 38 | break 39 | 40 | return songs 41 | 42 | 43 | def get_playlist_info(playlist_id): 44 | """ Returns information scraped from playlist """ 45 | (raw, resp) = ZSpotify.invoke_url(f'{PLAYLISTS_URL}/{playlist_id}?fields=name,owner(display_name)&market=from_token') 46 | return resp['name'].strip(), resp['owner']['display_name'].strip() 47 | 48 | 49 | def download_playlist(playlist): 50 | """Downloads all the songs from a playlist""" 51 | 52 | playlist_songs = [song for song in get_playlist_songs(playlist[ID]) if song[TRACK][ID]] 53 | p_bar = Printer.progress(playlist_songs, unit='song', total=len(playlist_songs), unit_scale=True) 54 | enum = 1 55 | for song in p_bar: 56 | download_track('extplaylist', song[TRACK][ID], extra_keys={'playlist': playlist[NAME], 'playlist_num': str(enum).zfill(2)}, disable_progressbar=True) 57 | p_bar.set_description(song[TRACK][NAME]) 58 | enum += 1 59 | 60 | 61 | def download_from_user_playlist(): 62 | """ Select which playlist(s) to download """ 63 | playlists = get_all_playlists() 64 | 65 | count = 1 66 | for playlist in playlists: 67 | print(str(count) + ': ' + playlist[NAME].strip()) 68 | count += 1 69 | 70 | selection = '' 71 | print('\n> SELECT A PLAYLIST BY ID') 72 | print('> SELECT A RANGE BY ADDING A DASH BETWEEN BOTH ID\'s') 73 | print('> OR PARTICULAR OPTIONS BY ADDING A COMMA BETWEEN ID\'s\n') 74 | while len(selection) == 0: 75 | selection = str(input('ID(s): ')) 76 | playlist_choices = map(int, split_input(selection)) 77 | 78 | for playlist_number in playlist_choices: 79 | playlist = playlists[playlist_number - 1] 80 | print(f'Downloading {playlist[NAME].strip()}') 81 | download_playlist(playlist) 82 | 83 | print('\n**All playlists have been downloaded**\n') 84 | -------------------------------------------------------------------------------- /zspotify/podcast.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from typing import Optional, Tuple 4 | 5 | from librespot.metadata import EpisodeId 6 | 7 | from const import ERROR, ID, ITEMS, NAME, SHOW, RELEASE_DATE, DURATION_MS, EXT_MAP 8 | from termoutput import PrintChannel, Printer 9 | from utils import create_download_directory, fix_filename 10 | from track import convert_audio_format 11 | from zspotify import ZSpotify 12 | from loader import Loader 13 | 14 | 15 | EPISODE_INFO_URL = 'https://api.spotify.com/v1/episodes' 16 | SHOWS_URL = 'https://api.spotify.com/v1/shows' 17 | 18 | 19 | def get_episode_info(episode_id_str) -> Tuple[Optional[str], Optional[str]]: 20 | with Loader(PrintChannel.PROGRESS_INFO, "Fetching episode information..."): 21 | (raw, info) = ZSpotify.invoke_url(f'{EPISODE_INFO_URL}/{episode_id_str}') 22 | if not info: 23 | Printer.print(PrintChannel.ERRORS, "### INVALID EPISODE ID ###") 24 | duration_ms = info[DURATION_MS] 25 | if ERROR in info: 26 | return None, None 27 | return fix_filename(info[SHOW][NAME]), duration_ms, fix_filename(info[NAME]), fix_filename(info[RELEASE_DATE]) 28 | 29 | 30 | def get_show_episodes(show_id_str) -> list: 31 | episodes = [] 32 | offset = 0 33 | limit = 50 34 | 35 | with Loader(PrintChannel.PROGRESS_INFO, "Fetching episodes..."): 36 | while True: 37 | resp = ZSpotify.invoke_url_with_params( 38 | f'{SHOWS_URL}/{show_id_str}/episodes', limit=limit, offset=offset) 39 | offset += limit 40 | for episode in resp[ITEMS]: 41 | episodes.append(episode[ID]) 42 | if len(resp[ITEMS]) < limit: 43 | break 44 | 45 | return episodes 46 | 47 | 48 | def download_podcast_directly(url, filename): 49 | import functools 50 | import pathlib 51 | import shutil 52 | import requests 53 | from tqdm.auto import tqdm 54 | 55 | r = requests.get(url, stream=True, allow_redirects=True) 56 | if r.status_code != 200: 57 | r.raise_for_status() # Will only raise for 4xx codes, so... 58 | raise RuntimeError( 59 | f"Request to {url} returned status code {r.status_code}") 60 | file_size = int(r.headers.get('Content-Length', 0)) 61 | 62 | path = pathlib.Path(filename).expanduser().resolve() 63 | path.parent.mkdir(parents=True, exist_ok=True) 64 | 65 | desc = "(Unknown total file size)" if file_size == 0 else "" 66 | r.raw.read = functools.partial( 67 | r.raw.read, decode_content=True) # Decompress if needed 68 | with tqdm.wrapattr(r.raw, "read", total=file_size, desc=desc) as r_raw: 69 | with path.open("wb") as f: 70 | shutil.copyfileobj(r_raw, f) 71 | 72 | return path 73 | 74 | 75 | def download_episode(episode_id) -> None: 76 | podcast_name, duration_ms, episode_name, release_date = get_episode_info(episode_id) 77 | prepare_download_loader = Loader(PrintChannel.PROGRESS_INFO, "Preparing download...") 78 | prepare_download_loader.start() 79 | 80 | if podcast_name is None: 81 | Printer.print(PrintChannel.SKIPS, '### SKIPPING: (EPISODE NOT FOUND) ###') 82 | prepare_download_loader.stop() 83 | else: 84 | ext = EXT_MAP.get(ZSpotify.CONFIG.get_download_format().lower()) 85 | 86 | output_template = ZSpotify.CONFIG.get_output('podcast') 87 | 88 | output_template = output_template.replace("{podcast}", fix_filename(podcast_name)) 89 | output_template = output_template.replace("{episode_name}", fix_filename(episode_name)) 90 | output_template = output_template.replace("{release_date}", fix_filename(release_date)) 91 | output_template = output_template.replace("{ext}", fix_filename(ext)) 92 | 93 | filename = os.path.join(ZSpotify.CONFIG.get_root_podcast_path(), output_template) 94 | download_directory = os.path.dirname(filename) 95 | create_download_directory(download_directory) 96 | 97 | episode_id = EpisodeId.from_base62(episode_id) 98 | stream = ZSpotify.get_content_stream( 99 | episode_id, ZSpotify.DOWNLOAD_QUALITY) 100 | 101 | total_size = stream.input_stream.size 102 | 103 | if ( 104 | os.path.isfile(filename) 105 | and os.path.getsize(filename) == total_size 106 | and ZSpotify.CONFIG.get_skip_existing_files() 107 | ): 108 | Printer.print(PrintChannel.SKIPS, "\n### SKIPPING: " + podcast_name + " - " + episode_name + " (EPISODE ALREADY EXISTS) ###") 109 | prepare_download_loader.stop() 110 | return 111 | 112 | prepare_download_loader.stop() 113 | time_start = time.time() 114 | downloaded = 0 115 | with open(filename, 'wb') as file, Printer.progress( 116 | desc=filename, 117 | total=total_size, 118 | unit='B', 119 | unit_scale=True, 120 | unit_divisor=1024 121 | ) as p_bar: 122 | prepare_download_loader.stop() 123 | while total_size > downloaded: 124 | data = stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size()) 125 | p_bar.update(file.write(data)) 126 | downloaded += len(data) 127 | if len(data) == 0: 128 | break 129 | if ZSpotify.CONFIG.get_download_real_time(): 130 | delta_real = time.time() - time_start 131 | delta_want = (downloaded / total_size) * (duration_ms/1000) 132 | if delta_want > delta_real: 133 | time.sleep(delta_want - delta_real) 134 | 135 | convert_audio_format(filename) 136 | 137 | prepare_download_loader.stop() 138 | -------------------------------------------------------------------------------- /zspotify/termoutput.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from enum import Enum 3 | from tqdm import tqdm 4 | 5 | from config import * 6 | from zspotify import ZSpotify 7 | 8 | 9 | class PrintChannel(Enum): 10 | SPLASH = PRINT_SPLASH 11 | SKIPS = PRINT_SKIPS 12 | DOWNLOAD_PROGRESS = PRINT_DOWNLOAD_PROGRESS 13 | ERRORS = PRINT_ERRORS 14 | WARNINGS = PRINT_WARNINGS 15 | DOWNLOADS = PRINT_DOWNLOADS 16 | API_ERRORS = PRINT_API_ERRORS 17 | PROGRESS_INFO = PRINT_PROGRESS_INFO 18 | 19 | 20 | ERROR_CHANNEL = [PrintChannel.ERRORS, PrintChannel.API_ERRORS] 21 | 22 | 23 | class Printer: 24 | @staticmethod 25 | def print(channel: PrintChannel, msg: str) -> None: 26 | if ZSpotify.CONFIG.get(channel.value): 27 | if channel in ERROR_CHANNEL: 28 | print(msg, file=sys.stderr) 29 | else: 30 | print(msg) 31 | 32 | @staticmethod 33 | def print_loader(channel: PrintChannel, msg: str) -> None: 34 | if ZSpotify.CONFIG.get(channel.value): 35 | print(msg, flush=True, end="") 36 | 37 | @staticmethod 38 | def progress(iterable=None, desc=None, total=None, unit='it', disable=False, unit_scale=False, unit_divisor=1000): 39 | if not ZSpotify.CONFIG.get(PrintChannel.DOWNLOAD_PROGRESS.value): 40 | disable = True 41 | return tqdm(iterable=iterable, desc=desc, total=total, disable=disable, unit=unit, unit_scale=unit_scale, unit_divisor=unit_divisor) 42 | -------------------------------------------------------------------------------- /zspotify/track.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import time 4 | import uuid 5 | from typing import Any, Tuple, List 6 | 7 | from librespot.audio.decoders import AudioQuality 8 | from librespot.metadata import TrackId 9 | from ffmpy import FFmpeg 10 | 11 | from const import TRACKS, ALBUM, GENRES, NAME, ITEMS, DISC_NUMBER, TRACK_NUMBER, IS_PLAYABLE, ARTISTS, IMAGES, URL, \ 12 | RELEASE_DATE, ID, TRACKS_URL, SAVED_TRACKS_URL, TRACK_STATS_URL, CODEC_MAP, EXT_MAP, DURATION_MS, HREF 13 | from termoutput import Printer, PrintChannel 14 | from utils import fix_filename, set_audio_tags, set_music_thumbnail, create_download_directory, \ 15 | get_directory_song_ids, add_to_directory_song_ids, get_previously_downloaded, add_to_archive, fmt_seconds 16 | from zspotify import ZSpotify 17 | import traceback 18 | from loader import Loader 19 | 20 | 21 | def get_saved_tracks() -> list: 22 | """ Returns user's saved tracks """ 23 | songs = [] 24 | offset = 0 25 | limit = 50 26 | 27 | while True: 28 | resp = ZSpotify.invoke_url_with_params( 29 | SAVED_TRACKS_URL, limit=limit, offset=offset) 30 | offset += limit 31 | songs.extend(resp[ITEMS]) 32 | if len(resp[ITEMS]) < limit: 33 | break 34 | 35 | return songs 36 | 37 | 38 | def get_song_info(song_id) -> Tuple[List[str], List[Any], str, str, Any, Any, Any, Any, Any, Any, int]: 39 | """ Retrieves metadata for downloaded songs """ 40 | with Loader(PrintChannel.PROGRESS_INFO, "Fetching track information..."): 41 | (raw, info) = ZSpotify.invoke_url(f'{TRACKS_URL}?ids={song_id}&market=from_token') 42 | 43 | if not TRACKS in info: 44 | raise ValueError(f'Invalid response from TRACKS_URL:\n{raw}') 45 | 46 | try: 47 | artists = [] 48 | for data in info[TRACKS][0][ARTISTS]: 49 | artists.append(data[NAME]) 50 | 51 | album_name = info[TRACKS][0][ALBUM][NAME] 52 | name = info[TRACKS][0][NAME] 53 | image_url = info[TRACKS][0][ALBUM][IMAGES][0][URL] 54 | release_year = info[TRACKS][0][ALBUM][RELEASE_DATE].split('-')[0] 55 | disc_number = info[TRACKS][0][DISC_NUMBER] 56 | track_number = info[TRACKS][0][TRACK_NUMBER] 57 | scraped_song_id = info[TRACKS][0][ID] 58 | is_playable = info[TRACKS][0][IS_PLAYABLE] 59 | duration_ms = info[TRACKS][0][DURATION_MS] 60 | 61 | return artists, info[TRACKS][0][ARTISTS], album_name, name, image_url, release_year, disc_number, track_number, scraped_song_id, is_playable, duration_ms 62 | except Exception as e: 63 | raise ValueError(f'Failed to parse TRACKS_URL response: {str(e)}\n{raw}') 64 | 65 | 66 | def get_song_genres(rawartists: List[str], track_name: str) -> List[str]: 67 | 68 | try: 69 | genres = [] 70 | for data in rawartists: 71 | # query artist genres via href, which will be the api url 72 | with Loader(PrintChannel.PROGRESS_INFO, "Fetching artist information..."): 73 | (raw, artistInfo) = ZSpotify.invoke_url(f'{data[HREF]}') 74 | if ZSpotify.CONFIG.get_all_genres() and len(artistInfo[GENRES]) > 0: 75 | for genre in artistInfo[GENRES]: 76 | genres.append(genre) 77 | elif len(artistInfo[GENRES]) > 0: 78 | genres.append(artistInfo[GENRES][0]) 79 | 80 | if len(genres) == 0: 81 | Printer.print(PrintChannel.WARNINGS, '### No Genres found for song ' + track_name) 82 | genres.append('') 83 | 84 | return genres 85 | except Exception as e: 86 | raise ValueError(f'Failed to parse GENRES response: {str(e)}\n{raw}') 87 | 88 | 89 | def get_song_duration(song_id: str) -> float: 90 | """ Retrieves duration of song in second as is on spotify """ 91 | 92 | (raw, resp) = ZSpotify.invoke_url(f'{TRACK_STATS_URL}{song_id}') 93 | 94 | # get duration in miliseconds 95 | ms_duration = resp['duration_ms'] 96 | # convert to seconds 97 | duration = float(ms_duration)/1000 98 | 99 | # debug 100 | # print(duration) 101 | # print(type(duration)) 102 | 103 | return duration 104 | 105 | 106 | # noinspection PyBroadException 107 | def download_track(mode: str, track_id: str, extra_keys=None, disable_progressbar=False) -> str: 108 | """ Downloads raw song audio from Spotify """ 109 | 110 | if extra_keys is None: 111 | extra_keys = {} 112 | 113 | prepare_download_loader = Loader(PrintChannel.PROGRESS_INFO, "Preparing download...") 114 | prepare_download_loader.start() 115 | 116 | filename = None 117 | 118 | try: 119 | output_template = ZSpotify.CONFIG.get_output(mode) 120 | 121 | (artists, raw_artists, album_name, name, image_url, release_year, disc_number, 122 | track_number, scraped_song_id, is_playable, duration_ms) = get_song_info(track_id) 123 | 124 | song_name = fix_filename(artists[0]) + ' - ' + fix_filename(name) 125 | 126 | for k in extra_keys: 127 | output_template = output_template.replace("{"+k+"}", fix_filename(extra_keys[k])) 128 | 129 | ext = EXT_MAP.get(ZSpotify.CONFIG.get_download_format().lower()) 130 | 131 | output_template = output_template.replace("{artist}", fix_filename(artists[0])) 132 | output_template = output_template.replace("{album}", fix_filename(album_name)) 133 | output_template = output_template.replace("{song_name}", fix_filename(name)) 134 | output_template = output_template.replace("{release_year}", fix_filename(release_year)) 135 | output_template = output_template.replace("{disc_number}", fix_filename(disc_number)) 136 | output_template = output_template.replace("{track_number}", fix_filename(track_number)) 137 | output_template = output_template.replace("{id}", fix_filename(scraped_song_id)) 138 | output_template = output_template.replace("{track_id}", fix_filename(track_id)) 139 | output_template = output_template.replace("{ext}", ext) 140 | 141 | filename = os.path.join(ZSpotify.CONFIG.get_root_path(), output_template) 142 | filedir = os.path.dirname(filename) 143 | 144 | filename_temp = filename 145 | if ZSpotify.CONFIG.get_temp_download_dir() != '': 146 | filename_temp = os.path.join(ZSpotify.CONFIG.get_temp_download_dir(), f'zspotify_{str(uuid.uuid4())}_{track_id}.{ext}') 147 | 148 | check_name = os.path.isfile(filename) and os.path.getsize(filename) 149 | check_id = scraped_song_id in get_directory_song_ids(filedir) 150 | check_all_time = scraped_song_id in get_previously_downloaded() 151 | 152 | # a file with the same name exists in the directory, but song not in the downloaded songs list 153 | if not check_id and check_name and not ZSpotify.CONFIG.get_skip_existing_any_origin(): 154 | c = len([file for file in os.listdir(filedir) if re.search(f'^{filename}_', str(file))]) + 1 155 | 156 | fname = os.path.splitext(os.path.basename(filename))[0] 157 | ext = os.path.splitext(os.path.basename(filename))[1] 158 | 159 | filename = os.path.join(filedir, f'{fname}_{c}{ext}') 160 | 161 | except Exception as e: 162 | Printer.print(PrintChannel.ERRORS, '### SKIPPING SONG - FAILED TO QUERY METADATA ###') 163 | Printer.print(PrintChannel.ERRORS, 'Track_ID: ' + str(track_id)) 164 | for k in extra_keys: 165 | Printer.print(PrintChannel.ERRORS, k + ': ' + str(extra_keys[k])) 166 | Printer.print(PrintChannel.ERRORS, "\n") 167 | Printer.print(PrintChannel.ERRORS, str(e) + "\n") 168 | Printer.print(PrintChannel.ERRORS, "".join(traceback.TracebackException.from_exception(e).format()) + "\n") 169 | 170 | else: 171 | try: 172 | if not is_playable: 173 | prepare_download_loader.stop() 174 | Printer.print(PrintChannel.SKIPS, '\n### SKIPPING: ' + song_name + ' (SONG IS UNAVAILABLE) ###' + "\n") 175 | else: 176 | if check_id and check_name and ZSpotify.CONFIG.get_skip_existing_files(): 177 | prepare_download_loader.stop() 178 | Printer.print(PrintChannel.SKIPS, '\n### SKIPPING: ' + song_name + ' (SONG ALREADY EXISTS) ###' + "\n") 179 | 180 | elif check_name and ZSpotify.CONFIG.get_skip_existing_any_origin(): 181 | prepare_download_loader.stop() 182 | Printer.print(PrintChannel.SKIPS, '\n### SKIPPING: ' + song_name + ' (SONG ALREADY EXISTS BUT WAS NOT DOWNLOADED WITH CLSPOTIFY) ###' + "\n") 183 | 184 | elif check_all_time and ZSpotify.CONFIG.get_skip_previously_downloaded(): 185 | prepare_download_loader.stop() 186 | Printer.print(PrintChannel.SKIPS, '\n### SKIPPING: ' + song_name + ' (SONG ALREADY DOWNLOADED ONCE) ###' + "\n") 187 | 188 | else: 189 | if track_id != scraped_song_id: 190 | track_id = scraped_song_id 191 | track_id = TrackId.from_base62(track_id) 192 | stream = ZSpotify.get_content_stream(track_id, ZSpotify.DOWNLOAD_QUALITY) 193 | create_download_directory(filedir) 194 | total_size = stream.input_stream.size 195 | 196 | prepare_download_loader.stop() 197 | 198 | time_start = time.time() 199 | downloaded = 0 200 | with open(filename_temp, 'wb') as file, Printer.progress( 201 | desc=song_name, 202 | total=total_size, 203 | unit='B', 204 | unit_scale=True, 205 | unit_divisor=1024, 206 | disable=disable_progressbar 207 | ) as p_bar: 208 | while total_size > downloaded: 209 | data = stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size()) 210 | p_bar.update(file.write(data)) 211 | downloaded += len(data) 212 | if len(data) == 0: 213 | break 214 | if ZSpotify.CONFIG.get_download_real_time(): 215 | delta_real = time.time() - time_start 216 | delta_want = (downloaded / total_size) * (duration_ms/1000) 217 | if delta_want > delta_real: 218 | time.sleep(delta_want - delta_real) 219 | 220 | time_downloaded = time.time() 221 | 222 | genres = get_song_genres(raw_artists, name) 223 | 224 | convert_audio_format(filename_temp) 225 | set_audio_tags(filename_temp, artists, genres, name, album_name, release_year, disc_number, track_number) 226 | set_music_thumbnail(filename_temp, image_url) 227 | 228 | if filename_temp != filename: 229 | os.rename(filename_temp, filename) 230 | 231 | time_finished = time.time() 232 | 233 | Printer.print(PrintChannel.DOWNLOADS, f'### Downloaded "{song_name}" to "{os.path.relpath(filename, ZSpotify.CONFIG.get_root_path())}" in {fmt_seconds(time_downloaded - time_start)} (plus {fmt_seconds(time_finished - time_downloaded)} converting) ###' + "\n") 234 | 235 | # add song id to archive file 236 | if ZSpotify.CONFIG.get_skip_previously_downloaded(): 237 | add_to_archive(scraped_song_id, os.path.basename(filename), artists[0], name) 238 | # add song id to download directory's .song_ids file 239 | if not check_id: 240 | add_to_directory_song_ids(filedir, scraped_song_id, os.path.basename(filename), artists[0], name) 241 | 242 | if not ZSpotify.CONFIG.get_anti_ban_wait_time(): 243 | time.sleep(ZSpotify.CONFIG.get_anti_ban_wait_time()) 244 | except Exception as e: 245 | Printer.print(PrintChannel.ERRORS, '### SKIPPING: ' + song_name + ' (GENERAL DOWNLOAD ERROR) ###') 246 | Printer.print(PrintChannel.ERRORS, 'Track_ID: ' + str(track_id)) 247 | for k in extra_keys: 248 | Printer.print(PrintChannel.ERRORS, k + ': ' + str(extra_keys[k])) 249 | Printer.print(PrintChannel.ERRORS, "\n") 250 | Printer.print(PrintChannel.ERRORS, str(e) + "\n") 251 | Printer.print(PrintChannel.ERRORS, "".join(traceback.TracebackException.from_exception(e).format()) + "\n") 252 | if os.path.exists(filename_temp): 253 | os.remove(filename_temp) 254 | 255 | prepare_download_loader.stop() 256 | return filename 257 | 258 | 259 | def convert_audio_format(filename) -> None: 260 | """ Converts raw audio into playable file """ 261 | temp_filename = f'{os.path.splitext(filename)[0]}.tmp' 262 | os.replace(filename, temp_filename) 263 | 264 | download_format = ZSpotify.CONFIG.get_download_format().lower() 265 | file_codec = CODEC_MAP.get(download_format, 'copy') 266 | if file_codec != 'copy': 267 | bitrate = ZSpotify.CONFIG.get_bitrate() 268 | if not bitrate: 269 | if ZSpotify.DOWNLOAD_QUALITY == AudioQuality.VERY_HIGH: 270 | bitrate = '320k' 271 | else: 272 | bitrate = '160k' 273 | else: 274 | bitrate = None 275 | 276 | output_params = ['-c:a', file_codec] 277 | if bitrate: 278 | output_params += ['-b:a', bitrate] 279 | 280 | ff_m = FFmpeg( 281 | global_options=['-y', '-hide_banner', '-loglevel error'], 282 | inputs={temp_filename: None}, 283 | outputs={filename: output_params} 284 | ) 285 | 286 | with Loader(PrintChannel.PROGRESS_INFO, "Converting file..."): 287 | ff_m.run() 288 | 289 | if os.path.exists(temp_filename): 290 | os.remove(temp_filename) 291 | -------------------------------------------------------------------------------- /zspotify/utils.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import math 3 | import os 4 | import platform 5 | import re 6 | import subprocess 7 | from enum import Enum 8 | from typing import List, Tuple 9 | 10 | import music_tag 11 | import requests 12 | 13 | from const import ARTIST, GENRE, TRACKTITLE, ALBUM, YEAR, DISCNUMBER, TRACKNUMBER, ARTWORK, \ 14 | WINDOWS_SYSTEM, ALBUMARTIST 15 | from zspotify import ZSpotify 16 | 17 | 18 | class MusicFormat(str, Enum): 19 | MP3 = 'mp3', 20 | OGG = 'ogg', 21 | 22 | 23 | def create_download_directory(download_path: str) -> None: 24 | """ Create directory and add a hidden file with song ids """ 25 | os.makedirs(download_path, exist_ok=True) 26 | 27 | # add hidden file with song ids 28 | hidden_file_path = os.path.join(download_path, '.song_ids') 29 | if not os.path.isfile(hidden_file_path): 30 | with open(hidden_file_path, 'w', encoding='utf-8') as f: 31 | pass 32 | 33 | 34 | def get_previously_downloaded() -> List[str]: 35 | """ Returns list of all time downloaded songs """ 36 | 37 | ids = [] 38 | archive_path = ZSpotify.CONFIG.get_song_archive() 39 | 40 | if os.path.exists(archive_path): 41 | with open(archive_path, 'r', encoding='utf-8') as f: 42 | ids = [line.strip().split('\t')[0] for line in f.readlines()] 43 | 44 | return ids 45 | 46 | 47 | def add_to_archive(song_id: str, filename: str, author_name: str, song_name: str) -> None: 48 | """ Adds song id to all time installed songs archive """ 49 | 50 | archive_path = ZSpotify.CONFIG.get_song_archive() 51 | 52 | if os.path.exists(archive_path): 53 | with open(archive_path, 'a', encoding='utf-8') as file: 54 | file.write(f'{song_id}\t{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\t{author_name}\t{song_name}\t{filename}\n') 55 | else: 56 | with open(archive_path, 'w', encoding='utf-8') as file: 57 | file.write(f'{song_id}\t{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\t{author_name}\t{song_name}\t{filename}\n') 58 | 59 | 60 | def get_directory_song_ids(download_path: str) -> List[str]: 61 | """ Gets song ids of songs in directory """ 62 | 63 | song_ids = [] 64 | 65 | hidden_file_path = os.path.join(download_path, '.song_ids') 66 | if os.path.isfile(hidden_file_path): 67 | with open(hidden_file_path, 'r', encoding='utf-8') as file: 68 | song_ids.extend([line.strip().split('\t')[0] for line in file.readlines()]) 69 | 70 | return song_ids 71 | 72 | 73 | def add_to_directory_song_ids(download_path: str, song_id: str, filename: str, author_name: str, song_name: str) -> None: 74 | """ Appends song_id to .song_ids file in directory """ 75 | 76 | hidden_file_path = os.path.join(download_path, '.song_ids') 77 | # not checking if file exists because we need an exception 78 | # to be raised if something is wrong 79 | with open(hidden_file_path, 'a', encoding='utf-8') as file: 80 | file.write(f'{song_id}\t{datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\t{author_name}\t{song_name}\t{filename}\n') 81 | 82 | 83 | def get_downloaded_song_duration(filename: str) -> float: 84 | """ Returns the downloaded file's duration in seconds """ 85 | 86 | command = ['ffprobe', '-show_entries', 'format=duration', '-i', f'{filename}'] 87 | output = subprocess.run(command, capture_output=True) 88 | 89 | duration = re.search(r'[\D]=([\d\.]*)', str(output.stdout)).groups()[0] 90 | duration = float(duration) 91 | 92 | return duration 93 | 94 | 95 | def split_input(selection) -> List[str]: 96 | """ Returns a list of inputted strings """ 97 | inputs = [] 98 | if '-' in selection: 99 | for number in range(int(selection.split('-')[0]), int(selection.split('-')[1]) + 1): 100 | inputs.append(number) 101 | else: 102 | selections = selection.split(',') 103 | for i in selections: 104 | inputs.append(i.strip()) 105 | return inputs 106 | 107 | 108 | def splash() -> str: 109 | """ Displays splash screen """ 110 | return """ 111 | ███████ ███████ ██████ ██████ ████████ ██ ███████ ██ ██ 112 | ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ 113 | ███ ███████ ██████ ██ ██ ██ ██ █████ ████ 114 | ███ ██ ██ ██ ██ ██ ██ ██ ██ 115 | ███████ ███████ ██ ██████ ██ ██ ██ ██ 116 | """ 117 | 118 | 119 | def clear() -> None: 120 | """ Clear the console window """ 121 | if platform.system() == WINDOWS_SYSTEM: 122 | os.system('cls') 123 | else: 124 | os.system('clear') 125 | 126 | 127 | def set_audio_tags(filename, artists, genres, name, album_name, release_year, disc_number, track_number) -> None: 128 | """ sets music_tag metadata """ 129 | tags = music_tag.load_file(filename) 130 | tags[ALBUMARTIST] = artists[0] 131 | tags[ARTIST] = conv_artist_format(artists) 132 | tags[GENRE] = genres[0] if not ZSpotify.CONFIG.get_all_genres() else ZSpotify.CONFIG.get_all_genres_delimiter().join(genres) 133 | tags[TRACKTITLE] = name 134 | tags[ALBUM] = album_name 135 | tags[YEAR] = release_year 136 | tags[DISCNUMBER] = disc_number 137 | tags[TRACKNUMBER] = track_number 138 | tags.save() 139 | 140 | 141 | def conv_artist_format(artists) -> str: 142 | """ Returns converted artist format """ 143 | return ', '.join(artists) 144 | 145 | 146 | def set_music_thumbnail(filename, image_url) -> None: 147 | """ Downloads cover artwork """ 148 | img = requests.get(image_url).content 149 | tags = music_tag.load_file(filename) 150 | tags[ARTWORK] = img 151 | tags.save() 152 | 153 | 154 | def regex_input_for_urls(search_input) -> Tuple[str, str, str, str, str, str]: 155 | """ Since many kinds of search may be passed at the command line, process them all here. """ 156 | track_uri_search = re.search( 157 | r'^spotify:track:(?P[0-9a-zA-Z]{22})$', search_input) 158 | track_url_search = re.search( 159 | r'^(https?://)?open\.spotify\.com/track/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 160 | search_input, 161 | ) 162 | 163 | album_uri_search = re.search( 164 | r'^spotify:album:(?P[0-9a-zA-Z]{22})$', search_input) 165 | album_url_search = re.search( 166 | r'^(https?://)?open\.spotify\.com/album/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 167 | search_input, 168 | ) 169 | 170 | playlist_uri_search = re.search( 171 | r'^spotify:playlist:(?P[0-9a-zA-Z]{22})$', search_input) 172 | playlist_url_search = re.search( 173 | r'^(https?://)?open\.spotify\.com/playlist/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 174 | search_input, 175 | ) 176 | 177 | episode_uri_search = re.search( 178 | r'^spotify:episode:(?P[0-9a-zA-Z]{22})$', search_input) 179 | episode_url_search = re.search( 180 | r'^(https?://)?open\.spotify\.com/episode/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 181 | search_input, 182 | ) 183 | 184 | show_uri_search = re.search( 185 | r'^spotify:show:(?P[0-9a-zA-Z]{22})$', search_input) 186 | show_url_search = re.search( 187 | r'^(https?://)?open\.spotify\.com/show/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 188 | search_input, 189 | ) 190 | 191 | artist_uri_search = re.search( 192 | r'^spotify:artist:(?P[0-9a-zA-Z]{22})$', search_input) 193 | artist_url_search = re.search( 194 | r'^(https?://)?open\.spotify\.com/artist/(?P[0-9a-zA-Z]{22})(\?si=.+?)?$', 195 | search_input, 196 | ) 197 | 198 | if track_uri_search is not None or track_url_search is not None: 199 | track_id_str = (track_uri_search 200 | if track_uri_search is not None else 201 | track_url_search).group('TrackID') 202 | else: 203 | track_id_str = None 204 | 205 | if album_uri_search is not None or album_url_search is not None: 206 | album_id_str = (album_uri_search 207 | if album_uri_search is not None else 208 | album_url_search).group('AlbumID') 209 | else: 210 | album_id_str = None 211 | 212 | if playlist_uri_search is not None or playlist_url_search is not None: 213 | playlist_id_str = (playlist_uri_search 214 | if playlist_uri_search is not None else 215 | playlist_url_search).group('PlaylistID') 216 | else: 217 | playlist_id_str = None 218 | 219 | if episode_uri_search is not None or episode_url_search is not None: 220 | episode_id_str = (episode_uri_search 221 | if episode_uri_search is not None else 222 | episode_url_search).group('EpisodeID') 223 | else: 224 | episode_id_str = None 225 | 226 | if show_uri_search is not None or show_url_search is not None: 227 | show_id_str = (show_uri_search 228 | if show_uri_search is not None else 229 | show_url_search).group('ShowID') 230 | else: 231 | show_id_str = None 232 | 233 | if artist_uri_search is not None or artist_url_search is not None: 234 | artist_id_str = (artist_uri_search 235 | if artist_uri_search is not None else 236 | artist_url_search).group('ArtistID') 237 | else: 238 | artist_id_str = None 239 | 240 | return track_id_str, album_id_str, playlist_id_str, episode_id_str, show_id_str, artist_id_str 241 | 242 | 243 | def fix_filename(name): 244 | """ 245 | Replace invalid characters on Linux/Windows/MacOS with underscores. 246 | List from https://stackoverflow.com/a/31976060/819417 247 | Trailing spaces & periods are ignored on Windows. 248 | >>> fix_filename(" COM1 ") 249 | '_ COM1 _' 250 | >>> fix_filename("COM10") 251 | 'COM10' 252 | >>> fix_filename("COM1,") 253 | 'COM1,' 254 | >>> fix_filename("COM1.txt") 255 | '_.txt' 256 | >>> all('_' == fix_filename(chr(i)) for i in list(range(32))) 257 | True 258 | """ 259 | return re.sub(r'[/\\:|<>"?*\0-\x1f]|^(AUX|COM[1-9]|CON|LPT[1-9]|NUL|PRN)(?![^.])|^\s|[\s.]$', "_", str(name), flags=re.IGNORECASE) 260 | 261 | 262 | def fmt_seconds(secs: float) -> str: 263 | val = math.floor(secs) 264 | 265 | s = math.floor(val % 60) 266 | val -= s 267 | val /= 60 268 | 269 | m = math.floor(val % 60) 270 | val -= m 271 | val /= 60 272 | 273 | h = math.floor(val) 274 | 275 | if h == 0 and m == 0 and s == 0: 276 | return "0s" 277 | elif h == 0 and m == 0: 278 | return f'{s}s'.zfill(2) 279 | elif h == 0: 280 | return f'{m}'.zfill(2) + ':' + f'{s}'.zfill(2) 281 | else: 282 | return f'{h}'.zfill(2) + ':' + f'{m}'.zfill(2) + ':' + f'{s}'.zfill(2) 283 | 284 | 285 | -------------------------------------------------------------------------------- /zspotify/zspotify.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | from getpass import getpass 4 | import time 5 | import requests 6 | from librespot.audio.decoders import VorbisOnlyAudioQuality 7 | from librespot.core import Session 8 | 9 | from const import TYPE, \ 10 | PREMIUM, USER_READ_EMAIL, OFFSET, LIMIT, \ 11 | PLAYLIST_READ_PRIVATE, USER_LIBRARY_READ 12 | from config import Config 13 | 14 | class ZSpotify: 15 | SESSION: Session = None 16 | DOWNLOAD_QUALITY = None 17 | CONFIG: Config = Config() 18 | 19 | def __init__(self, args): 20 | ZSpotify.CONFIG.load(args) 21 | ZSpotify.login() 22 | 23 | @classmethod 24 | def login(cls): 25 | """ Authenticates with Spotify and saves credentials to a file """ 26 | 27 | cred_location = Config.get_credentials_location() 28 | 29 | if os.path.isfile(cred_location): 30 | try: 31 | cls.SESSION = Session.Builder().stored_file(cred_location).create() 32 | return 33 | except RuntimeError: 34 | pass 35 | while True: 36 | user_name = '' 37 | while len(user_name) == 0: 38 | user_name = input('Username: ') 39 | password = getpass() 40 | try: 41 | conf = Session.Configuration.Builder().set_stored_credential_file(cred_location).build() 42 | cls.SESSION = Session.Builder(conf).user_pass(user_name, password).create() 43 | return 44 | except RuntimeError: 45 | pass 46 | 47 | @classmethod 48 | def get_content_stream(cls, content_id, quality): 49 | return cls.SESSION.content_feeder().load(content_id, VorbisOnlyAudioQuality(quality), False, None) 50 | 51 | @classmethod 52 | def __get_auth_token(cls): 53 | return cls.SESSION.tokens().get_token(USER_READ_EMAIL, PLAYLIST_READ_PRIVATE, USER_LIBRARY_READ).access_token 54 | 55 | @classmethod 56 | def get_auth_header(cls): 57 | return { 58 | 'Authorization': f'Bearer {cls.__get_auth_token()}', 59 | 'Accept-Language': f'{cls.CONFIG.get_language()}' 60 | } 61 | 62 | @classmethod 63 | def get_auth_header_and_params(cls, limit, offset): 64 | return { 65 | 'Authorization': f'Bearer {cls.__get_auth_token()}', 66 | 'Accept-Language': f'{cls.CONFIG.get_language()}' 67 | }, {LIMIT: limit, OFFSET: offset} 68 | 69 | @classmethod 70 | def invoke_url_with_params(cls, url, limit, offset, **kwargs): 71 | headers, params = cls.get_auth_header_and_params(limit=limit, offset=offset) 72 | params.update(kwargs) 73 | return requests.get(url, headers=headers, params=params).json() 74 | 75 | @classmethod 76 | def invoke_url(cls, url, tryCount=0): 77 | # we need to import that here, otherwise we will get circular imports! 78 | from termoutput import Printer, PrintChannel 79 | headers = cls.get_auth_header() 80 | response = requests.get(url, headers=headers) 81 | responsetext = response.text 82 | responsejson = response.json() 83 | 84 | if 'error' in responsejson: 85 | if tryCount < (cls.CONFIG.get_retry_attempts() - 1): 86 | Printer.print(PrintChannel.WARNINGS, f"Spotify API Error (try {tryCount + 1}) ({responsejson['error']['status']}): {responsejson['error']['message']}") 87 | time.sleep(5) 88 | return cls.invoke_url(url, tryCount + 1) 89 | 90 | Printer.print(PrintChannel.API_ERRORS, f"Spotify API Error ({responsejson['error']['status']}): {responsejson['error']['message']}") 91 | 92 | return responsetext, responsejson 93 | 94 | @classmethod 95 | def check_premium(cls) -> bool: 96 | """ If user has spotify premium return true """ 97 | return (cls.SESSION.get_user_attribute(TYPE) == PREMIUM) or cls.CONFIG.get_force_premium() 98 | --------------------------------------------------------------------------------