commit aad6fdf150700a7c9a13dc4eee05ea058d42d19f Author: oitsjustjose Date: Wed Sep 17 10:56:47 2025 -0500 Initial commit diff --git a/.envrc.example b/.envrc.example new file mode 100644 index 0000000..bdcd898 --- /dev/null +++ b/.envrc.example @@ -0,0 +1,9 @@ +export SPOTIPY_CLIENT_ID= # REPLACE THIS +export SPOTIPY_CLIENT_SECRET= # REPLACE THIS +export SPOTIPY_REDIRECT_URI= # REPLACE THIS + +export YT_MUSIC_AUTH= # REPLACE THIS +export YT_MUSIC_COOKIE= # REPLACE THIS + +export GOOGLE_CLIENT_ID= # REPLACE THIS +export GOOGLE_CLIENT_SECRET= # REPLACE THIS \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11d0214 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.envrc +.venv +__pycache__ +oauth.json +out.json +resp.json +.cache diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..bd36a10 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,12 @@ +{ + "configurations": [ + { + "name": "Python Debugger: Current File", + "type": "debugpy", + "request": "launch", + "module": "src.main", + "console": "integratedTerminal", + "justMyCode": false + } + ] +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..18ecfd8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +spotipy==2.25.1 +ytmusicapi @ git+https://github.com/Goldenfreddy0703/ytmusicapi.git@43971eb7d5609eef0ca0cc0350f44d645eb9242f diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..f32b016 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,9 @@ +from dataclasses import dataclass +from typing import Union, List + + +@dataclass +class Song: + name: str + artist: Union[str, List[str]] + album: str diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..1f82998 --- /dev/null +++ b/src/main.py @@ -0,0 +1,6 @@ +from src.ytmusic import get_all_songs_from_library +import json + +all_songs = get_all_songs_from_library() +with open("out.json", "w") as fh: + fh.write(json.dumps([{"title": x.name, "album": x.album, "artist": x.artist} for x in all_songs], indent=2)) diff --git a/src/spotify.py b/src/spotify.py new file mode 100644 index 0000000..b300178 --- /dev/null +++ b/src/spotify.py @@ -0,0 +1,19 @@ +from spotipy import Spotify +from spotipy.oauth2 import SpotifyClientCredentials +from typing import List, Union + + +_INSTANCE: Union[Spotify, None] + + +def get_instance(): + global _INSTANCE + + if not _INSTANCE: + auth_manager = SpotifyClientCredentials() + _INSTANCE = Spotify(auth_manager=auth_manager) + + return _INSTANCE + + +get_instance().user diff --git a/src/ytmusic.py b/src/ytmusic.py new file mode 100644 index 0000000..90e52c5 --- /dev/null +++ b/src/ytmusic.py @@ -0,0 +1,124 @@ +from os import environ +from typing import List, Union + +from ytmusicapi import OAuthCredentials, YTMusic + +from src import Song + +_INSTANCE: Union[YTMusic, None] = None +UNK = "Unknown" + + +def get_instance() -> YTMusic: + """Gets the YTMusic Singleton Instance + + Raises: + Exception: When GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET are not vaild environment variables + + Returns: + YTMusic: The existing, or newly created, singleton instance of YTMusic + """ + global _INSTANCE + + client_id = environ.get("GOOGLE_CLIENT_ID", "") + if not client_id: + raise Exception("GOOGLE_CLIENT_ID environment variable cannot be empty!") + + client_secret = environ.get("GOOGLE_CLIENT_SECRET", "") + if not client_secret: + raise Exception("GOOGLE_CLIENT_SECRET environment variable cannot be empty!") + + if not _INSTANCE: + _INSTANCE = YTMusic( + "oauth.json", # TODO: Get abspath? + oauth_credentials=OAuthCredentials(client_id=client_id, client_secret=client_secret), + ) + + return _INSTANCE + + +def to_song(raw: dict) -> Song: + """Converts a single raw track from the YTMusic API into our dataclass form + Performs parsing and fallback logic to use "Unknown" for any unparsed / + empty fields + + Args: + raw (dict): The dictionary object for the individual track + + Returns: + Song: A Song dataclass instance with the fields parsed properly + """ + + def __get_field_safe(field: str) -> str: + """Gets a field from the raw dictionary object, returning "Unknown" if + the field isn't found in the object or if the field exists but is None + + Args: + field (str): The field to lookup and validate + + Returns: + str: The field or "Unknown" as a fallback + """ + if field not in raw: + return UNK + return raw[field] or UNK + + def __get_artists_safe(field: str) -> Union[List[str], str]: + """Parses the artists in a relatively safe way, slightly different process + than that of the other two fields because a track may have multiple + artists and we want to parse that. If there are multiple, a list of + strings are returned, otherwise just a string is returned. + + Like the standard safe field lookup, will return "Unknown" if the field + doesn't exist in the object or if the field exists but is None + + Args: + field (str): The field to lookup and validate + + Returns: + Union[List[str], str]: + - List[str] if multiple artists are present + - str if only a single artist is present, or if the field cannot be found + or the field is None (in which case "Unknown" is returned) + """ + if field not in raw: + return UNK + if not raw[field]: + return UNK + val = [x["name"] for x in raw[field]] + return val[0] if len(val) == 1 else val + + title = __get_field_safe("title") + artists = __get_artists_safe("artists") + album = __get_field_safe("album") + return Song(title, artists, album) + + +def get_all_songs_from_library() -> List[Song]: + """Gets all songs from the Liked Songs 'playlist' in YTMusic for the + currently authed user. + + Raises: + Exception: When YT_MUSIC_AUTH or YT_MUSIC_COOKIE are not valid environment variables + + Returns: + List[Song]: A list of parsed Songs from the user's library + """ + + ytmusic = get_instance() + + auth = environ.get("YT_MUSIC_AUTH", "") + if not auth: + raise Exception("YT_MUSIC_AUTH environment variable cannot be empty!") + + cookie = environ.get("YT_MUSIC_COOKIE", "") + if not cookie: + raise Exception("YT_MUSIC_COOKIE environment variable cannot be empty!") + + ytmusic.headers["Cookie"] = cookie + ytmusic.headers["authorization"] = auth + + songs = ytmusic.get_liked_songs(limit=None) # type: ignore -- limit=None works and gets _all_ songs, and there's no pagination method + songs = songs["tracks"] + + return [to_song(x) for x in songs]