From 03151f246d74e099a83454695a2aa611275fc475 Mon Sep 17 00:00:00 2001 From: Alex Blank Date: Sat, 13 Aug 2022 18:00:14 +0200 Subject: [PATCH] initial commit --- .gitignore | 215 +++++++++++++++++++++++++++++++++++++++++ playlist_downloader.py | 40 ++++++++ requirements.txt | 2 + spotdl_connector.py | 25 +++++ spotify_connection.py | 28 ++++++ 5 files changed, 310 insertions(+) create mode 100644 .gitignore create mode 100644 playlist_downloader.py create mode 100644 requirements.txt create mode 100644 spotdl_connector.py create mode 100644 spotify_connection.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6827ee3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,215 @@ +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/ +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +additional_playlists.txt \ No newline at end of file diff --git a/playlist_downloader.py b/playlist_downloader.py new file mode 100644 index 0000000..351f307 --- /dev/null +++ b/playlist_downloader.py @@ -0,0 +1,40 @@ +import sys +import os + +from spotdl_connector import download_playlist +from spotify_connection import get_playlists_by_user, get_playlist_info + +ADDITIONAL_PLAYLIST_FILE = "additional_playlists.txt" + + +def main() -> None: + # check for parameters + if len(sys.argv) < 3: + print("Usage: python playlists_downloader.py ") + sys.exit(1) + username = sys.argv[1] + playlist_root = sys.argv[2] + + # check for additional playlists + if os.path.isfile(ADDITIONAL_PLAYLIST_FILE): + with open(ADDITIONAL_PLAYLIST_FILE, "r") as pl_file: + additional_playlists_raw = pl_file.readlines() + + additional_playlists = [get_playlist_info(pl_uri) for pl_uri in additional_playlists_raw] + + else: + additional_playlists = list() + + user_playlists = get_playlists_by_user(username) + playlists = user_playlists + additional_playlists + + print(f"Downloading {len(user_playlists)} public playlist(s) by {username}") + print(f"Downloading {len(additional_playlists)} additional playlist(s)") + print(f"Root for playlist folders: {playlist_root}") + [download_playlist(pl, playlist_root) for pl in playlists] + + print("Done.") + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..15dc8ac --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +spotdl +spotipy \ No newline at end of file diff --git a/spotdl_connector.py b/spotdl_connector.py new file mode 100644 index 0000000..7a3da1f --- /dev/null +++ b/spotdl_connector.py @@ -0,0 +1,25 @@ +import os + + +def download_playlist(playlist: dict, playlist_root: str) -> None: + print(f"Downloading playlist {playlist['name']}") + + # create playlist root, if not done yet + try: + os.mkdir(playlist_root) + except FileExistsError: + pass + os.chdir(playlist_root) + + # create playlist folder if not don yet + playlist_dir = os.path.join(playlist_root, playlist["name"]) + try: + os.mkdir(playlist_dir) + print(f"Playlist folder for {playlist['name']} created") + except FileExistsError: + print(f"Playlist folder for {playlist['name']} already created") + + os.chdir(playlist_dir) + + command = f"spotdl {playlist['external_urls']['spotify']}" + os.system(command) diff --git a/spotify_connection.py b/spotify_connection.py new file mode 100644 index 0000000..2018b82 --- /dev/null +++ b/spotify_connection.py @@ -0,0 +1,28 @@ +import spotipy +from spotipy.oauth2 import SpotifyClientCredentials + +auth_manager = SpotifyClientCredentials() +sp = spotipy.Spotify(auth_manager=auth_manager) + + +def get_playlists_by_user(username: str) -> list: + def fetch_playlists(username: str, playlists: list = None, limit=50) -> list: + + if playlists is None: + playlists = list() + + batch = sp.user_playlists(username, limit=limit, offset=len(playlists))["items"] + new_playlists = playlists + batch + + if len(batch) < limit: + return new_playlists + + return fetch_playlists(username, new_playlists) + + return fetch_playlists(username) + + +def get_playlist_info(playlist_uri: str) -> dict: + # extract id from uri and remove query parameters + playlist_id = playlist_uri.split('/')[-1].split('?')[0] + return sp.playlist(playlist_id)