@sdeck/plugin-spotify 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.d.ts +106 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2165 -0
- package/dist/index.js.map +24 -0
- package/dist/panels.d.ts +11 -0
- package/dist/panels.d.ts.map +1 -0
- package/package.json +60 -4
- package/src/api.ts +425 -0
- package/src/index.tsx +872 -0
- package/src/panels.tsx +261 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdeck/plugin-spotify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Built-in sdeck integration. Spotify: now playing and playback control.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"keywords": [
|
|
9
|
+
"sdeck-plugin"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"main": "./dist/index.js",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"bun": "./src/index.tsx",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"sdeck": {
|
|
26
|
+
"apiVersion": 2,
|
|
27
|
+
"entry": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "bun ../../scripts/build-package.ts --target=bun",
|
|
31
|
+
"clean": "rm -rf dist",
|
|
32
|
+
"test": "bun test"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@sdeck/plugin": "^0.1.0",
|
|
36
|
+
"@sdeck/schema": "^0.1.0",
|
|
37
|
+
"react": ">=19.3"
|
|
38
|
+
},
|
|
39
|
+
"peerDependenciesMeta": {
|
|
40
|
+
"@sdeck/plugin": {
|
|
41
|
+
"optional": true
|
|
42
|
+
},
|
|
43
|
+
"@sdeck/schema": {
|
|
44
|
+
"optional": true
|
|
45
|
+
},
|
|
46
|
+
"react": {
|
|
47
|
+
"optional": true
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@sdeck/plugin": "0.1.0",
|
|
52
|
+
"@sdeck/schema": "0.1.0"
|
|
53
|
+
},
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/ivanoliverfabra/sdeck.git",
|
|
57
|
+
"directory": "packages/plugin-spotify"
|
|
58
|
+
},
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"access": "public"
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spotify's Web API with the Authorization Code flow with PKCE: the user's own client id, no
|
|
3
|
+
* client secret. Only the refresh token is kept.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
export const SCOPES = [
|
|
8
|
+
"user-read-playback-state",
|
|
9
|
+
"user-modify-playback-state",
|
|
10
|
+
"user-read-currently-playing",
|
|
11
|
+
"user-library-read",
|
|
12
|
+
"user-library-modify",
|
|
13
|
+
"playlist-read-private",
|
|
14
|
+
"playlist-read-collaborative",
|
|
15
|
+
"playlist-modify-public",
|
|
16
|
+
"playlist-modify-private",
|
|
17
|
+
];
|
|
18
|
+
|
|
19
|
+
export interface Endpoints {
|
|
20
|
+
accounts: string;
|
|
21
|
+
api: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const SPOTIFY: Endpoints = {
|
|
25
|
+
accounts: "https://accounts.spotify.com",
|
|
26
|
+
api: "https://api.spotify.com/v1",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export function createPkce() {
|
|
30
|
+
const verifier = randomBytes(64).toString("base64url");
|
|
31
|
+
const challenge = createHash("sha256").update(verifier).digest("base64url");
|
|
32
|
+
return { verifier, challenge };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface SignIn {
|
|
36
|
+
/** Where to send the user. */
|
|
37
|
+
url: string;
|
|
38
|
+
/** Resolves once they approved and the tokens are saved. */
|
|
39
|
+
done: Promise<void>;
|
|
40
|
+
cancel(): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface ClientOptions {
|
|
44
|
+
clientId: () => string;
|
|
45
|
+
tokens: {
|
|
46
|
+
get(): string | undefined;
|
|
47
|
+
set(refresh: string | undefined): Promise<void>;
|
|
48
|
+
};
|
|
49
|
+
endpoints?: Endpoints;
|
|
50
|
+
fetch?: typeof fetch;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type Method = "GET" | "PUT" | "POST" | "DELETE";
|
|
54
|
+
|
|
55
|
+
export class RateLimited extends Error {
|
|
56
|
+
constructor(readonly retryAfterMs: number) {
|
|
57
|
+
super(`Spotify asks to slow down for ${Math.ceil(retryAfterMs / 1000)} s`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Not signed in: there is nothing to retry until the user signs in. */
|
|
62
|
+
export class SignedOut extends Error {
|
|
63
|
+
constructor(message = "Sign in to Spotify from the plugin's page") {
|
|
64
|
+
super(message);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const REASONS: Record<string, string> = {
|
|
69
|
+
PREMIUM_REQUIRED: "Spotify only lets Premium accounts control playback",
|
|
70
|
+
NO_ACTIVE_DEVICE: "nothing is playing: start Spotify on a device first",
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const page = (message: string) =>
|
|
74
|
+
new Response(`<!doctype html><meta charset="utf-8"><title>sdeck</title><p>${message}</p>`, {
|
|
75
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
export class SpotifyClient {
|
|
79
|
+
readonly #options: ClientOptions;
|
|
80
|
+
readonly #endpoints: Endpoints;
|
|
81
|
+
readonly #fetch: typeof fetch;
|
|
82
|
+
#access: { token: string; expires: number } | undefined;
|
|
83
|
+
#refreshing: Promise<string> | undefined;
|
|
84
|
+
|
|
85
|
+
constructor(options: ClientOptions) {
|
|
86
|
+
this.#options = options;
|
|
87
|
+
this.#endpoints = options.endpoints ?? SPOTIFY;
|
|
88
|
+
this.#fetch = options.fetch ?? fetch;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get signedIn(): boolean {
|
|
92
|
+
return this.#options.tokens.get() !== undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Starts signing in: listens on `http://127.0.0.1:<port>/callback` (which must be one of the
|
|
97
|
+
* app's redirect URIs) until the user approves, or five minutes pass.
|
|
98
|
+
*/
|
|
99
|
+
signIn(port: number, timeoutMs = 300_000): SignIn {
|
|
100
|
+
const clientId = this.#options.clientId();
|
|
101
|
+
if (!clientId) throw new Error("set your Spotify client id first");
|
|
102
|
+
const { verifier, challenge } = createPkce();
|
|
103
|
+
const state = randomBytes(16).toString("base64url");
|
|
104
|
+
let finish: (error?: Error) => void = () => {};
|
|
105
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
106
|
+
finish = (error) => (error ? reject(error) : resolve());
|
|
107
|
+
});
|
|
108
|
+
const server = Bun.serve({
|
|
109
|
+
hostname: "127.0.0.1",
|
|
110
|
+
port,
|
|
111
|
+
fetch: async (request) => {
|
|
112
|
+
const url = new URL(request.url);
|
|
113
|
+
if (url.pathname !== "/callback") return new Response("not found", { status: 404 });
|
|
114
|
+
// A page elsewhere cannot finish the sign-in: it does not know `state`.
|
|
115
|
+
if (url.searchParams.get("state") !== state) {
|
|
116
|
+
return new Response("wrong state", { status: 400 });
|
|
117
|
+
}
|
|
118
|
+
const code = url.searchParams.get("code");
|
|
119
|
+
if (!code) {
|
|
120
|
+
close(new Error(`Spotify said: ${url.searchParams.get("error") ?? "no code"}`));
|
|
121
|
+
return page("sdeck was not given access. You can close this tab.");
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
await this.#token({
|
|
125
|
+
grant_type: "authorization_code",
|
|
126
|
+
code,
|
|
127
|
+
redirect_uri: redirect,
|
|
128
|
+
code_verifier: verifier,
|
|
129
|
+
});
|
|
130
|
+
close();
|
|
131
|
+
return page("sdeck is connected to Spotify. You can close this tab.");
|
|
132
|
+
} catch (error) {
|
|
133
|
+
close(error as Error);
|
|
134
|
+
return page("Signing in failed. See the plugin's page in sdeck.");
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
const redirect = `http://127.0.0.1:${server.port}/callback`;
|
|
139
|
+
const timer = setTimeout(() => close(new Error("signing in timed out")), timeoutMs);
|
|
140
|
+
let closed = false;
|
|
141
|
+
const close = (error?: Error) => {
|
|
142
|
+
if (closed) return;
|
|
143
|
+
closed = true;
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
// Let the answer to the browser go out first.
|
|
146
|
+
setTimeout(() => server.stop(), 100);
|
|
147
|
+
finish(error);
|
|
148
|
+
};
|
|
149
|
+
const url = new URL("/authorize", this.#endpoints.accounts);
|
|
150
|
+
url.search = new URLSearchParams({
|
|
151
|
+
client_id: clientId,
|
|
152
|
+
response_type: "code",
|
|
153
|
+
redirect_uri: redirect,
|
|
154
|
+
scope: SCOPES.join(" "),
|
|
155
|
+
state,
|
|
156
|
+
code_challenge_method: "S256",
|
|
157
|
+
code_challenge: challenge,
|
|
158
|
+
}).toString();
|
|
159
|
+
return { url: url.toString(), done, cancel: () => close(new Error("sign-in cancelled")) };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async signOut(): Promise<void> {
|
|
163
|
+
this.#access = undefined;
|
|
164
|
+
await this.#options.tokens.set(undefined);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Calls the API; resolves with the JSON answer, or `undefined` for an empty one. `body` is sent
|
|
169
|
+
* as JSON.
|
|
170
|
+
*/
|
|
171
|
+
async request(
|
|
172
|
+
method: Method,
|
|
173
|
+
path: string,
|
|
174
|
+
query: Record<string, string> = {},
|
|
175
|
+
body?: unknown,
|
|
176
|
+
): Promise<unknown> {
|
|
177
|
+
const url = new URL(`${this.#endpoints.api}${path}`);
|
|
178
|
+
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
|
|
179
|
+
for (let attempt = 0; ; attempt++) {
|
|
180
|
+
const token = await this.#accessToken();
|
|
181
|
+
const response = await this.#fetch(url, {
|
|
182
|
+
method,
|
|
183
|
+
headers: {
|
|
184
|
+
authorization: `Bearer ${token}`,
|
|
185
|
+
...(body !== undefined && { "content-type": "application/json" }),
|
|
186
|
+
},
|
|
187
|
+
...(body !== undefined && { body: JSON.stringify(body) }),
|
|
188
|
+
signal: AbortSignal.timeout(10_000),
|
|
189
|
+
});
|
|
190
|
+
if (response.status === 401 && attempt === 0) {
|
|
191
|
+
this.#access = undefined;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (response.status === 429) {
|
|
195
|
+
throw new RateLimited(Number(response.headers.get("retry-after") ?? 5) * 1000);
|
|
196
|
+
}
|
|
197
|
+
const text = await response.text();
|
|
198
|
+
let answer: unknown;
|
|
199
|
+
try {
|
|
200
|
+
answer = text ? JSON.parse(text) : undefined;
|
|
201
|
+
} catch {
|
|
202
|
+
// Player commands may answer with plain text.
|
|
203
|
+
answer = undefined;
|
|
204
|
+
}
|
|
205
|
+
if (!response.ok) {
|
|
206
|
+
const error = (answer as { error?: { message?: string; reason?: string } })?.error;
|
|
207
|
+
// Signed in before sdeck asked for this permission.
|
|
208
|
+
if (response.status === 403 && /scope/i.test(error?.message ?? "")) {
|
|
209
|
+
throw new Error("Sign in to Spotify again to allow this (sdeck asks for more now)");
|
|
210
|
+
}
|
|
211
|
+
throw new Error(
|
|
212
|
+
REASONS[error?.reason ?? ""] ?? error?.message ?? `Spotify answered ${response.status}`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return answer;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async #accessToken(): Promise<string> {
|
|
220
|
+
if (this.#access && Date.now() < this.#access.expires) return this.#access.token;
|
|
221
|
+
const refresh = this.#options.tokens.get();
|
|
222
|
+
if (!refresh) throw new SignedOut();
|
|
223
|
+
// One refresh at a time: Spotify may replace the refresh token with each use.
|
|
224
|
+
this.#refreshing ??= this.#token({
|
|
225
|
+
grant_type: "refresh_token",
|
|
226
|
+
refresh_token: refresh,
|
|
227
|
+
}).finally(() => {
|
|
228
|
+
this.#refreshing = undefined;
|
|
229
|
+
});
|
|
230
|
+
return this.#refreshing;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async #token(fields: Record<string, string>): Promise<string> {
|
|
234
|
+
const response = await this.#fetch(new URL("/api/token", this.#endpoints.accounts), {
|
|
235
|
+
method: "POST",
|
|
236
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
237
|
+
body: new URLSearchParams({ ...fields, client_id: this.#options.clientId() }),
|
|
238
|
+
signal: AbortSignal.timeout(10_000),
|
|
239
|
+
});
|
|
240
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
241
|
+
access_token?: string;
|
|
242
|
+
refresh_token?: string;
|
|
243
|
+
expires_in?: number;
|
|
244
|
+
error?: string;
|
|
245
|
+
error_description?: string;
|
|
246
|
+
};
|
|
247
|
+
if (!response.ok || !body.access_token) {
|
|
248
|
+
if (body.error === "invalid_grant") {
|
|
249
|
+
await this.signOut();
|
|
250
|
+
throw new SignedOut("The Spotify sign-in expired: sign in again");
|
|
251
|
+
}
|
|
252
|
+
throw new Error(body.error_description ?? body.error ?? "Spotify gave no token");
|
|
253
|
+
}
|
|
254
|
+
if (body.refresh_token) await this.#options.tokens.set(body.refresh_token);
|
|
255
|
+
// A minute early, so a token never expires mid-request.
|
|
256
|
+
const lifetime = Math.max(0, (body.expires_in ?? 3600) - 60);
|
|
257
|
+
this.#access = { token: body.access_token, expires: Date.now() + lifetime * 1000 };
|
|
258
|
+
return body.access_token;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export interface Player {
|
|
263
|
+
playing: boolean;
|
|
264
|
+
/** The track or episode's `spotify:` URI, `""` when nothing is playing. */
|
|
265
|
+
uri: string;
|
|
266
|
+
track: string;
|
|
267
|
+
artist: string;
|
|
268
|
+
album: string;
|
|
269
|
+
/** Cover art URL (about 300 px), `""` when there is none. */
|
|
270
|
+
art: string;
|
|
271
|
+
/** 0–100 through the track. */
|
|
272
|
+
progress: number;
|
|
273
|
+
positionMs: number;
|
|
274
|
+
durationMs: number;
|
|
275
|
+
volume: number | undefined;
|
|
276
|
+
shuffle: boolean;
|
|
277
|
+
repeat: "off" | "track" | "context";
|
|
278
|
+
device: string;
|
|
279
|
+
deviceId: string;
|
|
280
|
+
/** The playlist, album or artist being played, `""` when there is none. */
|
|
281
|
+
context: string;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export const IDLE: Player = {
|
|
285
|
+
playing: false,
|
|
286
|
+
uri: "",
|
|
287
|
+
track: "",
|
|
288
|
+
artist: "",
|
|
289
|
+
album: "",
|
|
290
|
+
art: "",
|
|
291
|
+
progress: 0,
|
|
292
|
+
positionMs: 0,
|
|
293
|
+
durationMs: 0,
|
|
294
|
+
volume: undefined,
|
|
295
|
+
shuffle: false,
|
|
296
|
+
repeat: "off",
|
|
297
|
+
device: "",
|
|
298
|
+
deviceId: "",
|
|
299
|
+
context: "",
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
/** Reads the answer of `GET /me/player` (empty when nothing is playing anywhere). */
|
|
303
|
+
export function parsePlayer(body: unknown): Player {
|
|
304
|
+
if (typeof body !== "object" || body === null) return IDLE;
|
|
305
|
+
const raw = body as {
|
|
306
|
+
is_playing?: boolean;
|
|
307
|
+
progress_ms?: number;
|
|
308
|
+
shuffle_state?: boolean;
|
|
309
|
+
repeat_state?: string;
|
|
310
|
+
device?: { id?: string | null; name?: string; volume_percent?: number | null };
|
|
311
|
+
context?: { uri?: string } | null;
|
|
312
|
+
item?: {
|
|
313
|
+
uri?: string;
|
|
314
|
+
name?: string;
|
|
315
|
+
duration_ms?: number;
|
|
316
|
+
artists?: { name: string }[];
|
|
317
|
+
show?: { name?: string };
|
|
318
|
+
album?: { name?: string; images?: { url: string; width?: number }[] };
|
|
319
|
+
images?: { url: string; width?: number }[];
|
|
320
|
+
} | null;
|
|
321
|
+
};
|
|
322
|
+
const item = raw.item ?? undefined;
|
|
323
|
+
const images = item?.album?.images ?? item?.images ?? [];
|
|
324
|
+
const art =
|
|
325
|
+
[...images].sort((a, b) => Math.abs((a.width ?? 0) - 300) - Math.abs((b.width ?? 0) - 300))[0]
|
|
326
|
+
?.url ?? "";
|
|
327
|
+
const duration = item?.duration_ms ?? 0;
|
|
328
|
+
const position = raw.progress_ms ?? 0;
|
|
329
|
+
return {
|
|
330
|
+
playing: raw.is_playing === true,
|
|
331
|
+
uri: item?.uri ?? "",
|
|
332
|
+
track: item?.name ?? "",
|
|
333
|
+
artist: item?.artists?.map((a) => a.name).join(", ") ?? item?.show?.name ?? "",
|
|
334
|
+
album: item?.album?.name ?? "",
|
|
335
|
+
art,
|
|
336
|
+
progress: duration > 0 ? Math.round((100 * position) / duration) : 0,
|
|
337
|
+
positionMs: position,
|
|
338
|
+
durationMs: duration,
|
|
339
|
+
volume: raw.device?.volume_percent ?? undefined,
|
|
340
|
+
shuffle: raw.shuffle_state === true,
|
|
341
|
+
repeat:
|
|
342
|
+
raw.repeat_state === "track" || raw.repeat_state === "context" ? raw.repeat_state : "off",
|
|
343
|
+
device: raw.device?.name ?? "",
|
|
344
|
+
deviceId: raw.device?.id ?? "",
|
|
345
|
+
context: raw.context?.uri ?? "",
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const KINDS = ["track", "episode", "album", "playlist", "artist", "show"] as const;
|
|
350
|
+
export type ItemKind = (typeof KINDS)[number];
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The `spotify:` URI in a URI or an open.spotify.com link (`…/intl-de/track/<id>?si=…`), or
|
|
354
|
+
* undefined if it is neither.
|
|
355
|
+
*/
|
|
356
|
+
export function spotifyUri(text: string): { uri: string; kind: ItemKind } | undefined {
|
|
357
|
+
const trimmed = text.trim();
|
|
358
|
+
const fromUri = /^spotify:([a-z]+):([A-Za-z0-9]+)$/.exec(trimmed);
|
|
359
|
+
const fromLink =
|
|
360
|
+
/^https?:\/\/open\.spotify\.com\/(?:intl-[a-z-]+\/)?([a-z]+)\/([A-Za-z0-9]+)(?:[/?#].*)?$/i.exec(
|
|
361
|
+
trimmed,
|
|
362
|
+
);
|
|
363
|
+
const [, kind, id] = fromUri ?? fromLink ?? [];
|
|
364
|
+
if (!kind || !id || !KINDS.includes(kind as ItemKind)) return undefined;
|
|
365
|
+
return { uri: `spotify:${kind}:${id}`, kind: kind as ItemKind };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** What `PUT /me/player/play` needs to play a URI: one item, or a list to play through. */
|
|
369
|
+
export function playBody(uri: string, kind: ItemKind): Record<string, unknown> {
|
|
370
|
+
return kind === "track" || kind === "episode" ? { uris: [uri] } : { context_uri: uri };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export interface Playlist {
|
|
374
|
+
id: string;
|
|
375
|
+
uri: string;
|
|
376
|
+
name: string;
|
|
377
|
+
/** The user may add to it: theirs, or one they collaborate on. */
|
|
378
|
+
writable: boolean;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Reads a page of `GET /me/playlists`; `me` is the user's id. */
|
|
382
|
+
export function parsePlaylists(body: unknown, me: string): Playlist[] {
|
|
383
|
+
const items = (body as { items?: unknown[] } | undefined)?.items ?? [];
|
|
384
|
+
return items.flatMap((item) => {
|
|
385
|
+
const p = item as {
|
|
386
|
+
id?: string;
|
|
387
|
+
uri?: string;
|
|
388
|
+
name?: string;
|
|
389
|
+
collaborative?: boolean;
|
|
390
|
+
owner?: { id?: string };
|
|
391
|
+
} | null;
|
|
392
|
+
if (!p?.id || !p.uri) return [];
|
|
393
|
+
return [
|
|
394
|
+
{
|
|
395
|
+
id: p.id,
|
|
396
|
+
uri: p.uri,
|
|
397
|
+
name: p.name || "Untitled playlist",
|
|
398
|
+
writable: p.owner?.id === me || p.collaborative === true,
|
|
399
|
+
},
|
|
400
|
+
];
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export interface Device {
|
|
405
|
+
id: string;
|
|
406
|
+
name: string;
|
|
407
|
+
type: string;
|
|
408
|
+
active: boolean;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Reads `GET /me/player/devices`, leaving out devices that can't be controlled. */
|
|
412
|
+
export function parseDevices(body: unknown): Device[] {
|
|
413
|
+
const devices = (body as { devices?: unknown[] } | undefined)?.devices ?? [];
|
|
414
|
+
return devices.flatMap((item) => {
|
|
415
|
+
const d = item as {
|
|
416
|
+
id?: string | null;
|
|
417
|
+
name?: string;
|
|
418
|
+
type?: string;
|
|
419
|
+
is_active?: boolean;
|
|
420
|
+
is_restricted?: boolean;
|
|
421
|
+
} | null;
|
|
422
|
+
if (!d?.id || d.is_restricted) return [];
|
|
423
|
+
return [{ id: d.id, name: d.name ?? d.id, type: d.type ?? "", active: d.is_active === true }];
|
|
424
|
+
});
|
|
425
|
+
}
|