-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.py
345 lines (284 loc) · 9.95 KB
/
index.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
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
from base64 import b64decode, b64encode
from flask import Flask, session, request, render_template, redirect, Response, send_from_directory
from firebase_admin import credentials, firestore
import firebase_admin
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from dotenv import load_dotenv, find_dotenv
from time import time
import os
import json
import uuid
import functools
import requests
from random import randint
import sass
from distutils.util import strtobool
from themes import themes
# Compile all SCSS themes
try:
sass.compile(dirname=("templates", "templates"), output_style="compressed")
sass.compile(dirname=("static/css", "static/css"), output_style="compressed")
except Exception as e:
print("Could not compile SCSS files")
# Load environment variables
load_dotenv(find_dotenv())
# Global Variables
FLASK_SECRET_KEY = os.getenv("FLASK_SECRET_KEY")
SPOTIFY_CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
SPOTIFY_CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
SPOTIFY_SCOPES = ["user-read-recently-played", "user-read-currently-playing"]
BASE_URL = os.getenv("BASE_URL")
REDIRECT_URI = "{}/".format(BASE_URL)
FIREBASE_CONFIG = os.getenv("FIREBASE")
CACHE_TOKEN_INFO = {}
# Initialize Firebase
firebase_json = json.loads(b64decode(FIREBASE_CONFIG))
firebase_credentials = credentials.Certificate(firebase_json)
firebase_admin.initialize_app(firebase_credentials)
firebase_db = firestore.client()
# Initialize Flask app
app = Flask(__name__)
app.secret_key = FLASK_SECRET_KEY
app.static_url_path = ''
# Spotipy custom Cache Handler
# It just saves the token_info in an unused variable since
# not saving it would trigger a Spotipy error
class UselessCacheHandler(spotipy.cache_handler.CacheHandler):
def get_cached_token(self):
"""
Get and return a token_info dictionary object.
"""
return session.get("unused_token_info")
def save_token_to_cache(self, token_info):
"""
Save a token_info dictionary object to the cache and return None.
"""
session["unused_token_info"] = token_info
return None
# Spotipy Auth Manager
cache_handler = UselessCacheHandler()
auth_manager = spotipy.oauth2.SpotifyOAuth(
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SPOTIFY_SCOPES,
cache_handler=cache_handler,
show_dialog=False,
)
# When logging in, save the user inside the Firestore Database
def save_user_to_db(auth_manager, code):
# Get Access Token
token_info = auth_manager.get_access_token(request.args.get("code"), as_dict=True)
access_token = token_info["access_token"]
# Get User Info
spotify_api = spotipy.Spotify(auth=access_token)
user_id = spotify_api.me()["id"]
# Save to Database
doc_ref = firebase_db.collection("users").document(user_id)
doc_ref.set(token_info)
# Save to session
session["token_info"] = token_info
session["token_info"]["uid"] = user_id
return user_id
# Homepage that handles login
@app.route("/")
def index():
if request.args.get("code"):
user_id = save_user_to_db(
auth_manager=auth_manager, code=request.args.get("code")
)
return redirect("/editor?uid={}".format(user_id))
rendered_data = {"title": "Home"}
session_token_info = session.get("token_info")
if not auth_manager.validate_token(session_token_info):
auth_url = auth_manager.get_authorize_url()
rendered_data["auth_url"] = auth_url
rendered_data["is_authenticated"] = False
else:
spotify = spotipy.Spotify(auth_manager=auth_manager)
rendered_data["spotify"] = spotify
rendered_data["is_authenticated"] = True
return render_template("index.html", **rendered_data)
# Disconnect the user
@app.route("/sign-out")
def sign_out():
try:
session.pop("token_info")
except OSError as e:
print("Error: %s" % (e))
return redirect("/")
# Retrieve Access Token from Session or Firestore
def get_access_token(uid):
token_info = session.get("token_info")
# If getting the widget for another user, clear
# your own token_info stored in the session
if token_info is not None and token_info["uid"] != uid:
token_info = None
if token_info is None:
doc_ref = firebase_db.collection("users").document(uid)
doc = doc_ref.get()
if not doc.exists:
return False
token_info = doc.to_dict()
if auth_manager.is_token_expired(token_info):
updated_token_info = auth_manager.validate_token(token_info)
doc_ref = firebase_db.collection("users").document(uid)
doc_ref.update(updated_token_info)
access_token = updated_token_info["access_token"]
else:
access_token = token_info["access_token"]
return access_token
# Given a user ID, return the currently playing track
def get_song_info(access_token):
spotify = spotipy.Spotify(auth=access_token)
track = spotify.current_user_playing_track()
if track is not None and track["item"] is not None:
return track, True
else:
# Get a random recently played track from the last 10
tracks = spotify.current_user_recently_played(limit=10)
track = {}
track["item"] = tracks["items"][randint(0, 9)]["track"]
return track, False
return "not playing", False
# Widget Editor page
@app.route("/editor")
def editor():
uid = request.args.get("uid")
if not uid:
return redirect("/")
access_token = get_access_token(uid)
if not access_token:
return Response("User not authorized", status=403)
song, is_now_playing = get_song_info(access_token)
rendered_data = {
"title": "Editor",
"uid": uid,
"song": song,
"is_now_playing": is_now_playing,
"themes": themes,
}
return render_template("editor.html", **rendered_data)
# Convert song cover to base64 to be used in the SVG
@functools.lru_cache(maxsize=128)
def load_image_b64(url):
response = requests.get(url)
return b64encode(response.content).decode("ascii")
# Render the Widget SVG
@functools.lru_cache(maxsize=128)
def generate_svg(
theme,
height,
song_title,
song_artist,
song_cover_base64,
song_progress,
song_duration,
song_uri,
is_now_playing,
invert_artist_title,
cover,
progress_bar,
progress_color,
sound_waves,
sound_waves_color,
background,
background_color,
):
rendered_data = {
"theme": theme,
"height": height,
"song_title": song_title,
"song_artist": song_artist,
"song_cover_base64": song_cover_base64,
"song_progress": song_progress,
"song_duration": song_duration,
"song_uri": song_uri,
"is_now_playing": is_now_playing,
"invert_artist_title": invert_artist_title,
"cover": cover,
"progress_bar": progress_bar,
"progress_color": progress_color,
"sound_waves": sound_waves,
"sound_waves_color": sound_waves_color,
"background": background,
"background_color": background_color,
}
return render_template(f"themes/{theme}/{theme}.html", **rendered_data)
# Widget SVG direct URL
@app.route("/widget")
def widget():
uid = request.args.get("uid")
if not uid:
return redirect("/")
theme = request.args.get("theme", default="default")
if theme not in themes:
print("Theme not found")
# Get this theme's max height
height = themes[theme]["max_height"]
# Get all the parameters from the request
invert_artist_title = request.args.get("invert_artist_title") == "true"
cover = request.args.get("cover") == "true"
progress_bar = request.args.get("progress_bar") == "true"
progress_color = request.args.get("progress_color", "#B3B3B3")
sound_waves = request.args.get("sound_waves") == "true"
sound_waves_color = request.args.get("sound_waves_color", "#1ed760")
background = request.args.get("background") == "true"
background_color = request.args.get("background_color", "#121212")
# Get the song info
access_token = get_access_token(uid)
if not access_token:
return Response("User not authorized", status=403)
song, is_now_playing = get_song_info(access_token)
# Pick data we need for the widget
song_title = song["item"]["name"]
if song["item"]["type"] == "track":
song_cover_base64 = load_image_b64(song["item"]["album"]["images"][0]["url"])
elif song["item"]["type"] == "episode":
song_cover_base64 = load_image_b64(song["item"]["images"][0]["url"])
song_artist = song["item"]["artists"][0]["name"]
song_progress = song["progress_ms"] if is_now_playing else 0
song_duration = song["item"]["duration_ms"]
song_uri = song["item"]["uri"]
# Generate the SVG
# I need to pass single parameters because the caching decorator
# does not accept dictionaries/lists
svg_code = generate_svg(
theme,
height,
song_title,
song_artist,
song_cover_base64,
song_progress,
song_duration,
song_uri,
is_now_playing,
invert_artist_title,
cover,
progress_bar,
progress_color,
sound_waves,
sound_waves_color,
background,
background_color,
)
resp = Response(svg_code, mimetype="image/svg+xml")
resp.headers["Cache-Control"] = "s-maxage=1"
return resp
@app.context_processor
def context_processor():
@functools.lru_cache(maxsize=128)
def generate_css_bar(bar_count=75, bar_width=3, bar_spacing=1):
css_bar = ""
for i in range(1, bar_count + 1):
anim = randint(350, 500)
css_bar += ".bar:nth-child({}) {{ margin-left: {}px; animation-duration: {}ms; width: {}px; }}".format(
i, bar_spacing, anim, bar_width
)
return css_bar
return {
"generate_css_bar": generate_css_bar,
}
if __name__ == "__main__":
app.run(debug=True)