-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
175 lines (152 loc) · 5.48 KB
/
app.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
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
from time import sleep
import random
import argparse
import os
import csv
import sys
from pathlib import Path
from flask import Flask, redirect
app = Flask(__name__)
scope = "user-read-playback-state,user-modify-playback-state"
sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope))
tracks = []
current_track = ""
tsv_file = open(os.environ.get("TSV_FILE"))
playlist_title = Path(os.path.basename(tsv_file.name)).stem
tsv_reader = csv.reader(tsv_file, delimiter="\t")
tsv_clues = []
for row in tsv_reader:
tsv_clues.append(row)
unique_cats = []
for track in tsv_clues:
if track[5] not in unique_cats:
unique_cats.append(track[5])
def get_playlist_tracks(playlist_id):
pl_id = f"spotify:playlist:{playlist_id}"
offset = 0
while True:
response = sp.playlist_items(pl_id,
offset=offset,
fields='items.track.id,total',
additional_types=['track'])
if len(response['items']) == 0:
break
for t in response['items']:
# print(t['track']['id'])
tracks.append(t['track']['id'])
# pprint(response['items'])
offset = offset + len(response['items'])
print(f"{response['total']} total tracks in the playlist")
def play_track_for_x_time(track, time, start_point=-1):
# in seconds
playback_length = int(time)
start_point = int(start_point)
info = sp.track(track)
# TODO: Print artist
print(f"Playing {info['name']} from {start_point} seconds for {time} seconds")
current_track = f"Playing {info['name']}"
track_length = info['duration_ms']
if start_point == -1:
start = random.randint(0, track_length-playback_length*1000)
else:
start = start_point
# Shows playing devices
res = sp.devices()
# Change track
try:
sp.start_playback(uris=[f'spotify:track:{track}'], position_ms=start*1000)
except:
print("No devices found.\nMake sure to open Spotify in your browser or on your phone before starting.")
sys.exit()
sleep(playback_length)
print("Stopping playback")
sp.pause_playback()
def generate_html():
output = ""
for cat in unique_cats:
it = 1
output += "<tr>"
output += "<td>" + cat + "</td>"
for track in tsv_clues:
if track[5] == cat:
output += f"""
<td id="clue{it}"><a onclick="toggleView('clue{it}')" href="/shuffleplay/{it}">Clue {it}</a>
"""
it += 1
output += "</tr>"
# output = ""
# output += "<tr>"
# for cat in unique_cats:
# output += "<td>" + cat + "</td>"
# for cat in unique_cats:
# track_list = clues_by_cat[cat]
# for i in range(0,max_cat_length):
# pass
output = ""
for cat in unique_cats:
it = 1
output += "<div class='col text-center' style='height:60px;'><h4 class='h-100 overflow-hidden'>" + cat + "</h4><div class='dropdown-divider'></div>"
for track in tsv_clues:
if track[5] == cat:
output += f"""
<p class="bg-light" id="clue{it}"><a class="dropdown-item" onclick="toggleView('clue{it}')" href="/shuffleplay/{it}">Clue {it}</a></p>
"""
it += 1
output += "</div>"
return output
@app.route('/')
def webapp():
output = ("""
<html>
<head>
<title>Python Music Trivia - """ + playlist_title + """</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<style>
a:focus {
background: #c2ffbd !important;
}
</style>
<script>
function toggleView(id) {
var x = document.getElementById(id);
x.style.backgroundColor = "#c2ffbd";
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].onclick = function() {return false;};
}
}
</script>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col text-center">
<h1>Playlist: """ + playlist_title + """</h1>
<p>Click on any clue to start playback. Clue links are disabled until playback is finished.</p>
<p>The currently playing clue will be highlighted in <span style="background-color: #c2ffbd;">green</span>.</p>
</div>
</div>
</div>
<div class="container"><div class="row align-items-start">
""" + generate_html() +
"""
</div></div>
</body>
</html>
""")
return output
@app.route('/shuffleplay/<int:id>')
def shuffle_play(id):
id = id - 1
try:
play_track_for_x_time(tsv_clues[id][0], tsv_clues[id][4], tsv_clues[id][3])
except:
return """
<p>Oops. Spotify needs to be open on a device before this will work.</p>
<p>Click <a href='https://open.spotify.com/track/2d7139N7CJ9eJmGVE42Y44?si=94e5a32190fb45d2' target=_blank>here</a> to open Spotify in another browser tab and press the play button to activate the device for playback.<br/><b>Keep the Spotify tab open</b>.</p>
<p>Then go back to the <a href='/'>home page</a> and try again.</p>
"""
return redirect('/')