-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.html
582 lines (523 loc) · 27.7 KB
/
app.html
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
574
575
576
577
578
579
580
581
582
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/[email protected]/brython.min.js">
</script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/[email protected]/brython_stdlib.js">
</script>
<script>
function getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ( e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
function dismissAlert() {
$('.alert').alert('close')
}
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<title>Spotify Data</title>
</head>
<body class="bg-dark body" onload="brython(1)">
<nav class="navbar navbar-expand-sm navbar-light" style="background-color: #1DB954;">
<a class="navbar-brand" href="https://spotifydata.ml">Spotify Data</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggler" aria-controls="navbarToggler" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggler">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" href="#">Song Info</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Account Stats (coming soon)</a>
</li>
</ul>
</div>
</nav>
<div class="alertdiv"></div>
<div class="container mt-3" id="dataform" style="display: none;">
<div class="text-light text-center">
<h4>Search for a song below to see stats on it using the Spotify API:</h4>
</div>
<form class="needs-validation mt-3" novalidate>
<div class="form-group">
<!--<label class="success" for="validationCustom01">Yes</label>-->
<input type="text" class="form-control mx-auto" id="validationCustom01" style="max-width: 75%" placeholder="Search for a song..." data-toggle="tooltip" data-placement="top" data-trigger="hover focus" data-template='<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>' title="Search as you normally would on Spotify. Data is only collected for the first result, so be specific!" required>
<div class="invalid-feedback">
That's not a vaild search
</div>
</div>
<div class="text-center">
<button class="btn btn-primary" id="searchbutton" type="submit">Show me data!</button>
</div>
</form>
</div>
<div class="container mt-3" id="errormessage" style="display: none;">
<div class="text-light text-center">
<h4>Invalid access token! Please sign in again.</h4>
</div>
<div class="text-center">
<a class="btn btn-primary" id="loginbutton" href="https://spotifydata.ml">Back to login page</a>
</div>
</div>
<script>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<script type="text/python">
#access_token=BQDAd972QMo5MxC3EA9qw_wUd8CVP7UUHAuhmQ8YhEdXXP2p74jYHx_axRL-fBaWgswhJ1vkcbfZZPjpgAiYWF62dAMLds7xty6fe27LCGzxW6Ac_f238nOvhf5O6nFQpneg2eoeniqMdrDT3TRnwU1fdaXvTdn0fiY_eyfhVk_-ixeWmmLkuGlmcgq5sZXoAIHBNQp3voD8eZgZ_CF8aCw&token_type=Bearer&expires_in=3600&state=R6wHbLudpklxkgS9
#TODO
#ADD A WAY TO SEARCH BY TRACK DATA!!! (If possible)
#Style login page
#make numbers in chart easier to read and understand
#import requests
import datetime
import sys
import json
import javascript
from urllib import parse
from browser import document, html, ajax, window, timer
from browser.local_storage import storage
#storage['last_refresh_time']='2020-03-05 15:33:41.695988'
#print(document["test3"].attrs["style"])
'''
def authenticateUser():
def on_complete(req):
if req.status == 200 or req.status == 0:
document <= "User Authenticated!"
document <= req.text
document <= json.loads(req.text)
storage['access_token'] = json.loads(req.text)['access_token']
document <= str(json.loads(req.text)['access_token'])
else:
document <= "Error in token refresh!"
scopes = 'user-follow-read user-follow-modify user-read-private user-read-email streaming user-read-currently-playing user-modify-playback-state user-library-modify user-library-read user-top-read'
data = {'client_id' : storage['client_id'], 'response_type' : 'token', 'redirect_uri' : storage['redirect_uri'], 'state' : 'test', 'scope' : scopes}
url = "https://accounts.spotify.com/authorize?" + parse.urlencode(data)
document <= url
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a GET request to the url
req.open('GET', url, True)
# send data as a dictionary
req.set_header('content-type', 'application/x-www-form-urlencoded')
req.send(data)
'''
'''
def refreshAccessToken():
last_refreshed_time = datetime.datetime.strptime(storage['last_refresh_time'], '%Y-%m-%d %H:%M:%S.%f')
if datetime.datetime.now() - last_refreshed_time > datetime.timedelta(hours=1):
url = "https://accounts.spotify.com/api/token"
data = {'grant_type': 'refresh_token', 'refresh_token': storage['refresh_token'], 'client_id': storage['client_id'], 'client_secret': storage['client_secret']}
def on_complete(req):
if req.status == 200 or req.status == 0:
document <= "Access token refreshed!"
storage['access_token'] = json.loads(req.text)['access_token']
#document <= str(json.loads(req.text)['access_token'])
else:
document <= "Error in token refresh!"
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url
req.open('POST', url, False) #<--asyncronous
# send data as a dictionary
req.set_header('content-type', 'application/x-www-form-urlencoded')
req.send(data)
'''
def searchForTrack(ev):
if len(document.select(".form-control:invalid")) == 0:
searchfield = document["validationCustom01"]
search = searchfield.value
params = {"q" : search, "type" : "track", "limit" : 1}
#document <= parse.urlencode(params)
url = "https://api.spotify.com/v1/search/?" + parse.urlencode(params)
def on_complete(req):
if req.status == 200 or req.status == 0:
#document["result"].html = req.text
#document <= str(json.loads(req.text))
results = json.loads(req.text)
if len(results["tracks"]["items"]) > 0:
for i in range(0,len(results["tracks"]["items"])):
try:
print(results["tracks"]["items"][i]["name"] + " by " + results["tracks"]["items"][i]["artists"][0]["name"])
getTrackData(results["tracks"]["items"][i]["id"])
except:
document <= "Error!!!"
print("Error")
break
else:
print("No results for that search")
showAlert("<strong>No songs found for that search!</strong>")
elif req.status == 401:
#document <= "Error! Please sign in again by going to spotifydata.ml"
document["dataform"].attrs["style"] = "display: none"
del document["errormessage"].attrs["style"]
else:
document <= "Unkown Error"
print(error)
def submitRequest():
req.send()
def func():
document <= "Request timed out"
print("Request timed out")
#Get access_token
oauth_id = storage['access_token']
#url = "https://api.spotify.com/v1/audio-features/3Wv6AagA0qqWH7nRDrkgh7"
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url
req.open('GET', url, True) #<--asyncronous
req.set_header("Authorization", "Bearer " + oauth_id)
req.set_timeout(10, func)
# send data as a dictionary
#Put a loading icon in the button and disable it
spinner = html.SPAN(Class = "spinner-border spinner-border-sm")
document["searchbutton"].html = ""
document["searchbutton"] <= spinner
document["searchbutton"].attrs["disabled"] = ""
timer.set_timeout(submitRequest, 1000)
#print(search, results)
'''
try:
#print(len(results["tracks"]["items"]))
if len(results["tracks"]["items"]) >= 1:
for i in range(0,len(results["tracks"]["items"])):
try:
print(i+1, results["tracks"]["items"][i]["name"], "by", results["tracks"]["items"][i]["artists"][0]["name"])
except:
print("Error")
error = True
break
if error == False:
try:
selection = int(input("Which track would you like to get stats on? (Enter number): "))
if selection <= len(results["tracks"]["items"]) and selection >= 1:
return results["tracks"]["items"][selection-1]["id"]
else:
print("Error: That is not a valid number")
return None
except:
print("Error: That is not a valid number")
else:
print("No results found for that search")
except:
print("Error: That is not a valid search")
'''
def getParamsFromURL():
try:
hashParams = window.window.getHashParams().to_dict()
storage['access_token'] = hashParams["access_token"]
storage['received_state'] = hashParams["state"]
return True
except:
return False
#document <= hashParams["expires_in"]
def convertMilliseconds(millis):
millis = int(millis)
seconds=(millis/1000)%60
seconds = int(seconds)
minutes=(millis/(1000*60))%60
minutes = int(minutes)
hours=(millis/(1000*60*60))%24
return "%dh %dm %ds" % (hours, minutes, seconds)
def getTrackData(track_id): #Returns a dictionary based on the json response
def on_complete(req):
if req.status == 200 or req.status == 0:
#document["result"].html = req.text
#document <= str(json.loads(req.text))
data = json.loads(req.text)
getSongData(data)
elif req.status == 401:
document <= "Error! Please sign in again by going to spotifydata.ml"
else:
document <= "Unkown Error"
#Get access_token
oauth_id = storage['access_token']
url = "https://api.spotify.com/v1/audio-features/" + track_id
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url
req.open('GET', url, True) #<--asyncronous
req.set_header("Authorization", "Bearer " + oauth_id)
# send data as a dictionary
req.send()
def getSongData(track_data):
def on_complete(req):
if req.status == 200 or req.status == 0:
#document["result"].html = req.text
#document <= str(json.loads(req.text))
data = json.loads(req.text)
getArtistData(track_data, data)
elif req.status == 401:
document <= "Error! Please sign in again by going to spotifydata.ml"
else:
document <= "Unkown Error"
#Get access_token
oauth_id = storage['access_token']
url="https://api.spotify.com/v1/tracks/" + track_data["id"]
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url
req.open('GET', url, True) #<--asyncronous
req.set_header("Authorization", "Bearer " + oauth_id)
# send data as a dictionary
req.send()
def getArtistData(track_data, song_data):
def on_complete(req):
if req.status == 200 or req.status == 0:
#document["result"].html = req.text
#document <= str(json.loads(req.text))
data = json.loads(req.text)
formatData(track_data, song_data, data)
elif req.status == 401:
document <= "Error! Please sign in again by going to spotifydata.ml"
else:
document <= "Unkown Error"
#Get access_token
oauth_id = storage['access_token']
url="https://api.spotify.com/v1/artists/" + song_data["album"]["artists"][0]["id"]
req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url
req.open('GET', url, True) #<--asyncronous
req.set_header("Authorization", "Bearer " + oauth_id)
# send data as a dictionary
req.send()
def showAlert(message):
def dismissAlert():
window.window.dismissAlert()
alertdiv = document.select(".alertdiv")[0]
alert = html.DIV(message, Class = "alert alert-danger alert-dismissible fade show", role="alert")
button = html.BUTTON(type = "button", Class = "close", data_dismiss = "alert", aria_label = "Close")
button <= html.SPAN("×", aria_hidden = "true")
alert <= button
alertdiv <= alert
document["searchbutton"].html = ""
document["searchbutton"] <= "Show me data!"
del document["searchbutton"].attrs["disabled"]
timer.set_timeout(dismissAlert, 5000)
'''<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those fields below.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>'''
def formatData(track_data, song_data, artist_data):
song_key_codes = {-1 : "Unkown key", 0 : "C", 1 : "C#", 2 : "D", 3 : "D#", 4 : "E", 5 : "F", 6 : "F#", 7 : "G", 8 : "G#", 9 : "A", 10 : "A#", 11 : "B"}
song_mode_codes = {-1 : "Unkown mode", 0 : "minor", 1 : "major"}
#try:
track_data["duration"] = str(convertMilliseconds(track_data["duration_ms"]))
del track_data["duration_ms"]
track_data["loudness"] = str(round(track_data["loudness"], 1)) + " decibels"
track_data["valence (happiness)"] = float(track_data["valence"])
del track_data["valence"]
track_data["time signature"] = str(track_data["time_signature"])
del track_data["time_signature"]
track_data["tempo"] = str(int(round(track_data["tempo"], 0))) + " BPM"
track_data["danceability"] = int(round(track_data["danceability"]*100, 0))
track_data["energy"] = int(round(track_data["energy"]*100, 0))
track_data["speechiness"] = int(round(track_data["speechiness"]*100, 0))
track_data["acousticness"] = int(round(track_data["acousticness"]*100, 0))
track_data["instrumentalness"] = int(round(track_data["instrumentalness"]*100, 0))
track_data["liveness"] = int(round(track_data["liveness"]*100, 0))
track_data["valence (happiness)"] = int(round(track_data["valence (happiness)"]*100, 0))
# All the elements will be inserted in the div with the "container" id
container = document.select(".container")[0]
if len(document.select("table")) == 0:
sys.stdout.write("makeTable")
#this is the first request and there is no table present
rowdiv = html.DIV(Class = "row")
tablediv = html.DIV(Class = "col")
table = html.TABLE(Class = "table table-dark table-sm table-borderless mx-auto mt-3", style={"max-width":"500px"})
thead = html.THEAD(Class = "border-success border-bottom")
tbody = html.TBODY()
table <= thead
table <= tbody
else:
print("table exists")
#the table exists already
document.select("table")[0].remove()
rowdiv = html.DIV(Class = "row")
tablediv = html.DIV(Class = "col")
table = html.TABLE(Class = "table table-dark table-sm table-borderless mx-auto mt-3", style={"max-width":"500px"})
thead = html.THEAD(Class = "border-success border-bottom")
tbody = html.TBODY()
table <= thead
table <= tbody
try:
song_title = song_data["name"]
album = song_data["album"]["name"]
artist = song_data["album"]["artists"][0]["name"]
thead <= html.TR(html.TH("Stats for " + song_title + " by " + artist, colspan="2"), Class="text-center") #+ " on the album " + album + ":\n"
except:
thead <= "Error: Could not get track from the provided id"
thead <= html.TR(html.TH("Song Attribute") +
html.TH("Value", Class="text-left"))
# for key, value in track_data:
# tbody <= html.TR(html.TD(key) +
# html.TD(value))
# Now we add some style to the table
# table.style = {"padding": "5px",
# "backgroundColor": "#aaaaaa",
# "width": "100%"}
# Now we add the table to the new div previously created
tablediv <= table
# except:
# document <= "An error occured"
track_data["song popularity"] = str(song_data["popularity"])
track_data["artist popularity"] = str(artist_data["popularity"])
##document <= "artist popularity: " + str(artist_data["popularity"])
if song_data["explicit"] == False:
#document <= "explicit: no"
track_data["explicit"] = "no"
else:
#document <= "explicit: yes"
track_data["explicit"] = "yes"
track_data["release date"] = song_data["album"]["release_date"]
#document <= "release date: " + song_data["album"]["release_date"]
first = True
if len(artist_data["genres"]) == 0:
track_data["genres"] = "unknown"
elif len(artist_data["genres"]) == 1:
track_data["genre"] = artist_data["genres"][0]
else:
genre_string = ""
for i in artist_data["genres"]:
if i == artist_data["genres"][-1]:
genre_string = genre_string + i
else:
genre_string = genre_string + i + ", "
tbody <= html.TR(html.TD("genres", Class="text-left", style={"max-width":"80px"}) +
html.TD(genre_string, Class="text-left", style={"max-width":"80px"}))
for key in track_data:
if key == "key":
for cay in song_key_codes:
if track_data[key] == cay:
track_data[key] = song_key_codes[cay]
if key == "mode":
for cay in song_mode_codes:
if track_data[key] == cay:
track_data[key] = song_mode_codes[cay]
if key == "type" or key == "uri" or key == "track_href" or key == "analysis_url" or key == "id":
pass
else:
#document <= key + ": " + str(track_data[key])
tbody <= html.TR(html.TD(key, Class="text-left", style={"max-width":"80px"}) +
html.TD(track_data[key], Class="text-left", style={"max-width":"80px"}))
rowdiv <= tablediv
container <= rowdiv
document["searchbutton"].html = ""
document["searchbutton"] <= "Show me data!"
del document["searchbutton"].attrs["disabled"]
#document["data"].attrs["style"] = "display: none"
success = getParamsFromURL()
try:
if success and storage['received_state'] == storage['spotify_auth_state']:
#document <= state
del document["dataform"].attrs["style"]
searchbutton = document["searchbutton"]
searchbutton.bind("click", searchForTrack)
else:
del document["errormessage"].attrs["style"]
except:
del document["errormessage"].attrs["style"]
track_id = "0rKtyWc8bvkriBthvHKY8d"
#getTrackData("https://api.spotify.com/v1/audio-features/" + track_id, {})
#document <= str(doc)
'''
calc = html.TABLE()
calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) +
html.TD("C"))
lines = ["789/", "456*", "123-", "0.=+"]
calc <= (html.TR(html.TD(x) for x in line) for line in lines)
document <= calc
result = document["result"] # direct acces to an element by its id
def action(event):
"""Handles the "click" event on a button of the calculator."""
# The element the user clicked on is the attribute "target" of the
# event object
element = event.target
# The text printed on the button is the element's "text" attribute
value = element.text
if value not in "=C":
# update the result zone
if result.text in ["0", "error"]:
result.text = value
else:
result.text = result.text + value
elif value == "C":
# reset
result.text = "0"
elif value == "=":
# execute the formula in result zone
try:
result.text = eval(result.text)
except:
result.text = "error"
# Associate function action() to the event "click" on all buttons
for button in document.select("td"):
button.bind("click", action)
'''
</script>
<style>
.tooltip-inner{
max-width: 350px;
}
/*
*{
font-family: sans-serif;
font-weight: normal;
font-size: 1.1em;
}
td{
background-color: #ccc;
padding: 10px 30px 10px 30px;
border-radius: 0.2em;
text-align: center;
}
result{
border-color: #000;
border-width: 1px;
border-style: solid;
padding: 10px 30px 10px 30px;
text-align: right;
}*/
</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>