-
Notifications
You must be signed in to change notification settings - Fork 198
/
zspotify.py
462 lines (365 loc) · 15.2 KB
/
zspotify.py
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import os
import os.path
import platform
import unicodedata
import re
import subprocess
import time
import sys
import requests
import json
import music_tag
from librespot.audio.decoders import AudioQuality, VorbisOnlyAudioQuality
from librespot.core import Session
from librespot.metadata import TrackId
from pydub import AudioSegment
quality: AudioQuality = AudioQuality.HIGH
#quality: AudioQuality = AudioQuality.VERY_HIGH #Uncomment this line if you have a premium account
session: Session = None
import hashlib
rootPath = "ZSpotify Music/"
skipExistingFiles = True
#miscellaneous functions for general use
def clear():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def wait(seconds: int = 3):
for i in range(seconds)[::-1]:
print("\rWait for %d second(s)..." % (i + 1), end="")
time.sleep(1)
def sanitizeData(value):
return value.replace("\\", "").replace("/", "").replace(":", "").replace("*", "").replace("?", "").replace("'", "").replace("<", "").replace(">", "").replace('"',"")
def splash():
print("=================================\n"
"| Spotify Downloader |\n"
"| |\n"
"| by Footsiefat/Deathmonger |\n"
"=================================\n\n\n")
#two mains functions for logging in and doing client stuff
def login():
global session
if os.path.isfile("credentials.json"):
try:
session = Session.Builder().stored_file().create()
return
except RuntimeError:
pass
while True:
user_name = input("UserName: ")
password = input("Password: ")
try:
session = Session.Builder().user_pass(user_name, password).create()
return
except RuntimeError:
pass
def client():
global quality, session
splash()
if len(sys.argv) > 1:
if sys.argv[1] != "-p" and sys.argv[1] != "--playlist":
track_uri_search = re.search(
r"^spotify:track:(?P<TrackID>[0-9a-zA-Z]{22})$", sys.argv[1])
track_url_search = re.search(
r"^(https?://)?open\.spotify\.com/track/(?P<TrackID>[0-9a-zA-Z]{22})(\?si=.+?)?$",
sys.argv[1],
)
album_uri_search = re.search(
r"^spotify:album:(?P<AlbumID>[0-9a-zA-Z]{22})$", sys.argv[1])
album_url_search = re.search(
r"^(https?://)?open\.spotify\.com/album/(?P<AlbumID>[0-9a-zA-Z]{22})(\?si=.+?)?$",
sys.argv[1],
)
playlist_uri_search = re.search(
r"^spotify:playlist:(?P<PlaylistID>[0-9a-zA-Z]{22})$", sys.argv[1])
playlist_url_search = re.search(
r"^(https?://)?open\.spotify\.com/playlist/(?P<PlaylistID>[0-9a-zA-Z]{22})(\?si=.+?)?$",
sys.argv[1],
)
if track_uri_search is not None or track_url_search is not None:
track_id_str = (track_uri_search
if track_uri_search is not None else
track_url_search).group("TrackID")
downloadTrack(track_id_str)
elif album_uri_search is not None or album_url_search is not None:
album_id_str = (album_uri_search
if album_uri_search is not None else
album_url_search).group("AlbumID")
downloadAlbum(album_id_str)
elif playlist_uri_search is not None or playlist_url_search is not None:
playlist_id_str = (playlist_uri_search
if playlist_uri_search is not None else
playlist_url_search).group("PlaylistID")
token = session.tokens().get("user-read-email")
playlistSongs = get_playlist_songs(token, playlist_id_str)
name, creator = get_playlist_info(token, playlist_id_str)
for song in playlistSongs:
downloadTrack(song['track']['id'], name + "/")
print("\n")
else:
downloadFromOurPlaylists()
else:
searchText = input("Enter search: ")
search(searchText)
wait()
#related functions that do stuff with the spotify API
def search(searchTerm):
token = session.tokens().get("user-read-email")
resp = requests.get(
"https://api.spotify.com/v1/search",
{
"limit": "10",
"offset": "0",
"q": searchTerm,
"type": "track,album,playlist"
},
headers={"Authorization": "Bearer %s" % token},
)
i = 1
tracks = resp.json()["tracks"]["items"]
if len(tracks) > 0:
print("### TRACKS ###")
for track in tracks:
print("%d, %s | %s" % (
i,
track["name"],
",".join([artist["name"] for artist in track["artists"]]),
))
i += 1
totalTracks = i - 1
print("\n")
else:
totalTracks = 0
albums = resp.json()["albums"]["items"]
if len(albums) > 0:
print("### ALBUMS ###")
for album in albums:
print("%d, %s | %s" % (
i,
album["name"],
",".join([artist["name"] for artist in album["artists"]]),
))
i += 1
totalAlbums = i - totalTracks - 1
print("\n")
else:
totalAlbums = 0
playlists = resp.json()["playlists"]["items"]
if len(playlists) > 0:
print("### PLAYLISTS ###")
for playlist in playlists:
print("%d, %s | %s" % (
i,
playlist["name"],
playlist['owner']['display_name'],
))
i += 1
totalPlaylists = i - totalTracks - totalAlbums - 1
print("\n")
else:
totalPlaylists = 0
if len(tracks) + len(albums) + len(playlists) == 0:
print("NO RESULTS FOUND - EXITING...")
else:
position = int(input("SELECT ITEM BY ID: "))
if position <= totalTracks:
trackId = tracks[position - 1]["id"]
downloadTrack(trackId)
elif position <= totalAlbums + totalTracks:
downloadAlbum(albums[position - totalTracks - 1]["id"])
else:
playlistChoice = playlists[position - totalTracks - totalAlbums - 1]
playlistSongs = get_playlist_songs(token, playlistChoice['id'])
for song in playlistSongs:
if song['track']['id'] != None:
downloadTrack(song['track']['id'], sanitizeData(playlistChoice['name'].strip()) + "/")
print("\n")
def getSongInfo(songId):
token = session.tokens().get("user-read-email")
info = json.loads(requests.get("https://api.spotify.com/v1/tracks?ids=" + songId + '&market=from_token', headers={"Authorization": "Bearer %s" % token}).text)
artists = []
for x in info['tracks'][0]['artists']:
artists.append(sanitizeData(x['name']))
albumName = sanitizeData(info['tracks'][0]['album']["name"])
name = sanitizeData(info['tracks'][0]['name'])
imageUrl = info['tracks'][0]['album']['images'][0]['url']
releaseYear = info['tracks'][0]['album']['release_date'].split("-")[0]
disc_number = info['tracks'][0]['disc_number']
track_number = info['tracks'][0]['track_number']
scrapedSongId = info['tracks'][0]['id']
isPlayAble = info['tracks'][0]['is_playable']
return artists, albumName, name, imageUrl, releaseYear, disc_number, track_number, scrapedSongId, isPlayAble
#Functions directly related to modifying the downloaded audio and its metadata
def convertToMp3(filename):
print("### CONVERTING TO MP3 ###")
raw_audio = AudioSegment.from_file(filename, format="ogg",
frame_rate=44100, channels=2, sample_width=2)
raw_audio.export(filename, format="mp3")
def setAudioTags(filename, artists, name, albumName, releaseYear, disc_number, track_number):
print("### SETTING MUSIC TAGS ###")
f = music_tag.load_file(filename)
f['artist'] = convArtistFormat(artists)
f['tracktitle'] = name
f['album'] = albumName
f['year'] = releaseYear
f['discnumber'] = disc_number
f['tracknumber'] = track_number
f.save()
def setMusicThumbnail(filename, imageUrl):
print("### SETTING THUMBNAIL ###")
r = requests.get(imageUrl).content
f = music_tag.load_file(filename)
f['artwork'] = r
f.save()
def convArtistFormat(artists):
formatted = ""
for x in artists:
formatted += x + ", "
return formatted[:-2]
#Extra functions directly related to spotify playlists
def get_all_playlists(access_token):
playlists = []
limit = 50
offset = 0
while True:
headers = {'Authorization': f'Bearer {access_token}'}
params = {'limit': limit, 'offset': offset}
resp = requests.get("https://api.spotify.com/v1/me/playlists", headers=headers, params=params).json()
offset += limit
playlists.extend(resp['items'])
if len(resp['items']) < limit:
break
return playlists
def get_playlist_songs(access_token, playlist_id):
songs = []
offset = 0
limit = 100
while True:
headers = {'Authorization': f'Bearer {access_token}'}
params = {'limit': limit, 'offset': offset}
resp = requests.get(f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks', headers=headers, params=params).json()
offset += limit
songs.extend(resp['items'])
if len(resp['items']) < limit:
break
return songs
def get_playlist_info(access_token, playlist_id):
headers = {'Authorization': f'Bearer {access_token}'}
resp = requests.get(f'https://api.spotify.com/v1/playlists/{playlist_id}?fields=name,owner(display_name)&market=from_token', headers=headers).json()
return resp['name'].strip(), resp['owner']['display_name'].strip()
#Extra functions directly related to spotify albums
def get_album_tracks(access_token, album_id):
songs = []
offset = 0
limit = 50
while True:
headers = {'Authorization': f'Bearer {access_token}'}
params = {'limit': limit, 'offset': offset}
resp = requests.get(f'https://api.spotify.com/v1/albums/{album_id}/tracks', headers=headers, params=params).json()
offset += limit
songs.extend(resp['items'])
if len(resp['items']) < limit:
break
return songs
def get_album_name(access_token, album_id):
headers = {'Authorization': f'Bearer {access_token}'}
resp = requests.get(f'https://api.spotify.com/v1/albums/{album_id}', headers=headers).json()
return resp['artists'][0]['name'], sanitizeData(resp['name'])
#Functions directly related to downloading stuff
def downloadTrack(track_id_str: str, extra_paths = ""):
global rootPath, skipExistingFiles
track_id = TrackId.from_base62(track_id_str)
artists, albumName, name, imageUrl, releaseYear, disc_number, track_number, scrapedSongId, isPlayAble = getSongInfo(track_id_str)
songName = artists[0] + " - " + name
filename = rootPath + extra_paths + songName + '.mp3'
if not isPlayAble:
print("### SKIPPING:", songName, "(SONG IS UNAVAILABLE) ###")
else:
if os.path.isfile(filename) and skipExistingFiles:
print("### SKIPPING:", songName, "(SONG ALREADY EXISTS) ###")
else:
if track_id_str != scrapedSongId:
print("### APPLYING PATCH TO LET SONG DOWNLOAD ###")
track_id_str = scrapedSongId
track_id = TrackId.from_base62(track_id_str)
print("### FOUND SONG:", songName, " ###")
stream = session.content_feeder().load(
track_id, VorbisOnlyAudioQuality(quality), False, None)
print("### DOWNLOADING RAW AUDIO ###")
if not os.path.isdir(rootPath + extra_paths):
os.makedirs(rootPath + extra_paths)
with open(filename,'wb') as f:
'''
chunk_size = 1024 * 16
buffer = bytearray(chunk_size)
bpos = 0
'''
#With the updated version of librespot my faster download method broke so we are using the old fallback method
while True:
byte = stream.input_stream.stream().read()
if byte == b'':
break
f.write(byte)
'''
while True:
byte = stream.input_stream.stream().read()
if byte == -1:
# flush buffer before breaking
if bpos > 0:
f.write(buffer[0:bpos])
break
print(bpos)
buffer[bpos] = byte
bpos += 1
if bpos == (chunk_size):
f.write(buffer)
bpos = 0
'''
convertToMp3(filename)
setAudioTags(filename, artists, name, albumName, releaseYear, disc_number, track_number)
setMusicThumbnail(filename, imageUrl)
def downloadAlbum(album):
token = session.tokens().get("user-read-email")
artist, album_name = get_album_name(token, album)
tracks = get_album_tracks(token, album)
for track in tracks:
downloadTrack(track['id'], artist + " - " + album_name + "/")
print("\n")
def downloadFromOurPlaylists():
token = session.tokens().get("user-read-email")
playlists = get_all_playlists(token)
count = 1
for playlist in playlists:
print(str(count) + ": " + playlist['name'].strip())
count += 1
playlistChoice = input("SELECT A PLAYLIST BY ID: ")
playlistSongs = get_playlist_songs(token, playlists[int(playlistChoice) - 1]['id'])
for song in playlistSongs:
if song['track']['id'] != None:
downloadTrack(song['track']['id'], sanitizeData(playlists[int(playlistChoice) - 1]['name'].strip()) + "/")
print("\n")
#Core functions here
def main():
login()
client()
if __name__ == "__main__":
main()
#Left over code ill probably want to reference at some point
"""
if args[0] == "q" or args[0] == "quality":
if len(args) == 1:
print("Current Quality: " + quality.name)
wait()
elif len(args) == 2:
if args[1] == "normal" or args[1] == "96":
quality = AudioQuality.NORMAL
elif args[1] == "high" or args[1] == "160":
quality = AudioQuality.HIGH
elif args[1] == "veryhigh" or args[1] == "320":
quality = AudioQuality.VERY_HIGH
print("Set Quality to %s" % quality.name)
wait()
"""
#TO DO'S:
#MAKE AUDIO SAVING MORE EFFICIENT