forked from caseychu/spotify-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
159 lines (120 loc) · 4.41 KB
/
Copy pathutils.py
File metadata and controls
159 lines (120 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import coloredlogs
from datetime import datetime
import logging
from constants import LIKES_PLAYLIST
from spotify_api import SpotifyAPI
def setup_logging():
coloredlogs.install(
datefmt="%I:%M:%S", fmt="[%(asctime)s] %(levelname)s %(message)s"
)
def login(spotify: SpotifyAPI):
# Get the ID of the logged in user.
logging.info("Loading user info...")
me = spotify.get("me")
logging.info("Logged in as {display_name} ({id})".format(**me))
return me
def parse_choices(choices):
choice_ranges = (x.split("-") for x in choices.split(","))
choice_list = [i for r in choice_ranges for i in range(int(r[0]), int(r[-1]) + 1)]
return choice_list
def get_playlists(
spotify: SpotifyAPI, me, include: str = "likes,playlists", mine: bool = False
) -> list:
playlists = []
# Add Likes playlist
if "likes" in include:
playlists += [{"id": "likes", "name": LIKES_PLAYLIST, "tracks": []}]
# List all playlists and the tracks in each playlist
if "playlists" in include:
logging.info("Loading playlists...")
playlist_data = spotify.list(
"users/{user_id}/playlists".format(user_id=me["id"]), {"limit": 50}
)
logging.info(f"Found {len(playlist_data)} playlists")
if mine:
playlist_data = [p for p in playlist_data if p["owner"]["id"] == me["id"]]
playlists += playlist_data
return playlists
def load_playlist(spotify: SpotifyAPI, me, playlist):
if playlist["name"] == LIKES_PLAYLIST:
# List all liked tracks
playlist["tracks"] = spotify.list(
"users/{user_id}/tracks".format(user_id=me["id"]), {"limit": 50}
)
logging.info(f"Loaded {playlist['name']} ({len(playlist['tracks'])} songs)")
else:
# List all tracks in playlist
logging.info(
f"Loading playlist: {playlist['name']} ({playlist['tracks']['total']} songs)"
)
playlist["tracks"] = spotify.list(playlist["tracks"]["href"], {"limit": 100})
def list_playlists(playlists, all=True):
# list available choices
for i, playlist in enumerate(playlists):
print(i, playlist["name"], sep="\t")
if all:
print(-1, "All", sep="\t")
def choose_playlist(playlists):
list_playlists(playlists, all=False)
# prompt for choices
while True:
try:
choice = int(input("Choose: "))
assert choice >= 0 and choice < len(playlists), "not in range"
break
except (ValueError, AssertionError):
print("Please enter a valid integer index")
return playlists[choice]
def choose_playlists(playlists):
list_playlists(playlists)
# prompt for choices
while True:
try:
choices = input("Choose: ")
if choices.strip() == "-1":
choices = None
break
choices = parse_choices(choices)
assert all(
choice >= 0 and choice < len(playlists) for choice in choices
), "not in range"
break
except (ValueError, AssertionError):
print("Please enter a valid integer indices")
if choices:
playlists = [playlists[choice] for choice in choices]
return playlists
def create_playlist(spotify: SpotifyAPI, me, name: str, tracks: list = []):
new_playlist = spotify.post(
"users/{id}/playlists".format(**me),
data={
"name": name,
"public": False,
"description": f"Created by SpotifyDataTools at {datetime.today()}",
},
)
logging.info(f"Created playlist: {name}")
if tracks:
add_tracks(spotify, new_playlist, tracks)
logging.info(f"Added total {len(tracks)} tracks to playlist: {name}")
return new_playlist
def add_tracks(spotify: SpotifyAPI, playlist, tracks: list):
uris = [t["track"]["uri"] for t in tracks]
i = 0
step = 100
while i < len(uris):
spotify.post(
"playlists/{id}/tracks".format(**playlist),
data={"uris": uris[i : i + step]},
)
if len(tracks) > step:
logging.debug(
f"Added {len(uris[i : i + step])} tracks to playlist: {playlist['name']}"
)
i += step
def release_to_year(release):
return int(release.split("-")[0])
def year_to_decade(year):
return year // 10 * 10
def year_to_decade_str(year):
return f"{year_to_decade(year):02d}s"