-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotify.py
124 lines (94 loc) · 2.76 KB
/
spotify.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
import json
import os
import sys
import time
import requests
USER_ID = "1219121420"
PAGE_SIZE = 50
PAGINATION_SLEEP_S = 3
def get_token():
r = requests.post(
url="https://accounts.spotify.com/api/token",
headers={"Content-type": "application/x-www-form-urlencoded"},
data={
"grant_type": "client_credentials",
"client_id": os.environ["SPOTIFY_CLIENT_ID"],
"client_secret": os.environ["SPOTIFY_CLIENT_SECRET"],
},
)
r.raise_for_status()
return r.json()["access_token"]
def _get(url, page_num=0):
offset = page_num * PAGE_SIZE
token = get_token()
r = requests.get(
url=url,
headers={"Authorization": f"Bearer {token}"},
params={"limit": PAGE_SIZE, "offset": offset},
)
r.raise_for_status()
return r.json()
def _get_playlists(page_num=0):
return _get(
url=f"https://api.spotify.com/v1/users/{USER_ID}/playlists",
page_num=page_num,
)['items']
def _get_playlist_tracks(playlist_id, page_num=0):
return _get(
url=f"https://api.spotify.com/v1/users/{USER_ID}/playlists/{playlist_id}/tracks",
page_num=page_num,
)['items']
def _get_liked_songs(page_num=0):
# TODO this doesn't work using existing method, might need auth?
return _get(
url=f"https://api.spotify.com/v1/me/tracks",
page_num=page_num,
)['items']
def get_playlists():
page = 0
all_results = []
while True:
batch = _get_playlists(page_num=page)
all_results += batch
if len(batch) < PAGE_SIZE:
break
page += 1
time.sleep(PAGINATION_SLEEP_S)
return all_results
def get_liked_songs():
page = 0
all_results = []
while True:
batch = _get_liked_songs(page_num=page)
all_results += batch
if len(batch) < PAGE_SIZE:
break
page += 1
time.sleep(PAGINATION_SLEEP_S)
return all_results
def get_playlist_tracks(playlist_id):
page = 0
all_results = []
while True:
batch = _get_playlist_tracks(playlist_id, page_num=page)
all_results += batch
if len(batch) < PAGE_SIZE:
break
page += 1
time.sleep(PAGINATION_SLEEP_S)
return all_results
if __name__ == "__main__":
arg = sys.argv[1]
if arg == 'playlists':
playlists = get_playlists()
for playlist in playlists:
print(json.dumps(playlist))
if arg == 'playlist-tracks':
playlist_id = sys.argv[2]
tracks = get_playlist_tracks(playlist_id)
for track in tracks:
print(json.dumps(track))
if arg == 'liked-songs':
liked_songs = get_liked_songs()
for song in liked_songs:
print(json.dumps(song))