-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.py
More file actions
321 lines (229 loc) · 9.81 KB
/
App.py
File metadata and controls
321 lines (229 loc) · 9.81 KB
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
from http.server import BaseHTTPRequestHandler, HTTPServer
import urllib.parse as urlparse
import time
import webbrowser
import requests
import requests
import base64
import json
playingMusic = False
settings = {}
defaultSettings = {
"winMusic": {
"enabled": True,
"track": "spotify:track:0TtD91m3UCmluyHjbm5k5w",
"startTime": 93000
},
"refreshToken": {
"enabled": True
}
}
def MakeGetAuthorizationCodeHandler(OAuth2Class):
class GetAuthorizationCodeHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_GET(self):
parsedPath = urlparse.urlparse(self.path)
for q in parsedPath.query.split("&"):
kv = q.split("=")
if kv[0] == "code":
OAuth2Class.authorizationCode = kv[1]
self.send_response(200)
self.end_headers()
self.wfile.write("<script>window.close();</script>")
return
return GetAuthorizationCodeHandler
def MakeGameStateIntegrationHandler(OAuth2Class, deviceId):
class GetGameStateHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def do_POST(self):
global playingMusic
parsedPath = urlparse.urlparse(self.path)
contentLength = int(self.headers["content-length"])
body = json.loads(self.rfile.read(contentLength))
shouldBePlay = shouldPlay(body)
if shouldBePlay == True and not playingMusic:
resumeMusic(auth, deviceId)
elif shouldBePlay == False and playingMusic:
pauseMusic(auth, deviceId)
elif shouldBePlay == "win" and not playingMusic == "win":
playWinMusic(auth, deviceId)
playingMusic = shouldBePlay
self.send_response(200)
self.end_headers()
return
return GetGameStateHandler
class OAuth2:
def __init__(self, clientId, clientSecret, authorizationURL, tokenURL):
self.clientId = clientId
self.clientSecret = clientSecret
self.authorizationURL = authorizationURL
self.tokenURL = tokenURL
self.authorizationCode = ""
def openAuthorizationURL(self, scopes):
url = self.getAuthorizationURL(scopes)
webbrowser.open(url)
return self.getAuthorizationCode()
def getAuthorizationURL(self, scopes):
return authorizationURL + "?" + "scope=" + " ".join(scopes) + "&response_type=code&client_id=" + self.clientId + "&redirect_uri=http://localhost:4074/"
def getAuthorizationCode(self):
self.authorizationCode = ""
server = HTTPServer(("", 4074), MakeGetAuthorizationCodeHandler(self))
print("Waiting for authorization code")
while self.authorizationCode == "":
server.handle_request()
return self.authorizationCode
def getTokens(self):
data = {"grant_type": "authorization_code", "code": self.authorizationCode, "redirect_uri": "http://localhost:4074/"}
r = requests.post(self.tokenURL, data=data, headers={"Authorization": "Basic " + base64.b64encode((self.clientId + ":" + self.clientSecret).encode()).decode()})
return json.loads(r.text)
def getAccessToken(self, secondTry = False):
if time.time() >= self.expires and not secondTry:
prin("Access token expired")
self.refreshAcessToken()
return self.getAccessToken(secondTry = True)
return self.accessToken
def refreshAcessToken(self):
data = {"grant_type": "refresh_token", "refresh_token": self.refreshToken}
r = requests.post(self.tokenURL, data=data, headers={"Authorization": "Basic " + base64.b64encode((self.clientId + ":" + self.clientSecret).encode()).decode()})
tokens = json.loads(r.text)
self.accessToken = tokens["access_token"]
self.expires = time.time() + tokens["expires_in"]
print("Refreshed acceses token")
def authorize(self, scopes, refreshToken = None):
if not refreshToken == None:
self.refreshToken = refreshToken
self.refreshAcessToken()
else:
self.openAuthorizationURL(scopes)
tokens = self.getTokens()
self.accessToken = tokens["access_token"]
self.refreshToken = tokens["refresh_token"]
self.expires = time.time() + tokens["expires_in"]
return self.refreshToken
def getDeivce(auth):
chooseMode = getSetting("playbackDevice/mode")
if chooseMode == "active":
devices = getDevices(auth)
if not "devices" in devices:
print("No active devices")
exit()
for d in devices["devices"]:
if d["is_active"]:
print("active", d["id"])
return d["id"]
print("No active device")
exit()
elif chooseMode == "given":
deviceId = getSetting("playbackDevice/deviceId")
if not deviceId:
deviceId = choseDevice(auth)
setSetting("playbackDevice/deviceId", deviceId)
return deviceId
else:
return choseDevice(auth)
def choseDevice(auth):
devices = getDevices(auth)
if not "devices" in devices:
print("No active devices")
exit()
i = 1
for d in devices["devices"]:
print(i, d["name"], d["id"])
i += 1
print("Enter the number for the device you want to start playback from")
index = int(raw_input()) - 1
if len(devices["devices"]) < index:
print("Chosen device is out of bounds")
exit()
return devices["devices"][index]["id"]
def startGSIServer(oauth, deviceId):
print("Starting GSI server")
server = HTTPServer(("", 27375), MakeGameStateIntegrationHandler(oauth, deviceId))
server.serve_forever()
def getDevices(oauth2):
r = requests.get("https://api.spotify.com/v1/me/player/devices", headers={"Accept": "application/json", "Authorization": "Bearer " + oauth2.getAccessToken()})
return json.loads(r.text)
def readSettings():
global settings
try:
file = open("settings.json", "r")
settings = json.load(file)
return True
except IOError:
return False
def writeSettings():
file = open("settings.json", "w")
json.dump(settings, file, indent=4)
file.close()
def getSetting(path, s = None):
if s == None:
s = settings
path = path.split("/", 1)
if len(path) == 1 and path[0] in s:
return s[path[0]]
elif path[0] in s:
return getSetting(path[1], s[path[0]])
elif path[0] in defaultSettings:
return getSetting(path[1], defaultSettings[path[0]])
else:
return None
def _setSettingRecursive(path, value, s):
path = path.split("/", 1)
if not path[0] in s and len(path) > 1:
s[path[0]] = {}
if len(path) == 1:
s[path[0]] = value
else:
s[path[0]] = _setSettingRecursive(path[1], value, s[path[0]])
return s
def setSetting(path, value):
global settings
settings = _setSettingRecursive(path, value, settings)
writeSettings()
def playWinMusic(oauth, device):
# Play track
r = requests.put("https://api.spotify.com/v1/me/player/play?device_id=" + device, json={"uris": [getSetting("winMusic/track")]}, headers={"Accept": "application/json", "Authorization": "Bearer " + oauth.getAccessToken()})
# Go to chorus
r = requests.put("https://api.spotify.com/v1/me/player/seek?device_id=" + device + "&position_ms=" + getSetting("winMusic/startTime"), headers={"Accept": "application/json", "Authorization": "Bearer " + oauth.getAccessToken()})
# Try to find and API to resume the old music
def pauseMusic(oauth, device):
print("Pausing music")
r = requests.put("https://api.spotify.com/v1/me/player/pause?device_id=" + device, headers={"Accept": "application/json", "Authorization": "Bearer " + oauth.getAccessToken()})
def resumeMusic(oauth, device):
print("Resuming music")
r = requests.put("https://api.spotify.com/v1/me/player/play?device_id=" + device, headers={"Accept": "application/json", "Authorization": "Bearer " + oauth.getAccessToken()})
def shouldPlay(body):
if not "map" in body: # Not in game, prevents errors from trying to access non existing keys in body
return
health = body["player"]["state"]["health"]
roundPhase = body["round"]["phase"]
if body["map"]["phase"] == "gameover":
if body["map"]["team_ct"]["score"] == body["map"]["team_t"]["score"]:
return True
winner = "CT" if body["map"]["team_ct"]["score"] > body["map"]["team_t"]["score"] else "T"
if winner == body["player"]["team"]:
return "win"
else:
return True
if not body["map"]["mode"] == "competitive":
return True
if not body["player"]["steamid"] == body["provider"]["steamid"]:
return True
if health > 0 and roundPhase == "live":
return False
return True
if __name__ == "__main__":
readSettings()
authorizationURL = "https://accounts.spotify.com/authorize"
tokenURL = "https://accounts.spotify.com/api/token"
auth = OAuth2(getSetting("spotifyAPI/clientId"), getSetting("spotifyAPI/clientSecret"), authorizationURL, tokenURL)
refreshToken = None
if getSetting("refreshToken/enabled"):
refreshToken = getSetting("refreshToken/token")
print("Authorizing Spotify...")
refreshToken = auth.authorize(["user-modify-playback-state", "user-read-playback-state", "user-modify-playback-state"], refreshToken)
if getSetting("refreshToken/enabled"):
setSetting("refreshToken/token", refreshToken)
startGSIServer(auth, getDeivce(auth))