-
Notifications
You must be signed in to change notification settings - Fork 0
/
non_routes.py
218 lines (159 loc) · 5.29 KB
/
non_routes.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
from apscheduler.schedulers.background import BackgroundScheduler
import time
import json
import random
import redis
import requests
import os
#enviro vars
REDIR_URI = os.environ.get('REDIRECT_URI')
CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')
REDIS_URL = os.environ.get('REDIS_URL')
#constants
ALLOWED_IDLE_TIME = 60*60*3 #measured in seconds
scheduler = BackgroundScheduler()
scheduler.start()
def redis_instance():
global REDIS_URL
if REDIS_URL:
return redis.from_url(REDIS_URL)
else:
return redis.Redis()
def generate_roomcode():
r = redis_instance()
lower = 10**5
upper = 10**6
while True:
code = str(random.randint(lower,upper))
if not r.exists(code):
r.set(code,'taken',ex=20)
return code
upper *= 10
def create_room(roomcode,auth_result):
global scheduler
r = redis_instance()
data = {
'access_token': auth_result[0],
'refresh_token': auth_result[1],
}
r.delete(roomcode)
r.hset(roomcode,mapping=data)
renewer = scheduler.add_job(
func=room_checkup,
trigger="interval",
seconds=auth_result[2],
args=(roomcode,)
)
#remember the id of this job so we can delete it later
r.hset(roomcode, 'job_id', renewer.id)
### SCHEDULED WORKERS ###
def room_checkup(roomcode):
global ALLOWED_IDLE_TIME, scheduler
r = redis_instance()
#first, check if we should kill the room
queue_key = roomcode+'q'
idle_time = r.object("idletime", queue_key)
# idle time is in seconds
if not idle_time or idle_time > ALLOWED_IDLE_TIME:
job_id = r.hget(roomcode, 'job_id')
r.delete(roomcode)
r.delete(queue_key)
#seppuku
print('goodbye room',roomcode)
scheduler.remove_job(job_id)
else:
renew_token(roomcode)
#refresh active users
r.delete(roomcode+'p')
print('room checkup done on', roomcode)
### SPOTIFY ###
def get_api_token(authCode):
global REDIR_URI, CLIENT_ID, CLIENT_SECRET
params = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': authCode,
'redirect_uri': REDIR_URI
}
url = 'https://accounts.spotify.com/api/token'
response = requests.post(url, data=params).json()
return response['access_token'],response['refresh_token'],response['expires_in']
def renew_token(roomcode):
global CLIENT_ID, CLIENT_SECRET
r = redis_instance()
refresh_token = r.hget(roomcode,'access_token').decode('utf-8')
params = {
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
url = 'https://accounts.spotify.com/api/token'
headers = {'Authorization': f'Basic {CLIENT_ID}:{CLIENT_SECRET}'}
response = requests.post(url, data=params, headers=headers).json()
r.hset(roomcode,'access_token', response['access_token'])
def play_state(code):
r = redis_instance()
token = r.hget(code,'access_token').decode('utf-8')
headers = {'Authorization': f'Bearer {token}'}
url = 'https://api.spotify.com/v1/me/player'
resp = requests.get(url, headers=headers)
try:
return resp.json()
except json.decoder.JSONDecodeError:
return None
def queue_song(code, uri):
params = {
'uri': uri
}
r = redis_instance()
token = r.hget(code,'access_token').decode('utf-8')
headers = {'Authorization': f'Bearer {token}'}
url = 'https://api.spotify.com/v1/me/player/queue'
resp = requests.post(url, headers=headers, params=params)
return str(resp.status_code)
def skip_song(code):
r = redis_instance()
token = r.hget(str(code),'access_token').decode('utf-8')
headers = {'Authorization': f'Bearer {token}'}
url = f'https://api.spotify.com/v1/me/player/next'
requests.post(url,headers=headers)
def get_tracks_info(uris, roomcode):
#chop off the resource type to get the spotify ids
spot_ids = [x[14:] for x in uris]
r = redis_instance()
token = r.hget(str(roomcode),'access_token').decode('utf-8')
params = {
'ids': ','.join(spot_ids)
}
headers = {'Authorization': f'Bearer {token}'}
url = f'https://api.spotify.com/v1/tracks'
resp = requests.get(url,params=params, headers=headers).json()
return resp['tracks']
def proccess_tracks(tracks):
new_tracks = []
for track, score in tracks:
data = {
'score': score,
'image': track['album']['images'][0]['url'],
'uri': track['uri'],
'name': track['name'],
'artist': track['artists'][0]['name']
}
new_tracks.append(data)
return new_tracks
def get_time_left(roomcode):
a=time.time()*1000
#get time left on current track
playback_info = play_state(roomcode)
#check if a song is actually playing
if playback_info is None or not playback_info['is_playing']:
return float('inf')
cur_song = playback_info['item']['uri']
cur_track_info = get_tracks_info([cur_song], roomcode)[0]
cur_duration = cur_track_info['duration_ms']
b=time.time()*1000
latency = b-a
progress = playback_info['progress_ms'] + latency
time_left = cur_duration-progress
return time_left