-
Notifications
You must be signed in to change notification settings - Fork 0
/
tidallister.py.api6
executable file
·573 lines (516 loc) · 18.9 KB
/
tidallister.py.api6
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# Include standard modules
import argparse
import json
# Tidal API - https://github.com/tamland/python-tidal && https://tidalapi.netlify.app/api.html#
import tidalapi
# Modules for spotify feature
import sys
import re
import requests
from bs4 import BeautifulSoup
# pip3 install argparse tidalapi requests bs4
playlistPrefix = "TidalLister: "
useDefaultPlaylistName = True
newPlaylistDescription = "Generated by TidalLister. \n"
# Initiate the parser
parser = argparse.ArgumentParser()
parser.add_argument(
"-A", "--artists", help="comma separated list of arists to search for"
)
parser.add_argument(
"-T",
"--tracks",
help="same as -K, comma separated list of tracks to search for",
)
parser.add_argument(
"-G", "--genres", help="comma separated list of genres to search for"
)
parser.add_argument(
"-L", "--albums", help="comma separated list of albums to search for"
)
parser.add_argument(
"-K", "--keywords", help="comma separated list, top tracks of each search term"
)
parser.add_argument(
"-S",
"--similars",
help="the number of similar artists to get extra tracks from (only works if -A is declared) (default is 3)",
)
parser.add_argument(
"-SD",
"--similarsdeep",
help="use true/false or 1/0, this goes deeper and gets similars of similars (only works if -A & -S are declared) (** BE CAREFUL: this makes your playlist grow exponentially!**)",
)
parser.add_argument(
"-AD",
"--allowdupes",
help="use true/false or 1/0, this allows duplicates if true, default is to skip duplicates",
)
parser.add_argument(
"-P",
"--playlist",
help="the name of the playlist to create, optional, will be prefixed with '"
+ playlistPrefix
+ "'",
)
parser.add_argument(
"-Q",
"--qty",
help="the number of songs from each search to add (default is 10 for each artist/genre/keyword)",
)
parser.add_argument(
"-SP",
"--spotify",
help="take a Spotify url (for artist,album,playist) and attempt to recreate it (approximately) in Tidal (forces Q=1 & AD=1)",
)
# Read arguments from the command line
args = parser.parse_args()
# Store arg values
print("Creating a Tidal Playlist using the following input...")
if (artists := args.artists) is not None:
artists = str(args.artists).strip()
print(" > artists:", artists)
if (albums := args.albums) is not None:
albums = str(args.albums).strip()
print(" > albums:", albums)
if (genres := args.genres) is not None:
genres = str(args.genres).strip()
print(" > genres:", genres)
if (similars := args.similars) is not None:
similars = str(args.similars).strip()
print(" > similars:", similars)
if (similarsdeep := args.similarsdeep) is not None:
similarsdeep = str(args.similarsdeep).strip()
print(" > similarsdeep:", similarsdeep)
if (allowdupes := args.allowdupes) is not None:
allowdupes = str(args.allowdupes).strip()
print(" > allowdupes:", allowdupes)
if (playlist := args.playlist) is not None:
playlist = str(args.playlist).strip()
print(" > playlist:", playlist)
if (spotify := args.spotify) is not None:
spotify = str(args.spotify).strip()
print(" > spotify:", spotify)
if (qty := args.qty) is not None:
qty = str(args.qty).strip()
print(" > qty:", qty)
else:
qty = 10
# track search just uses keyword, so show provided values
# but then merge them if they both exist
if (tracks := args.tracks) is not None:
tracks = str(args.tracks).strip()
print(" > tracks:", tracks)
if (keywords := args.keywords) is not None:
keywords = str(args.keywords).strip()
print(" > keywords:", keywords)
# Build lists to use later
artistsList = []
albumsList = []
genresList = []
keywordsList = []
tracksToAdd = []
artistsIDs = []
spotifyList = []
# set up defaults
if not int(qty):
qty = 10
else:
qty = int(qty)
if allowdupes:
allowdupes = bool(json.loads(str(allowdupes).lower()))
letsGoDeep = False
if not similars:
getSimilars = False
similars = 0
else:
getSimilars = True
if similarsdeep:
letsGoDeep = True
if not int(similars):
similars = 3
else:
similars = int(similars)
if not playlist:
useDefaultPlaylistName = True
playlist = playlistPrefix
else:
useDefaultPlaylistName = False
playlist = playlistPrefix + playlist + " - "
if artists:
artistsList = artists.split(",")
playlist += " " + " ".join(artists.split(","))
newPlaylistDescription += "--artists '" + artists + "' "
if similars:
playlist += " (& Similar Artists)"
newPlaylistDescription += "--similars='" + str(similars) + "' "
if similarsdeep:
playlist += " [DEEP]"
newPlaylistDescription += "--similarsdeep='" + str(similarsdeep) + "' "
if albums:
albumsList = albums.split(",")
playlist += " " + " ".join(albums.split(","))
newPlaylistDescription += "--albums '" + albums + "' "
if genres:
genresList = genres.split(",")
playlist += " " + " ".join(genres.split(","))
newPlaylistDescription += "--genres '" + genres + "' "
if keywords:
keywordsList += keywords.split(",")
playlist += " " + " ".join(keywords.split(","))
newPlaylistDescription += "--keywords '" + keywords + "' "
if tracks:
# track search just uses keyword search
keywordsList += tracks.split(",")
playlist += " " + " ".join(tracks.split(","))
newPlaylistDescription += "--tracks '" + tracks + "' "
if not keywords:
keywords = tracks
else:
keywords += ", " + tracks
spotifyURL = ""
spotifyFront = "https://open.spotify.com/"
spotifyCases = ("artist/", "album/", "playlist/")
spotPlaylistName = ""
spotTracksString = ""
# print(spotify)
if spotify:
spotifyList += spotify.split(",")
for spot in spotifyList:
# first, check if it's a partial url
if spot.startswith(spotifyCases):
print(" > spotify:", "Building direct url -", spot)
spot = spotifyFront + spot
# check if this is a full spotify url
if spot.startswith(spotifyFront):
print(" > spotify:", "Using direct url -", spot)
spotifyURL = spot
else:
print(" > spotify:", "assuming this is a playlist ID -", spot)
# else, assume it's a playlist id and add the https front
spotifyURL = spotifyFront + "playlist/" + spot
# now setup actual search with spotify
if spotifyURL:
spotPage = requests.get(spotifyURL)
spotSoup = BeautifulSoup(spotPage.text, "html.parser")
# print(spotSoup)
spotPlaylistName += (
spotSoup.title.get_text()
.replace(" | Spotify", "")
.replace(" - playlist", "")
) + " [Spotify]. "
spotTracks = spotSoup.select('[data-testid="track-row"]')
spotTracksDict = []
# print(spotifyURL)
print(" *** Getting Spotify playlist:", spotPlaylistName)
print(" from:", spotifyURL)
for spotTrack in spotTracks:
try:
links = spotTrack.select("a[href]")
songRaw = links[0].get_text()
songRaw = (
songRaw.replace(",", " ").replace("/", " ").replace("\\", " ")
)
songRaw = songRaw.replace("'", "").replace('"', "")
song = re.sub("'\"\s\’\”", "", songRaw.replace(" ", " "))
artistRaw = links[1].get_text()
artistRaw = (
artistRaw.replace(",", " ").replace("/", " ").replace("\\", " ")
)
artistRaw = artistRaw.replace("'", "").replace('"', "")
artist = re.sub("'\"\s\’\”", "", artistRaw.replace(" ", " "))
print(" --- Spotify track:", song, artist)
spotTracksDict.append(song + " " + artist)
except:
print(" *** Spotify script had an error. Moving on")
print(" *** Spotify links:", links)
# finally add it to the keyword search
totalTrackCount = len(spotTracks)
print(" Total Tracks:", totalTrackCount)
if totalTrackCount > 0:
keywordsList += spotTracksDict
spotTracksString += ", ".join(spotTracksDict)
playlist += " " + spotPlaylistName
newPlaylistDescription += "--spotify '" + spotify + "' "
# for spotify, force the QTY & dupes
qty = 1
allowdupes = 1
if not keywords:
keywords = spotTracksString
else:
keywords += ", " + spotTracksString
# custom method to remove bracket text
def remove_bracket_text(test_str):
ret = ""
skip1c = 0
skip2c = 0
for i in test_str:
if i == "[":
skip1c += 1
elif i == "(":
skip2c += 1
elif i == "]" and skip1c > 0:
skip1c -= 1
elif i == ")" and skip2c > 0:
skip2c -= 1
elif skip1c == 0 and skip2c == 0:
ret += i
return ret
# return track name as a unique string ID
# Given: "Heroes (Live) [Album Version]"
# Returns: "heroes"
# So that duplicates (even live versions) can be identified
def make_string_id(test_str):
ret = str(test_str)
if not allowdupes:
ret = remove_bracket_text(ret)
ret = ret.lower().strip().replace(" ", "")
ret = "".join(char for char in ret if char.isalnum())
return ret
print("- - -")
# Connect to Tidal
session = tidalapi.Session()
# Will run until you visit the printed url and link your account
session.login_oauth_simple()
userID = session.user.id
print("")
## TODO:
def get_all_tracks_from_all_albums(artistID):
# return list of track ids
pass
def get_artist_radio(artistID):
# return list of track ids
pass
def get_track_radio(trackID):
# return list of track ids
pass
# https://tidalapi.netlify.app/_modules/tidalapi.html#Session.get_artist_similar
def get_artist_similar(artistID):
# return list of track ids
pass
def get_similars(artistID, artistName, goDeep=False):
print("Getting", similars, "artists similar to", artistName, "...")
# if there are no similar artists, the response if 404 error
try:
similarArtists = session.get_artist_similar(artistID)
similarsFound = 0
for i, sim in enumerate(similarArtists):
if sim.id not in artistsIDs:
if similarsFound == int(similars):
break
else:
similarsFound += 1
artistsIDs.append(sim.id)
print(
artistName,
"* SIMILAR ARTIST #",
similarsFound,
":",
sim.name,
sim.id,
)
else:
print(
artistName,
"* SIMILAR ARTIST",
sim.name,
sim.id,
"but they're already in the list",
)
if goDeep:
print("\nGoing Deep...")
get_similars(sim.id, artistName + " > " + sim.name, False)
except Exception as e:
print(e, "\n")
print(" ")
# END get_similars
# Search for the artists
if artists:
for a in artistsList:
print("- - - \n")
print("* Searching for ARTIST:", a)
search = session.search("artist", a, limit=1)
if search.artists:
for result in search.artists:
artistID = result.id
# add all artist IDs to list, then loop through to get tracks
if artistID not in artistsIDs:
artistsIDs.append(artistID)
print("** Found ARTIST:", result.name, artistID)
else:
print(
"** Found ARTIST:",
result.name,
artistID,
"and they're already in the list",
)
if getSimilars:
get_similars(artistID, result.name, letsGoDeep)
# END if getSimilars:
# END if search.artists:
# Loop through artistsIDs and add tracks
if artistsIDs:
print(" - - - \n")
for artistID in artistsIDs:
print("Getting Tracks for artistID:", artistID, "\n")
topTracks = session.get_artist_top_tracks(artistID)
# collect track titles so we can avoid duplicates
trackTitles = []
for i, track in enumerate(topTracks):
trackID = str(track.id)
trackStringID = make_string_id(track.name) + make_string_id(
track.artist.name
)
trackInfoForPrint = (
trackID
+ " - "
+ track.name
+ " by "
+ track.artist.name
+ " * "
+ trackStringID
)
if int(qty) == len(trackTitles):
break
else:
if trackStringID not in trackTitles:
tracksToAdd.append(trackID)
trackTitles.append(trackStringID)
print(" +Added!", trackInfoForPrint)
else:
print(" -Duplicate:", trackInfoForPrint)
print("\n")
# Search for the albums
if albums:
for a in albumsList:
print(" - - - \n")
print("* Searching for ALBUMS: ", a)
search = session.search("album", a, limit=1)
if search.albums:
for result in search.albums:
albumID = result.id
print("** Found ALBUM: ", result.name, albumID, "\n")
albumTracks = session.get_album_tracks(albumID)
trackTitles = []
for i, track in enumerate(albumTracks):
trackID = str(track.id)
trackStringID = make_string_id(track.name) + make_string_id(
track.artist.name
)
trackInfoForPrint = (
trackID
+ " - "
+ track.name
+ " by "
+ track.artist.name
+ " * "
+ trackStringID
)
if trackStringID not in trackTitles:
tracksToAdd.append(trackID)
trackTitles.append(trackStringID)
print(" +Added!", trackInfoForPrint)
else:
print(" -Duplicate:", trackInfoForPrint)
print("\n")
# Search for the genres (by finding the first playlist named for the genre)
if genres:
for a in genresList:
print(" - - - \n")
print("* Searching for GENRES: ", a)
search = session.search("playlist", a, limit=1)
if search.playlists:
for result in search.playlists:
playlistID = result.id
print("** Found GENRE Playlist: ", result.name, playlistID, "\n")
genreTracks = session.get_playlist_tracks(playlistID)
trackTitles = []
for i, track in enumerate(genreTracks):
trackID = str(track.id)
trackStringID = make_string_id(track.name) + make_string_id(
track.artist.name
)
trackInfoForPrint = (
trackID
+ " - "
+ track.name
+ " by "
+ track.artist.name
+ " * "
+ trackStringID
)
if int(qty) == len(trackTitles):
break
else:
if trackStringID not in trackTitles:
tracksToAdd.append(trackID)
trackTitles.append(trackStringID)
print(" +Added!", trackInfoForPrint)
else:
print(" -Duplicate:", trackInfoForPrint)
print("\n")
# print("keywords", keywords)
# print("keywordsList", keywordsList)
# Search for the keywords (by finding the top tracks for each keyword)
if keywords:
for a in keywordsList:
print(" - - - \n")
print("* Searching for KEYWORDS: ", a)
# we'll pad the qty a bit in case of duplicates so that we get more than enough results and can then limit it to the qty
search = session.search("track", a, limit=(int(qty) + 10))
if search.tracks:
print("** Found KEYWORD results: ", a, "\n")
trackTitles = []
for i, track in enumerate(search.tracks):
trackID = str(track.id)
trackStringID = make_string_id(track.name) + make_string_id(
track.artist.name
)
trackInfoForPrint = (
trackID
+ " - "
+ track.name
+ " by "
+ track.artist.name
+ " * "
+ trackStringID
)
if int(qty) == len(trackTitles):
break
else:
if trackStringID not in trackTitles:
tracksToAdd.append(trackID)
trackTitles.append(trackStringID)
print(" +Added!", trackInfoForPrint)
else:
print(" -Duplicate:", trackInfoForPrint)
print("\n")
if tracksToAdd:
print("\nMaking a new playlist with", len(tracksToAdd), "tracks...\n")
# Create new playlist
newPlaylistName = " ".join(playlist.split())
newPlaylistName = newPlaylistName.strip().replace(" ", " ")
newPlaylistDescription += "--qty '" + str(qty) + "' "
newPlaylistDescription = newPlaylistDescription.strip().replace(" ", " ")
newPlaylist = session.request(
"POST",
"users/%s/playlists" % userID,
data={"title": newPlaylistName, "description": newPlaylistDescription},
)
newPlaylistID = newPlaylist.json()["uuid"]
# print(newPlaylistID)
# Add Tracks to playlist
# to_index = 0
etag = session.request("GET", "playlists/%s" % newPlaylistID).headers["ETag"]
headers = {"if-none-match": etag}
data = {"trackIds": ",".join(tracksToAdd)}
result = session.request(
"POST", "playlists/%s/tracks" % newPlaylistID, data=data, headers=headers
)
newPlaylistURL = "https://tidal.com/browse/playlist/" + newPlaylistID
print("Done! Your New Playlist is available at:")
print(newPlaylistURL)
print(newPlaylistName)
print(newPlaylistDescription)
else:
print("Could not find any tracks to add. Exiting now.")