Skip to content

Commit

Permalink
Merge pull request #25 from rnagabhyrava/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
rnagabhyrava authored Jul 11, 2022
2 parents 7c87391 + 6e1694b commit afe014f
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 30 deletions.
30 changes: 16 additions & 14 deletions plex-playlist-sync/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,18 @@

# Read ENV variables
userInputs = UserInputs(
plex_url=os.environ.get("PLEX_URL"),
plex_token=os.environ.get("PLEX_TOKEN"),
write_missing_as_csv=os.environ.get("WRITE_MISSING_AS_CSV", "0") == "1",
add_playlist_poster=os.environ.get("ADD_PLAYLIST_POSTER", "1") == "1",
add_playlist_description=os.environ.get("ADD_PLAYLIST_DESCRIPTION", "1") == "1",
append_instead_of_sync=os.environ.get("APPEND_INSTEAD_OF_SYNC", False) == "1",
wait_seconds=int(os.environ.get("SECONDS_TO_WAIT", 86400)),
spotipy_client_id=os.environ.get("SPOTIFY_CLIENT_ID"),
spotipy_client_secret=os.environ.get("SPOTIFY_CLIENT_SECRET"),
spotify_user_id=os.environ.get("SPOTIFY_USER_ID"),
deezer_user_id=os.environ.get("DEEZER_USER_ID"),
deezer_playlist_ids=os.environ.get("DEEZER_PLAYLIST_ID"),
plex_url=os.getenv("PLEX_URL"),
plex_token=os.getenv("PLEX_TOKEN"),
write_missing_as_csv=os.getenv("WRITE_MISSING_AS_CSV", "0") == "1",
add_playlist_poster=os.getenv("ADD_PLAYLIST_POSTER", "1") == "1",
add_playlist_description=os.getenv("ADD_PLAYLIST_DESCRIPTION", "1") == "1",
append_instead_of_sync=os.getenv("APPEND_INSTEAD_OF_SYNC", False) == "1",
wait_seconds=int(os.getenv("SECONDS_TO_WAIT", 86400)),
spotipy_client_id=os.getenv("SPOTIFY_CLIENT_ID"),
spotipy_client_secret=os.getenv("SPOTIFY_CLIENT_SECRET"),
spotify_user_id=os.getenv("SPOTIFY_USER_ID"),
deezer_user_id=os.getenv("DEEZER_USER_ID"),
deezer_playlist_ids=os.getenv("DEEZER_PLAYLIST_ID"),
)
while True:
logging.info("Starting playlist sync")
Expand Down Expand Up @@ -53,7 +53,8 @@
try:
sp = spotipy.Spotify(
auth_manager=SpotifyClientCredentials(
userInputs.spotipy_client_id, userInputs.spotipy_client_secret
userInputs.spotipy_client_id,
userInputs.spotipy_client_secret,
)
)
SP_AUTHSUCCESS = True
Expand All @@ -62,7 +63,8 @@

else:
logging.info(
"Missing one or more Spotify Authorization Variables, skipping spotify sync"
"Missing one or more Spotify Authorization Variables, skipping"
" spotify sync"
)

