-
Notifications
You must be signed in to change notification settings - Fork 664
/
view.py
284 lines (210 loc) · 7.63 KB
/
view.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
from flask import Flask, Response, jsonify, render_template, redirect, request
from base64 import b64decode, b64encode
from dotenv import load_dotenv, find_dotenv
from util.firestore import get_firestore_db
load_dotenv(find_dotenv())
from sys import getsizeof
from PIL import Image
from time import time
import io
from util import spotify
import random
import requests
import functools
import colorgram
import math
print("Starting Server")
db = None
CACHE_TOKEN_INFO = {}
app = Flask(__name__)
@functools.lru_cache(maxsize=128)
def generate_css_bar(num_bar=75):
css_bar = ""
left = 1
for i in range(1, num_bar + 1):
anim = random.randint(350, 500)
css_bar += ".bar:nth-child({}) {{ left: {}px; animation-duration: {}ms; }}".format(
i, left, anim
)
left += 4
return css_bar
@functools.lru_cache(maxsize=128)
def load_image(url):
resposne = requests.get(url)
return resposne.content
def to_img_b64(content):
return b64encode(content).decode("ascii")
def load_image_b64(url):
return to_img_b64(load_image(url))
def isLightOrDark(rgbColor=[0, 128, 255], threshold=127.5):
# https://stackoverflow.com/a/58270890
[r, g, b] = rgbColor
hsp = math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))
if hsp > threshold:
return "light"
else:
return "dark"
@functools.lru_cache(maxsize=128)
def make_svg(
artist_name, song_name, img, is_now_playing, cover_image, theme, bar_color, show_offline
):
height = 0
num_bar = 75
if theme == "compact":
if cover_image:
height = 400
else:
height = 100
elif theme == "natemoo-re":
height = 84
num_bar = 100
elif theme == "novatorem":
height = 100
num_bar = 100
else:
if cover_image:
height = 445
else:
height = 145
if is_now_playing:
title_text = "Now playing"
content_bar = "".join(["<div class='bar'></div>" for i in range(num_bar)])
css_bar = generate_css_bar(num_bar)
elif show_offline:
title_text = "Not playing"
content_bar = ""
css_bar = None
else:
title_text = "Recently played"
content_bar = ""
css_bar = generate_css_bar(num_bar)
rendered_data = {
"height": height,
"num_bar": num_bar,
"content_bar": content_bar,
"css_bar": css_bar,
"title_text": title_text,
"artist_name": artist_name,
"song_name": song_name,
"img": img,
"cover_image": cover_image,
"bar_color": bar_color,
}
return render_template(f"spotify.{theme}.html.j2", **rendered_data)
def get_cache_token_info(uid):
global CACHE_TOKEN_INFO
token_info = CACHE_TOKEN_INFO.get(uid, None)
if type(token_info) == dict:
current_ts = int(time())
expired_ts = token_info.get("expired_ts")
if expired_ts is None or current_ts >= expired_ts:
return None
return token_info
def get_access_token(uid):
global CACHE_TOKEN_INFO
# Load token from cache memory
token_info = get_cache_token_info(uid)
if token_info is None:
# Load from firebase
doc_ref = db.collection("users").document(uid)
doc = doc_ref.get()
if not doc.exists:
print("not exist")
# TODO: show error
return Response("not ok")
token_info = doc.to_dict()
CACHE_TOKEN_INFO[uid] = token_info
current_ts = int(time())
access_token = token_info["access_token"]
# Check token expired
expired_ts = token_info.get("expired_ts")
if expired_ts is None or current_ts >= expired_ts:
# Refresh token
refresh_token = token_info["refresh_token"]
new_token = spotify.refresh_token(refresh_token)
expired_ts = int(time()) + new_token["expires_in"]
update_data = {"access_token": new_token["access_token"], "expired_ts": expired_ts}
doc_ref = db.collection("users").document(uid)
doc_ref.update(update_data)
access_token = new_token["access_token"]
# Save in memory cache
CACHE_TOKEN_INFO[uid] = update_data
return access_token
def get_song_info(uid, show_offline):
access_token = get_access_token(uid)
data = spotify.get_now_playing(access_token)
if data:
item = data["item"]
item["currently_playing_type"] = data["currently_playing_type"]
is_now_playing = True
elif show_offline:
return None, False
else:
recent_plays = spotify.get_recently_play(access_token)
size_recent_play = len(recent_plays["items"])
idx = random.randint(0, size_recent_play - 1)
item = recent_plays["items"][idx]["track"]
item["currently_playing_type"] = "track"
is_now_playing = False
return item, is_now_playing
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def catch_all(path):
uid = request.args.get("uid")
cover_image = request.args.get("cover_image", default="true") == "true"
is_redirect = request.args.get("redirect", default="false") == "true"
theme = request.args.get("theme", default="default")
bar_color = request.args.get("bar_color", default="53b14f")
is_bar_color_from_cover = request.args.get("bar_color_cover", default="false") == "true"
show_offline = request.args.get("show_offline", default="false") == "true"
item, is_now_playing = get_song_info(uid, show_offline)
if show_offline and not is_now_playing:
artist_name = "Offline"
song_name = "Currently not playing on Spotify"
img_b64 = ""
cover_image = False
svg = make_svg(artist_name, song_name, img_b64, is_now_playing, cover_image, theme, bar_color, show_offline)
resp = Response(svg, mimetype="image/svg+xml")
resp.headers["Cache-Control"] = "s-maxage=1"
return resp
currently_playing_type = item.get("currently_playing_type", "track")
if is_redirect:
return redirect(item["uri"], code=302)
img = None
img_b64 = ""
if cover_image:
if currently_playing_type == "track":
img = load_image(item["album"]["images"][1]["url"])
elif currently_playing_type == "episode":
img = load_image(item["images"][1]["url"])
img_b64 = to_img_b64(img)
# Extract cover image color
if is_bar_color_from_cover and img:
is_skip_dark = False
if theme in ["default"]:
is_skip_dark = True
pil_img = Image.open(io.BytesIO(img))
colors = colorgram.extract(pil_img, 5)
for color in colors:
rgb = color.rgb
light_or_dark = isLightOrDark([rgb.r, rgb.g, rgb.b], threshold=80)
if light_or_dark == "dark" and is_skip_dark:
# Skip to use bar in dark color
continue
bar_color = "%02x%02x%02x" % rgb
break
# Find artist_name and song_name
if currently_playing_type == "track":
artist_name = item["artists"][0]["name"].replace("&", "&")
song_name = item["name"].replace("&", "&")
elif currently_playing_type == "episode":
artist_name = item["show"]["publisher"].replace("&", "&")
song_name = item["name"].replace("&", "&")
svg = make_svg(artist_name, song_name, img_b64, is_now_playing, cover_image, theme, bar_color, show_offline)
resp = Response(svg, mimetype="image/svg+xml")
resp.headers["Cache-Control"] = "s-maxage=1"
print("cache size:", getsizeof(CACHE_TOKEN_INFO))
return resp
if __name__ == "__main__":
db = get_firestore_db()
app.run(debug=True, port=5003)