Repository navigation
Expand file tree
/
Copy pathspotify.js
More file actions
479 lines (390 loc) · 13.9 KB
/
Copy pathspotify.js
File metadata and controls
479 lines (390 loc) · 13.9 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
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
const fs = require("fs");
const path = require("path");
const { Vibrant } = require("node-vibrant/node");
const { loadToken, saveToken } = require('./spotify-token-store');
const { getCanvas } = require("./canvas");
const MAX_CACHE_SIZE = 100;
const paletteCache = new Map();
const fallbackCache = new Map();
const currentTrackCache = {
expiresAt: 0,
value: null,
pending: null
};
const SPOTIFY_PATTERN = /https:\/\/open\.spotify\.com\/(?:intl-[^/]+\/)?track\/[a-zA-Z0-9]{22}(?:\?si=[a-zA-Z0-9]+)?/;
function formatTrack(track) {
const id = track.id || `local-${track.name}-${track.duration_ms}`;
return {
id,
// Every id this song goes by - see core/sameTrack.js. Asked for with
// market=from_token, Spotify plays a copy available in the streamer's
// country and names the one that was asked for in linked_from.
ids: [...new Set([id, track.linked_from?.id].filter(Boolean))],
name: track.name,
artists: track.artists?.map(artist => artist.name).join(', ') || 'Local Track',
durationMs: track.duration_ms,
cover: track.album?.images?.[0]?.url || null,
// Spotify lists the sizes largest first. The smallest is what a chip in
// the widget's Up next row needs, at a fraction of the download.
thumb: track.album?.images?.at(-1)?.url || null,
isLocal: !track.id
};
}
const FALLBACK_VIDEO_DIR = path.join(__dirname, "assets", "fallback_videos");
const FALLBACK_VIDEOS = fs.existsSync(FALLBACK_VIDEO_DIR)
? fs.readdirSync(FALLBACK_VIDEO_DIR)
.filter(file => file.endsWith(".mp4"))
.map(file => `/assets/fallback_videos/${file}`)
: [];
function getRandomFallbackVideo() {
if (!FALLBACK_VIDEOS.length) {
return null;
}
return FALLBACK_VIDEOS[
Math.floor(Math.random() * FALLBACK_VIDEOS.length)
];
}
function trimCache(cache, maxSize) {
while (cache.size > maxSize) {
const oldestKey = cache.keys().next().value;
cache.delete(oldestKey);
}
}
async function getMedia(track) {
const canvas = await getCanvas(track.id);
if (canvas?.includes("canvaz.scdn.co") && canvas.endsWith(".mp4")) {
return {
type: "video",
url: canvas
};
}
if (track.cover) {
return {
type: "image",
url: track.cover
};
}
const fallbackKey = `${track.name}-${track.artists}-${track.durationMs}`;
if (!fallbackCache.has(fallbackKey)) {
fallbackCache.set(
fallbackKey,
getRandomFallbackVideo()
);
trimCache(fallbackCache, MAX_CACHE_SIZE);
}
return {
type: "video",
url: fallbackCache.get(fallbackKey)
};
}
async function getPalette(trackId, imageUrl) {
if (!imageUrl) return null;
if (paletteCache.has(trackId)) {
return paletteCache.get(trackId);
}
try {
const palette = await Vibrant
.from(imageUrl)
.getPalette();
const colors = {
vibrant: palette.Vibrant?.hex,
darkVibrant: palette.DarkVibrant?.hex,
lightVibrant: palette.LightVibrant?.hex,
muted: palette.Muted?.hex,
darkMuted: palette.DarkMuted?.hex,
lightMuted: palette.LightMuted?.hex
};
paletteCache.set(trackId, colors);
trimCache(paletteCache, MAX_CACHE_SIZE);
return colors;
} catch (err) {
console.error("Palette extraction failed:", err);
return null;
}
}
function getTrackId(url) {
const match = url?.match(SPOTIFY_PATTERN);
if (!match) return null;
return match[0].split('/track/')[1].split('?')[0];
}
const MAX_FETCH_RETRIES = 2;
const FETCH_RETRY_DELAY_MS = 200;
const MAX_RATE_LIMIT_RETRIES = 3;
class SpotifyApiError extends Error {
constructor(status, message) {
super(message);
this.name = 'SpotifyApiError';
this.status = status;
}
}
async function getApiError(response) {
try {
const data = await response.json();
return data?.error?.message || data?.message || `Spotify API request failed with status ${response.status}`;
} catch {
return `Spotify API request failed with status ${response.status}`;
}
}
function getRetryDelay(response, attempt) {
const retryAfter = Number(response.headers?.get?.('Retry-After'));
if (Number.isFinite(retryAfter) && retryAfter >= 0) {
return retryAfter * 1000;
}
return FETCH_RETRY_DELAY_MS * 2 ** (attempt - 1);
}
async function fetchWithRateLimitRetry(url, options, attempt = 1) {
const response = await fetch(url, options);
if (response.status === 429 && attempt <= MAX_RATE_LIMIT_RETRIES) {
const delay = getRetryDelay(response, attempt);
console.warn(`Spotify rate limit reached, retrying in ${delay}ms (${attempt}/${MAX_RATE_LIMIT_RETRIES})...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRateLimitRetry(url, options, attempt + 1);
}
return response;
}
function shouldRetryFetchError(err) {
if (!err) return false;
const code = err.code || err?.cause?.code;
return typeof code === 'string' && code.startsWith('UND_ERR');
}
async function fetchWithToken(url, options = {}, retry = true, attempt = 1) {
let token = await getValidToken();
try {
const response = await fetch(url, {
...options,
headers: {
...(options.headers || {}),
Authorization: `Bearer ${token}`
}
});
if (response.status === 401 && retry) {
token = await refreshAccessToken(token);
return fetchWithToken(url, options, false, attempt);
}
if (response.status === 429 && attempt <= MAX_RATE_LIMIT_RETRIES) {
const delay = getRetryDelay(response, attempt);
console.warn(`Spotify rate limit reached, retrying in ${delay}ms (${attempt}/${MAX_RATE_LIMIT_RETRIES})...`);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithToken(url, options, retry, attempt + 1);
}
if (!response.ok) {
throw new SpotifyApiError(response.status, await getApiError(response));
}
return response;
} catch (err) {
if (attempt <= MAX_FETCH_RETRIES && shouldRetryFetchError(err)) {
console.warn(`Spotify fetch error, retrying (${attempt}/${MAX_FETCH_RETRIES})...`, err.code || err.message);
await new Promise(resolve => setTimeout(resolve, FETCH_RETRY_DELAY_MS));
return fetchWithToken(url, options, retry, attempt + 1);
}
throw err;
}
}
let refreshPromise = null;
async function refreshAccessToken(expectedToken = null) {
const currentTokenData = loadToken();
// Someone else's concurrent refresh already replaced the token we were
// trying to refresh away from - use it instead of firing another grant.
if (expectedToken && currentTokenData.access_token !== expectedToken) {
return currentTokenData.access_token;
}
if (!currentTokenData.refresh_token) {
throw new Error('Missing Spotify refresh token. Run `node auth.js` first.');
}
if (!process.env.SPOTIFY_CLIENT_ID || !process.env.SPOTIFY_CLIENT_SECRET) {
throw new Error('Missing SPOTIFY_CLIENT_ID or SPOTIFY_CLIENT_SECRET in .env');
}
if (!refreshPromise) {
refreshPromise = (async () => {
const response = await fetchWithRateLimitRetry('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + Buffer.from(
process.env.SPOTIFY_CLIENT_ID + ':' + process.env.SPOTIFY_CLIENT_SECRET
).toString('base64')
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: currentTokenData.refresh_token
})
});
const data = await response.json().catch(() => ({}));
if (!response.ok) {
if (response.status === 400 && data.error === 'invalid_grant') {
throw new Error('Spotify refresh token expired or was revoked. Run `node auth.js` to authorize again.');
}
throw new Error(data.error_description || data.error || `Spotify token refresh failed with status ${response.status}`);
}
if (!data.access_token || !data.expires_in) {
throw new Error(`Spotify token refresh response was incomplete: ${JSON.stringify(data)}`);
}
const updatedTokenData = {
...currentTokenData,
access_token: data.access_token,
expires_at: Date.now() + data.expires_in * 1000,
...(data.refresh_token ? { refresh_token: data.refresh_token } : {})
};
saveToken(updatedTokenData);
console.log('Spotify token refreshed.');
return updatedTokenData.access_token;
})().finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
async function getValidToken() {
const currentTokenData = loadToken();
if (currentTokenData.access_token && Date.now() < currentTokenData.expires_at - 60000) {
return currentTokenData.access_token;
}
return await refreshAccessToken();
}
async function addToQueue(url, maxSongLengthSeconds, allowExplicit = true, trackData = null) {
return addTrackToQueue(url, maxSongLengthSeconds, allowExplicit, trackData);
}
async function skipToNext() {
try {
await fetchWithToken('https://api.spotify.com/v1/me/player/next', {
method: 'POST'
});
return true;
} catch (err) {
console.error('Spotify skip failed:', err.message, err.status ? `(HTTP ${err.status})` : '');
return false;
}
}
async function getTrack(url) {
try {
if (!url) return 'noinput';
const trackId = getTrackId(url);
if (!trackId) return 'invalid';
// from_token: the copy that will actually play here, with the id that was
// asked for in linked_from, so the request can be recognized whichever id
// Spotify reports once it starts.
const trackRes = await fetchWithToken(`https://api.spotify.com/v1/tracks/${trackId}?market=from_token`);
if (!trackRes.ok) return null;
return await trackRes.json();
} catch (err) {
console.error('Spotify track lookup failed:', err.message, err.status ? `(HTTP ${err.status})` : '');
return null;
}
}
async function addTrackToQueue(url, maxSongLengthSeconds, allowExplicit = true, trackData = null) {
try {
if (!url) return 'noinput';
const trackId = getTrackId(url);
if (!trackId) return 'invalid';
const uri = `spotify:track:${trackId}`;
trackData ??= await getTrack(url);
if (!trackData) return 'failed';
if (trackData.explicit && !allowExplicit) return 'explicit';
if (trackData.duration_ms > maxSongLengthSeconds * 1000) return 'toolong';
const queueRes = await fetchWithToken(`https://api.spotify.com/v1/me/player/queue?uri=${encodeURIComponent(uri)}`, {
method: 'POST'
});
if (!queueRes.ok) return 'failed';
return {
status: 'ok',
track: formatTrack(trackData)
};
} catch (err) {
console.error('Spotify queue failed:', err.message, err.status ? `(HTTP ${err.status})` : '');
return { status: 'failed', message: err.message };
}
}
/**
* What is playing, or `{ isPlaying: false }` when nothing is, or false when
* Spotify could not be asked.
*
* Answers are shared for two seconds, because the widget asks constantly.
* `fresh` skips that: the queue bookkeeping in services/syncQueue.js reads
* this next to the queue, and a two-second-old answer next to a new queue is
* what used to hand a request's credit to nobody at the moment a song changed.
* `quiet` keeps a failure out of the console, for the background watcher that
* would otherwise repeat it every few seconds.
*/
async function getCurrentTrack({ fresh = false, quiet = false } = {}) {
if (!fresh) {
const now = Date.now();
if (currentTrackCache.expiresAt > now && currentTrackCache.value) {
return currentTrackCache.value;
}
if (currentTrackCache.pending) {
return currentTrackCache.pending;
}
}
const lookup = fetchCurrentTrack(quiet);
if (!fresh) {
currentTrackCache.pending = lookup.finally(() => {
currentTrackCache.pending = null;
});
return currentTrackCache.pending;
}
return lookup;
}
async function fetchCurrentTrack(quiet) {
try {
// from_token adds linked_from to a relinked track - see formatTrack.
const response = await fetchWithToken(
"https://api.spotify.com/v1/me/player?market=from_token"
);
if (response.status === 204) {
return {
isPlaying: false
};
}
if (!response.ok) {
throw new SpotifyApiError(response.status, await getApiError(response));
}
const data = await response.json();
// When the playhead was read - taken now, before the cover art and its
// colors are fetched, which can take a moment the first time a song is
// seen. core/state.js times how far a song can have got by this.
const fetchedAt = Date.now();
if (!data.item || data.currently_playing_type !== "track") {
return {
isPlaying: false
};
}
const track = formatTrack(data.item);
const media = await getMedia(track);
const result = {
...track,
media,
progressMs: data.progress_ms,
durationMs: data.item.duration_ms,
isPlaying: data.is_playing,
fetchedAt,
palette: await getPalette(track.id, track.cover)
};
currentTrackCache.value = result;
currentTrackCache.expiresAt = Date.now() + 2000;
return result;
} catch (err) {
if (!quiet) {
console.error("Spotify active lookup failed:", err.message, err.status ? `(HTTP ${err.status})` : '');
}
return false;
}
}
async function getUserQueue() {
try {
const response = await fetchWithToken('https://api.spotify.com/v1/me/player/queue');
if (!response.ok) {
throw new SpotifyApiError(response.status, await getApiError(response));
}
const data = await response.json();
return {
currentlyPlaying: data.currently_playing?.type === 'track' ? formatTrack(data.currently_playing) : null,
queue: (data.queue || [])
.filter(item => item.type === 'track')
.map(formatTrack)
};
} catch (err) {
console.error('Spotify queue lookup failed:', err.message, err.status ? `(HTTP ${err.status})` : '');
return false;
}
}
module.exports = { addToQueue, skipToNext, getCurrentTrack, getUserQueue, getTrackId, getTrack };