forked from RegsonDR/spotify-save-playlists-cron
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nmf_dance.py
162 lines (140 loc) · 5.63 KB
/
nmf_dance.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
from dotenv import load_dotenv, find_dotenv
from datetime import date
import requests
import urllib.request
import base64
import json
import os
import sys
load_dotenv(find_dotenv())
REFRESH_TOKEN = os.environ.get("REFRESH_TOKEN").strip()
CLIENT_ID = os.environ.get("CLIENT_ID").strip()
CLIENT_SECRET = os.environ.get("CLIENT_SECRET").strip()
NEW_MUSIC_FRIDAY_DANCE_ID = os.environ.get("NEW_MUSIC_FRIDAY_DANCE_ID").strip()
USER_ID = os.environ.get("USER_ID")
today = date.today()
d1 = today.strftime("%d/%m/%Y")
d2 = today.strftime("%Y%m%d")
year = today.strftime("%Y")
OAUTH_TOKEN_URL = "https://accounts.spotify.com/api/token"
def refresh_access_token():
payload = {
"refresh_token": REFRESH_TOKEN,
"grant_type": "refresh_token",
"client_id": CLIENT_ID,
}
encoded_client = base64.b64encode((CLIENT_ID + ":" + CLIENT_SECRET).encode('ascii'))
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic %s" % encoded_client.decode('ascii')
}
response = requests.post(OAUTH_TOKEN_URL, data=payload, headers=headers)
return response.json()
def get_playlist(access_token,playlistid):
url = "https://api.spotify.com/v1/playlists/%s" % playlistid
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.get(url, headers=headers)
return response.json()
def create_playlist(access_token):
url = "https://api.spotify.com/v1/users/%s/playlists" % USER_ID
payload = {
"name": "New Music Friday Dance del %s" % d1,
"description": "Ogni Venerdi, le migliori nuove uscite dance ed elettroniche, copia salvata il %s" % d1
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response.json()
def add_to_nmf(access_token, nmfplaylisttoday, tracklist):
url = "https://api.spotify.com/v1/playlists/%s/tracks" % nmfplaylisttoday
payload = {
"uris" : tracklist
}
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response.json()
def get_spoticode(nmfplaylisttoday):
base_url = 'https://scannables.scdn.co/uri/plain/png/bdd74/black/640/spotify:playlist:'
spoti_url = ''.join([base_url, nmfplaylisttoday])
print("Spotify Code:",spoti_url)
return spoti_url
def get_playlistcover(access_token, nmfplaylisttoday):
url = "https://api.spotify.com/v1/playlists/%s/images" % nmfplaylisttoday
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % access_token
}
response = requests.get(url, headers=headers)
return response.json()
def downloadart(arturl, filename):
response = urllib.request.urlretrieve(arturl, filename)
return response
def check_env():
if REFRESH_TOKEN is None or CLIENT_ID is None or CLIENT_SECRET is None or NEW_MUSIC_FRIDAY_DANCE_ID is None:
response = 1
else:
response = 0
return response
def pause():
programPause = input("Press the <ENTER> key to continue...")
if check_env() == 1:
print("Environment variables have not been loaded, abort.")
sys.exit(1)
access_token = refresh_access_token()['access_token']
tracks = get_playlist(access_token,NEW_MUSIC_FRIDAY_DANCE_ID)['tracks']['items']
if len(tracks) > 10:
nmfplaylisttoday = create_playlist(access_token)['id']
nmfplaylisttoday_info = get_playlist(access_token,nmfplaylisttoday)
tracklist = []
try:
for item in tracks:
if item['track'] is not None: # Thanks to https://stackoverflow.com/a/60496351/2220346
tracklist.append(item['track']['uri'])
except:
json_string = json.dumps(tracks)
tracklisterror = "%s_tracklisterror.json" % d2
with open(tracklisterror, 'w') as outfile:
outfile.write(json_string)
sys.exit(1) # Thanks to https://stackoverflow.com/a/69257826/2220346
response = add_to_nmf(access_token, nmfplaylisttoday, tracklist)
if "snapshot_id" in response:
print("Playlist backup complete!")
nmf_spoticode = get_spoticode(nmfplaylisttoday)
nmf_cover = get_playlistcover(access_token, NEW_MUSIC_FRIDAY_DANCE_ID)[0]['url']
downloadart(nmf_spoticode,"nmf_dance_spoticode.png")
downloadart(nmf_cover,"nmf_dance_cover.png")
print("Adding playlist to current JSON file ...")
print("{}: {}".format(nmfplaylisttoday_info['name'], nmfplaylisttoday_info['external_urls']['spotify']))
json_nmf_add = {
"title": nmfplaylisttoday_info['name'],
"cover": nmf_cover,
"url": nmfplaylisttoday_info['external_urls']['spotify'],
"spoticode": nmf_spoticode
}
json_folder_dance = os.path.join("json","dance")
if not os.path.exists(json_folder_dance):
os.makedirs(json_folder_dance)
env_file = os.getenv('GITHUB_ENV')
with open(env_file, "a") as ghenv:
ghenv.write("jsn="+year+".json")
filename = os.path.join(json_folder_dance,year+".json") # Thanks to https://howtodoinjava.com/json/append-json-to-file/
json_nmf = []
with open(filename) as fp:
json_nmf = json.load(fp)
json_nmf.append(json_nmf_add)
print(json_nmf)
with open(filename, 'w') as fp_updated:
json.dump(json_nmf, fp_updated,
indent=4,
separators=(',',': '))
else:
print("Check tracklist len")
sys.exit(1)