if SP_AUTHSUCCESS:
Expand Down
10 changes: 7 additions & 3 deletions plex-playlist-sync/utils/deezer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ def _get_dz_playlists(

if userInputs.deezer_user_id:
try:
dz_user_playlists = dz.get_user(userInputs.deezer_user_id).get_playlists()
dz_user_playlists = dz.get_user(
userInputs.deezer_user_id
).get_playlists()
except:
dz_user_playlists = []
logging.info(
"Can't get playlists from this user, skipping deezer user playlists"
"Can't get playlists from this user, skipping deezer user"
" playlists"
)

if userInputs.deezer_playlist_ids:
Expand All @@ -42,7 +45,8 @@ def _get_dz_playlists(
except:
dz_id_playlists = []
logging.info(
"Unable to get the playlists from given ids, skipping deezer playlists for IDs"
"Unable to get the playlists from given ids, skipping deezer"
" playlists for IDs"
)

dz_playlists = list(set(dz_user_playlists + dz_id_playlists))
Expand Down
62 changes: 50 additions & 12 deletions plex-playlist-sync/utils/plex.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from difflib import SequenceMatcher
from typing import List

import plexapi
from plexapi.exceptions import BadRequest, NotFound
from plexapi.server import PlexServer

Expand All @@ -18,7 +19,8 @@ def _write_csv(tracks: List[Track], name: str, path: str = "/data") -> None:
Args:
tracks (List[Track]): List of Track objects
name (str): Name of the file to write to
name (str): Name of the file to write
path (str): Root directory to write the file
"""
# pathlib.Path(path).mkdir(parents=True, exist_ok=True)

Expand All @@ -28,9 +30,23 @@ def _write_csv(tracks: List[Track], name: str, path: str = "/data") -> None:

with open(file, "w", encoding="utf-8") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["title", "artist", "album", "url"])
writer.writerow(Track.__annotations__.keys())
for track in tracks:
writer.writerow([track.title, track.artist, track.album, track.url])
writer.writerow(
[track.title, track.artist, track.album, track.url]
)


def _delete_csv(name: str, path: str = "/data") -> None:
"""Delete file associated with given name
Args:
name (str): Name of the file to delete
path (str, optional): Root directory to delete the file from
"""
data_folder = pathlib.Path(path)
file = data_folder / f"{name}.csv"
file.unlink()


def _get_available_plex_tracks(plex: PlexServer, tracks: List[Track]) -> List:
Expand Down Expand Up @@ -84,8 +100,9 @@ def _get_available_plex_tracks(plex: PlexServer, tracks: List[Track]) -> List:

except IndexError:
logging.info(
"Looks like plex mismatched the search for %s, retrying with next result",
track,
"Looks like plex mismatched the search for %s,"
" retrying with next result",
track.title,
)
if not found:
missing_tracks.append(track)
Expand All @@ -94,17 +111,21 @@ def _get_available_plex_tracks(plex: PlexServer, tracks: List[Track]) -> List:


def _update_plex_playlist(
plex: PlexServer, available_tracks: List, playlist: Playlist, append: bool = False
) -> None:
plex: PlexServer,
available_tracks: List,
playlist: Playlist,
append: bool = False,
) -> plexapi.playlist.Playlist:
"""Update existing plex playlist with new tracks and metadata.
Args:
plex (PlexServer): A configured PlexServer instance
available_tracks (List): list of plex track objects
playlist (Playlist): Playlist object
append (bool): Boolean for Append or sync
Returns:
plexapi.playlist: plex playlist object
plexapi.playlist.Playlist: plex playlist object
"""
plex_playlist = plex.playlist(playlist.name)
if not append:
Expand All @@ -114,7 +135,10 @@ def _update_plex_playlist(


def update_or_create_plex_playlist(
plex: PlexServer, playlist: Playlist, tracks: List[Track], userInputs: UserInputs
plex: PlexServer,
playlist: Playlist,
tracks: List[Track],
userInputs: UserInputs,
) -> None:
"""Update playlist if exists, else create a new playlist.
Expand Down Expand Up @@ -142,11 +166,14 @@ def update_or_create_plex_playlist(
plex_playlist.edit(summary=playlist.description)
if playlist.poster and userInputs.add_playlist_poster:
plex_playlist.uploadPoster(url=playlist.poster)
logging.info("Updated playlist %s with summary and poster", playlist.name)
logging.info(
"Updated playlist %s with summary and poster", playlist.name
)

else:
logging.info(
"No songs for playlist %s were found on plex, skipping the playlist creation",
"No songs for playlist %s were found on plex, skipping the"
" playlist creation",
playlist.name,
)
if missing_tracks and userInputs.write_missing_as_csv:
Expand All @@ -155,6 +182,17 @@ def update_or_create_plex_playlist(
logging.info("Missing tracks written to %s.csv", playlist.name)
except:
logging.info(
"Failed to write missing tracks for %s, likely permission issue",
"Failed to write missing tracks for %s, likely permission"
" issue",
playlist.name,
)
if (not missing_tracks) and userInputs.write_missing_as_csv:
try:
# Delete playlist created in prev run if no tracks are missing now
_delete_csv(playlist.name)
logging.info("Deleted old %s.csv", playlist.name)
except:
logging.info(
"Failed to delete %s.csv, likely permission issue",
playlist.name,
)
4 changes: 3 additions & 1 deletion plex-playlist-sync/utils/spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def extract_sp_track_metadata(track) -> Track:
# If playlist contains more than 100 tracks this loop is useful
while sp_playlist_tracks["next"]:
sp_playlist_tracks = sp.next(sp_playlist_tracks)
tracks.extend(list(map(extract_sp_track_metadata, sp_playlist_tracks["items"])))
tracks.extend(
list(map(extract_sp_track_metadata, sp_playlist_tracks["items"]))
)
return tracks


Expand Down

0 comments on commit afe014f

Please sign in to comment.