@sdeck/plugin-spotify 0.0.0-stage → 0.2.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 +1316 -0
- package/dist/index.js.map +12 -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 +873 -0
- package/src/panels.tsx +261 -0
- package/README.md +0 -3
package/src/index.tsx
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defineAction,
|
|
3
|
+
definePlugin,
|
|
4
|
+
defineTrigger,
|
|
5
|
+
type PluginContext,
|
|
6
|
+
type SelectOption,
|
|
7
|
+
Shared,
|
|
8
|
+
type StateDef,
|
|
9
|
+
useKeyPress,
|
|
10
|
+
useSensorPress,
|
|
11
|
+
} from "@sdeck/plugin";
|
|
12
|
+
import {
|
|
13
|
+
type ImageLayer,
|
|
14
|
+
iconLayer,
|
|
15
|
+
iconLook,
|
|
16
|
+
type Layer,
|
|
17
|
+
type Look,
|
|
18
|
+
textLayer,
|
|
19
|
+
} from "@sdeck/schema";
|
|
20
|
+
import {
|
|
21
|
+
type Method,
|
|
22
|
+
type Player,
|
|
23
|
+
type Playlist,
|
|
24
|
+
parseDevices,
|
|
25
|
+
parsePlayer,
|
|
26
|
+
parsePlaylists,
|
|
27
|
+
playBody,
|
|
28
|
+
RateLimited,
|
|
29
|
+
SignedOut,
|
|
30
|
+
type SignIn,
|
|
31
|
+
SpotifyClient,
|
|
32
|
+
spotifyUri,
|
|
33
|
+
} from "./api.ts";
|
|
34
|
+
|
|
35
|
+
import { BACKGROUND, disc, FAINT, GREEN, MUTED, NowPlaying } from "./panels.tsx";
|
|
36
|
+
|
|
37
|
+
export * from "./api.ts";
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_PORT = 43821;
|
|
40
|
+
const POLL_MS = 3000;
|
|
41
|
+
|
|
42
|
+
let context: PluginContext | undefined;
|
|
43
|
+
let signingIn: SignIn | undefined;
|
|
44
|
+
|
|
45
|
+
const spotify = new SpotifyClient({
|
|
46
|
+
clientId: () => String(context?.settings().clientId ?? "").trim(),
|
|
47
|
+
tokens: {
|
|
48
|
+
get: () => context?.secrets.get("refreshToken"),
|
|
49
|
+
set: async (token) => {
|
|
50
|
+
await context?.secrets.set("refreshToken", token);
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
/** Asks the poller to read again now (after a command changed something). */
|
|
56
|
+
let pollNow: () => void = () => {};
|
|
57
|
+
|
|
58
|
+
/** The player, read every few seconds while something shows it. */
|
|
59
|
+
const player = new Shared<Player | undefined>((emit) => {
|
|
60
|
+
let stopped = false;
|
|
61
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
62
|
+
let running = false;
|
|
63
|
+
const tick = async () => {
|
|
64
|
+
if (running || stopped) return;
|
|
65
|
+
running = true;
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
let wait = POLL_MS;
|
|
68
|
+
try {
|
|
69
|
+
const next = parsePlayer(await spotify.request("GET", "/me/player"));
|
|
70
|
+
if (!stopped) emit(next);
|
|
71
|
+
context?.status("Signed in to Spotify", "ok");
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (!stopped) emit(undefined);
|
|
74
|
+
if (error instanceof RateLimited) wait = error.retryAfterMs;
|
|
75
|
+
else if (error instanceof SignedOut) wait = 10_000;
|
|
76
|
+
context?.status((error as Error).message, error instanceof SignedOut ? "info" : "error");
|
|
77
|
+
}
|
|
78
|
+
running = false;
|
|
79
|
+
if (!stopped) timer = setTimeout(tick, wait);
|
|
80
|
+
};
|
|
81
|
+
pollNow = () => {
|
|
82
|
+
// Spotify needs a moment before it reports the change.
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
timer = setTimeout(tick, 400);
|
|
85
|
+
};
|
|
86
|
+
void tick();
|
|
87
|
+
return () => {
|
|
88
|
+
stopped = true;
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
pollNow = () => {};
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const readPlayer = async () => parsePlayer(await spotify.request("GET", "/me/player"));
|
|
95
|
+
|
|
96
|
+
async function command(
|
|
97
|
+
method: Method,
|
|
98
|
+
path: string,
|
|
99
|
+
query?: Record<string, string>,
|
|
100
|
+
body?: unknown,
|
|
101
|
+
) {
|
|
102
|
+
await spotify.request(method, path, query, body);
|
|
103
|
+
pollNow();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The track or episode playing now; fails when nothing is. */
|
|
107
|
+
async function current(): Promise<Player> {
|
|
108
|
+
const now = await readPlayer();
|
|
109
|
+
if (!now.uri) throw new Error("nothing is playing");
|
|
110
|
+
return now;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const isLiked = async (uri: string) =>
|
|
114
|
+
((await spotify.request("GET", "/me/library/contains", { uris: uri })) as boolean[])[0] === true;
|
|
115
|
+
|
|
116
|
+
/** Tells the liked state what a command just did. */
|
|
117
|
+
let likedNow: (uri: string, liked: boolean) => void = () => {};
|
|
118
|
+
|
|
119
|
+
/** Whether what is playing is in Liked Songs: checked when the track changes, and every 30 s. */
|
|
120
|
+
const liked = new Shared<boolean | undefined>((emit) => {
|
|
121
|
+
let uri = "";
|
|
122
|
+
let checkedAt = 0;
|
|
123
|
+
let stopped = false;
|
|
124
|
+
const off = player.listen((p) => {
|
|
125
|
+
const next = p?.uri ?? "";
|
|
126
|
+
if (next === uri && Date.now() - checkedAt < 30_000) return;
|
|
127
|
+
uri = next;
|
|
128
|
+
checkedAt = Date.now();
|
|
129
|
+
if (!next) return emit(undefined);
|
|
130
|
+
isLiked(next).then(
|
|
131
|
+
(value) => !stopped && uri === next && emit(value),
|
|
132
|
+
() => !stopped && uri === next && emit(undefined),
|
|
133
|
+
);
|
|
134
|
+
});
|
|
135
|
+
likedNow = (track, value) => {
|
|
136
|
+
if (track !== uri) return;
|
|
137
|
+
checkedAt = Date.now();
|
|
138
|
+
emit(value);
|
|
139
|
+
};
|
|
140
|
+
return () => {
|
|
141
|
+
stopped = true;
|
|
142
|
+
off();
|
|
143
|
+
likedNow = () => {};
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const setLiked = async (uri: string, value: boolean) => {
|
|
148
|
+
await spotify.request(value ? "PUT" : "DELETE", "/me/library", { uris: uri });
|
|
149
|
+
likedNow(uri, value);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
let me: Promise<string> | undefined;
|
|
153
|
+
/** The signed-in user's id. */
|
|
154
|
+
function userId(): Promise<string> {
|
|
155
|
+
me ??= spotify.request("GET", "/me").then((body) => {
|
|
156
|
+
const id = (body as { id?: string } | undefined)?.id;
|
|
157
|
+
if (!id) throw new Error("Spotify did not say who is signed in");
|
|
158
|
+
return id;
|
|
159
|
+
});
|
|
160
|
+
me.catch(() => {
|
|
161
|
+
me = undefined;
|
|
162
|
+
});
|
|
163
|
+
return me;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The user's playlists (the first 200). */
|
|
167
|
+
async function playlists(): Promise<Playlist[]> {
|
|
168
|
+
const id = await userId();
|
|
169
|
+
const all: Playlist[] = [];
|
|
170
|
+
for (let offset = 0; offset < 200; offset += 50) {
|
|
171
|
+
const page = await spotify.request("GET", "/me/playlists", {
|
|
172
|
+
limit: "50",
|
|
173
|
+
offset: String(offset),
|
|
174
|
+
});
|
|
175
|
+
const found = parsePlaylists(page, id);
|
|
176
|
+
all.push(...found);
|
|
177
|
+
if (!(page as { next?: string | null } | undefined)?.next) break;
|
|
178
|
+
}
|
|
179
|
+
return all;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const key = (icon: string, caption = "", color = "#ffffff"): Look =>
|
|
183
|
+
iconLook({ icon, caption, background: BACKGROUND, color });
|
|
184
|
+
|
|
185
|
+
/** A small dot under the icon while `active` holds, as Spotify marks shuffle and repeat. */
|
|
186
|
+
const dot = (active: string) =>
|
|
187
|
+
iconLayer("dot", disc(GREEN), { size: 7, position: "bottom", visible: active });
|
|
188
|
+
|
|
189
|
+
/** One icon while `active` holds and another (or the same, greyed) while it does not. */
|
|
190
|
+
const switched = (
|
|
191
|
+
active: string,
|
|
192
|
+
on: string,
|
|
193
|
+
off: string,
|
|
194
|
+
colors: { on: string; off: string },
|
|
195
|
+
): ImageLayer[] => [
|
|
196
|
+
iconLayer("on", on, { color: colors.on, size: 58, visible: active }),
|
|
197
|
+
iconLayer("off", off, { color: colors.off, size: 58, visible: `!(${active})` }),
|
|
198
|
+
];
|
|
199
|
+
|
|
200
|
+
// -- Actions ------------------------------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
const setPlaying = (play: boolean) => command("PUT", play ? "/me/player/play" : "/me/player/pause");
|
|
203
|
+
|
|
204
|
+
const playPause = defineAction({
|
|
205
|
+
id: "play-pause",
|
|
206
|
+
name: "Play / pause",
|
|
207
|
+
description: "Shows the cover of what is playing; pressing it plays or pauses.",
|
|
208
|
+
category: "Spotify",
|
|
209
|
+
icon: "play",
|
|
210
|
+
slots: ["key", "sensor"],
|
|
211
|
+
settings: {
|
|
212
|
+
cover: { type: "boolean", label: "Show the cover art", default: true, appearance: true },
|
|
213
|
+
},
|
|
214
|
+
run: async () => {
|
|
215
|
+
const before = (await readPlayer()).playing;
|
|
216
|
+
await setPlaying(!before);
|
|
217
|
+
return { label: before ? "Pause" : "Play", undo: () => setPlaying(before) };
|
|
218
|
+
},
|
|
219
|
+
look: (s): Look => {
|
|
220
|
+
// The button shows what pressing it does: Spotify's green disc with a black symbol.
|
|
221
|
+
const centered = (size: number) => {
|
|
222
|
+
const at = (100 - size) / 2;
|
|
223
|
+
return { x: at, y: at, width: size, height: size };
|
|
224
|
+
};
|
|
225
|
+
const button = (visible: string): ImageLayer[] => [
|
|
226
|
+
iconLayer("disc", disc(GREEN), { frame: centered(70), visible }),
|
|
227
|
+
iconLayer("pause", "tb/TbPlayerPauseFilled", {
|
|
228
|
+
color: "#000000",
|
|
229
|
+
frame: centered(34),
|
|
230
|
+
visible: `(${visible}) && spotify.playing`,
|
|
231
|
+
}),
|
|
232
|
+
iconLayer("play", "tb/TbPlayerPlayFilled", {
|
|
233
|
+
color: "#000000",
|
|
234
|
+
frame: { ...centered(34), x: 35 },
|
|
235
|
+
visible: `(${visible}) && !spotify.playing`,
|
|
236
|
+
}),
|
|
237
|
+
];
|
|
238
|
+
if (!s.cover) return { background: BACKGROUND, layers: button("true") };
|
|
239
|
+
return {
|
|
240
|
+
background: BACKGROUND,
|
|
241
|
+
layers: [
|
|
242
|
+
iconLayer("cover", "{{spotify.art}}", { frame: centered(100), visible: "spotify.art" }),
|
|
243
|
+
// Over a cover, a paused track gets a play button; playing shows just the art.
|
|
244
|
+
iconLayer("shade", disc("#000000", 0.6), {
|
|
245
|
+
frame: centered(48),
|
|
246
|
+
visible: "spotify.art && !spotify.playing",
|
|
247
|
+
}),
|
|
248
|
+
iconLayer("resume", "tb/TbPlayerPlayFilled", {
|
|
249
|
+
frame: { ...centered(24), x: 39 },
|
|
250
|
+
visible: "spotify.art && !spotify.playing",
|
|
251
|
+
}),
|
|
252
|
+
...button("!spotify.art"),
|
|
253
|
+
],
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
const skip = (id: "next" | "previous", name: string, icon: string, back: "next" | "previous") =>
|
|
259
|
+
defineAction({
|
|
260
|
+
id,
|
|
261
|
+
name,
|
|
262
|
+
category: "Spotify",
|
|
263
|
+
icon,
|
|
264
|
+
slots: ["key", "sensor"],
|
|
265
|
+
run: async () => {
|
|
266
|
+
await command("POST", `/me/player/${id}`);
|
|
267
|
+
return { label: name, undo: () => command("POST", `/me/player/${back}`) };
|
|
268
|
+
},
|
|
269
|
+
look: () => key(id === "next" ? "tb/TbPlayerSkipForwardFilled" : "tb/TbPlayerSkipBackFilled"),
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
const next = skip("next", "Next track", "skip-forward", "previous");
|
|
273
|
+
const previous = skip("previous", "Previous track", "skip-back", "next");
|
|
274
|
+
|
|
275
|
+
const nowPlaying = defineAction({
|
|
276
|
+
id: "now-playing",
|
|
277
|
+
name: "Now playing",
|
|
278
|
+
description: "The current track and artist, with how far through it is.",
|
|
279
|
+
category: "Spotify",
|
|
280
|
+
icon: "music",
|
|
281
|
+
slots: ["window", "key", "sensor"],
|
|
282
|
+
settings: {
|
|
283
|
+
press: {
|
|
284
|
+
type: "select",
|
|
285
|
+
label: "When pressed",
|
|
286
|
+
default: "play-pause",
|
|
287
|
+
options: [
|
|
288
|
+
{ value: "play-pause", label: "Play or pause" },
|
|
289
|
+
{ value: "next", label: "Next track" },
|
|
290
|
+
{ value: "like", label: "Like or unlike" },
|
|
291
|
+
{ value: "none", label: "Nothing" },
|
|
292
|
+
],
|
|
293
|
+
},
|
|
294
|
+
},
|
|
295
|
+
display: true,
|
|
296
|
+
run: async () => ({ result: await readPlayer() }),
|
|
297
|
+
component: ({ settings, slot, plugin }) => {
|
|
298
|
+
const act = () => {
|
|
299
|
+
const press = settings.press;
|
|
300
|
+
if (press === "none") return;
|
|
301
|
+
const done =
|
|
302
|
+
press === "next"
|
|
303
|
+
? command("POST", "/me/player/next")
|
|
304
|
+
: press === "like"
|
|
305
|
+
? current().then(async ({ uri }) => setLiked(uri, !(await isLiked(uri))))
|
|
306
|
+
: readPlayer().then((p) => setPlaying(!p.playing));
|
|
307
|
+
done.catch((error: Error) => plugin.log("now playing:", error.message));
|
|
308
|
+
};
|
|
309
|
+
// Each hook listens only in its own kind of slot.
|
|
310
|
+
useKeyPress(slot.kind === "key" ? act : undefined, {
|
|
311
|
+
key: slot.kind === "key" ? slot.index : -1,
|
|
312
|
+
});
|
|
313
|
+
useSensorPress(slot.kind === "sensor" ? act : undefined, {
|
|
314
|
+
sensor: slot.kind === "sensor" ? slot.index : -1,
|
|
315
|
+
});
|
|
316
|
+
return <NowPlaying kind={slot.kind} />;
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
/** The level to go back to after muting. */
|
|
321
|
+
let unmuted = 50;
|
|
322
|
+
|
|
323
|
+
const volume = defineAction({
|
|
324
|
+
id: "volume",
|
|
325
|
+
name: "Spotify volume",
|
|
326
|
+
category: "Spotify",
|
|
327
|
+
icon: "volume-1",
|
|
328
|
+
slots: ["key", "sensor"],
|
|
329
|
+
settings: {
|
|
330
|
+
operation: {
|
|
331
|
+
type: "select",
|
|
332
|
+
label: "When pressed",
|
|
333
|
+
default: "up",
|
|
334
|
+
options: [
|
|
335
|
+
{ value: "up", label: "Volume up" },
|
|
336
|
+
{ value: "down", label: "Volume down" },
|
|
337
|
+
{ value: "set", label: "Set a level" },
|
|
338
|
+
{ value: "mute", label: "Mute / unmute" },
|
|
339
|
+
],
|
|
340
|
+
},
|
|
341
|
+
step: {
|
|
342
|
+
type: "number",
|
|
343
|
+
label: "Step (%)",
|
|
344
|
+
default: 10,
|
|
345
|
+
min: 1,
|
|
346
|
+
max: 50,
|
|
347
|
+
visibleIf: { operation: ["up", "down"] },
|
|
348
|
+
},
|
|
349
|
+
level: {
|
|
350
|
+
type: "number",
|
|
351
|
+
label: "Level (%)",
|
|
352
|
+
default: 50,
|
|
353
|
+
min: 0,
|
|
354
|
+
max: 100,
|
|
355
|
+
visibleIf: { operation: "set" },
|
|
356
|
+
},
|
|
357
|
+
},
|
|
358
|
+
run: async ({ settings }) => {
|
|
359
|
+
const before = (await readPlayer()).volume;
|
|
360
|
+
if (before === undefined) throw new Error("this device does not report its volume");
|
|
361
|
+
const { operation, step } = settings;
|
|
362
|
+
if (operation === "mute" && before > 0) unmuted = before;
|
|
363
|
+
const wanted =
|
|
364
|
+
operation === "mute"
|
|
365
|
+
? before > 0
|
|
366
|
+
? 0
|
|
367
|
+
: unmuted
|
|
368
|
+
: operation === "set"
|
|
369
|
+
? settings.level
|
|
370
|
+
: before + (operation === "up" ? step : -step);
|
|
371
|
+
const level = Math.min(100, Math.max(0, Math.round(wanted)));
|
|
372
|
+
const set = (value: number) =>
|
|
373
|
+
command("PUT", "/me/player/volume", { volume_percent: String(value) });
|
|
374
|
+
await set(level);
|
|
375
|
+
return { result: level, label: `Spotify volume ${level}%`, undo: () => set(before) };
|
|
376
|
+
},
|
|
377
|
+
look: (s): Look => {
|
|
378
|
+
const icon =
|
|
379
|
+
s.operation === "mute"
|
|
380
|
+
? "lucide/volume-x"
|
|
381
|
+
: s.operation === "down"
|
|
382
|
+
? "lucide/volume-1"
|
|
383
|
+
: "lucide/volume-2";
|
|
384
|
+
const level: Layer = {
|
|
385
|
+
id: "level",
|
|
386
|
+
type: "bar",
|
|
387
|
+
value: "spotify.volume ?? 0",
|
|
388
|
+
color: GREEN,
|
|
389
|
+
track: FAINT,
|
|
390
|
+
position: "bottom",
|
|
391
|
+
thickness: 6,
|
|
392
|
+
};
|
|
393
|
+
if (s.operation === "mute") {
|
|
394
|
+
return {
|
|
395
|
+
background: BACKGROUND,
|
|
396
|
+
layers: [
|
|
397
|
+
...switched("spotify.volume == 0", icon, "lucide/volume-2", {
|
|
398
|
+
on: "#f87171",
|
|
399
|
+
off: "#ffffff",
|
|
400
|
+
}),
|
|
401
|
+
level,
|
|
402
|
+
],
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
// Louder and quieter tell themselves apart by their icon; a set level names it.
|
|
406
|
+
return {
|
|
407
|
+
background: BACKGROUND,
|
|
408
|
+
layers: [
|
|
409
|
+
iconLayer("icon", icon, {
|
|
410
|
+
color: "#ffffff",
|
|
411
|
+
size: s.operation === "set" ? 42 : 52,
|
|
412
|
+
position: s.operation === "set" ? "top" : "middle",
|
|
413
|
+
}),
|
|
414
|
+
...(s.operation === "set"
|
|
415
|
+
? [textLayer("label", `${s.level}%`, { color: MUTED, size: 14, position: "bottom" })]
|
|
416
|
+
: []),
|
|
417
|
+
level,
|
|
418
|
+
],
|
|
419
|
+
};
|
|
420
|
+
},
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
const shuffle = defineAction({
|
|
424
|
+
id: "shuffle",
|
|
425
|
+
name: "Shuffle",
|
|
426
|
+
category: "Spotify",
|
|
427
|
+
icon: "shuffle",
|
|
428
|
+
slots: ["key", "sensor"],
|
|
429
|
+
run: async () => {
|
|
430
|
+
const before = (await readPlayer()).shuffle;
|
|
431
|
+
const set = (state: boolean) => command("PUT", "/me/player/shuffle", { state: String(state) });
|
|
432
|
+
await set(!before);
|
|
433
|
+
return { result: !before, label: `Shuffle ${before ? "off" : "on"}`, undo: () => set(before) };
|
|
434
|
+
},
|
|
435
|
+
look: () => ({
|
|
436
|
+
background: BACKGROUND,
|
|
437
|
+
layers: [
|
|
438
|
+
...switched("spotify.shuffle", "lucide/shuffle", "lucide/shuffle", {
|
|
439
|
+
on: GREEN,
|
|
440
|
+
off: MUTED,
|
|
441
|
+
}),
|
|
442
|
+
dot("spotify.shuffle"),
|
|
443
|
+
],
|
|
444
|
+
}),
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
/** The repeat mode after `mode`, in the order Spotify's own button uses. */
|
|
448
|
+
export function nextRepeat(mode: Player["repeat"]): Player["repeat"] {
|
|
449
|
+
return mode === "off" ? "context" : mode === "context" ? "track" : "off";
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const repeat = defineAction({
|
|
453
|
+
id: "repeat",
|
|
454
|
+
name: "Repeat",
|
|
455
|
+
description: "Cycles repeat: off, the playlist, one track.",
|
|
456
|
+
category: "Spotify",
|
|
457
|
+
icon: "repeat",
|
|
458
|
+
slots: ["key", "sensor"],
|
|
459
|
+
run: async () => {
|
|
460
|
+
const before = (await readPlayer()).repeat;
|
|
461
|
+
const state = nextRepeat(before);
|
|
462
|
+
const set = (value: string) => command("PUT", "/me/player/repeat", { state: value });
|
|
463
|
+
await set(state);
|
|
464
|
+
return { result: state, label: `Repeat ${state}`, undo: () => set(before) };
|
|
465
|
+
},
|
|
466
|
+
look: () => ({
|
|
467
|
+
background: BACKGROUND,
|
|
468
|
+
layers: [
|
|
469
|
+
iconLayer("off", "lucide/repeat", {
|
|
470
|
+
color: MUTED,
|
|
471
|
+
size: 58,
|
|
472
|
+
visible: 'spotify.repeat != "context" && spotify.repeat != "track"',
|
|
473
|
+
}),
|
|
474
|
+
iconLayer("all", "lucide/repeat", {
|
|
475
|
+
color: GREEN,
|
|
476
|
+
size: 58,
|
|
477
|
+
visible: 'spotify.repeat == "context"',
|
|
478
|
+
}),
|
|
479
|
+
iconLayer("one", "lucide/repeat-1", {
|
|
480
|
+
color: GREEN,
|
|
481
|
+
size: 58,
|
|
482
|
+
visible: 'spotify.repeat == "track"',
|
|
483
|
+
}),
|
|
484
|
+
dot('spotify.repeat == "context" || spotify.repeat == "track"'),
|
|
485
|
+
],
|
|
486
|
+
}),
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
const like = defineAction({
|
|
490
|
+
id: "like",
|
|
491
|
+
name: "Like",
|
|
492
|
+
description: "Adds what is playing to Liked Songs, or takes it out. Lit while it is liked.",
|
|
493
|
+
category: "Spotify",
|
|
494
|
+
icon: "heart",
|
|
495
|
+
slots: ["key", "sensor"],
|
|
496
|
+
settings: {
|
|
497
|
+
mode: {
|
|
498
|
+
type: "select",
|
|
499
|
+
label: "When pressed",
|
|
500
|
+
default: "toggle",
|
|
501
|
+
options: [
|
|
502
|
+
{ value: "toggle", label: "Like / unlike" },
|
|
503
|
+
{ value: "like", label: "Like" },
|
|
504
|
+
{ value: "unlike", label: "Unlike" },
|
|
505
|
+
],
|
|
506
|
+
},
|
|
507
|
+
},
|
|
508
|
+
run: async ({ settings }) => {
|
|
509
|
+
const { uri, track } = await current();
|
|
510
|
+
const before = await isLiked(uri);
|
|
511
|
+
const after = settings.mode === "toggle" ? !before : settings.mode === "like";
|
|
512
|
+
if (after !== before) await setLiked(uri, after);
|
|
513
|
+
return {
|
|
514
|
+
result: after,
|
|
515
|
+
label: `${after ? "Liked" : "Unliked"} ${track}`,
|
|
516
|
+
...(after !== before && { undo: () => setLiked(uri, before) }),
|
|
517
|
+
};
|
|
518
|
+
},
|
|
519
|
+
look: () => ({
|
|
520
|
+
background: BACKGROUND,
|
|
521
|
+
layers: switched("spotify.liked == true", "tb/TbHeartFilled", "tb/TbHeart", {
|
|
522
|
+
on: GREEN,
|
|
523
|
+
off: MUTED,
|
|
524
|
+
}),
|
|
525
|
+
}),
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
const addToPlaylist = defineAction({
|
|
529
|
+
id: "add-to-playlist",
|
|
530
|
+
name: "Add to playlist",
|
|
531
|
+
description: "Adds what is playing to one of your playlists.",
|
|
532
|
+
category: "Spotify",
|
|
533
|
+
icon: "list-plus",
|
|
534
|
+
slots: ["key", "sensor"],
|
|
535
|
+
settings: {
|
|
536
|
+
playlist: {
|
|
537
|
+
type: "select",
|
|
538
|
+
label: "Playlist",
|
|
539
|
+
options: [],
|
|
540
|
+
source: "playlists",
|
|
541
|
+
description: "Yours, and ones you collaborate on.",
|
|
542
|
+
},
|
|
543
|
+
text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
|
|
544
|
+
},
|
|
545
|
+
run: async ({ settings }) => {
|
|
546
|
+
if (!settings.playlist) throw new Error("Pick a playlist in the key's settings");
|
|
547
|
+
const { uri, track } = await current();
|
|
548
|
+
await spotify.request(
|
|
549
|
+
"POST",
|
|
550
|
+
`/playlists/${encodeURIComponent(settings.playlist)}/items`,
|
|
551
|
+
{},
|
|
552
|
+
{
|
|
553
|
+
uris: [uri],
|
|
554
|
+
},
|
|
555
|
+
);
|
|
556
|
+
// Not undoable: taking it out again would also remove copies that were there before.
|
|
557
|
+
return { label: `Added ${track} to a playlist` };
|
|
558
|
+
},
|
|
559
|
+
look: (s) => key("lucide/list-plus", s.text),
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
const play = defineAction({
|
|
563
|
+
id: "play",
|
|
564
|
+
name: "Play",
|
|
565
|
+
description: "Plays a playlist, album, artist, track or episode, or adds it to the queue.",
|
|
566
|
+
category: "Spotify",
|
|
567
|
+
icon: "list-music",
|
|
568
|
+
slots: ["key", "sensor"],
|
|
569
|
+
settings: {
|
|
570
|
+
item: {
|
|
571
|
+
type: "text",
|
|
572
|
+
label: "What to play",
|
|
573
|
+
source: "library",
|
|
574
|
+
placeholder: "A Spotify link, or pick a playlist",
|
|
575
|
+
description: "In Spotify: Share → Copy link.",
|
|
576
|
+
},
|
|
577
|
+
mode: {
|
|
578
|
+
type: "select",
|
|
579
|
+
label: "When pressed",
|
|
580
|
+
default: "play",
|
|
581
|
+
options: [
|
|
582
|
+
{ value: "play", label: "Play now" },
|
|
583
|
+
{ value: "queue", label: "Add to the queue (tracks and episodes)" },
|
|
584
|
+
],
|
|
585
|
+
},
|
|
586
|
+
shuffle: {
|
|
587
|
+
type: "boolean",
|
|
588
|
+
label: "Shuffle",
|
|
589
|
+
default: false,
|
|
590
|
+
visibleIf: { mode: "play" },
|
|
591
|
+
},
|
|
592
|
+
text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
|
|
593
|
+
},
|
|
594
|
+
run: async ({ settings }) => {
|
|
595
|
+
const target = spotifyUri(settings.item);
|
|
596
|
+
if (!target) throw new Error("set what to play: a Spotify link or spotify: URI");
|
|
597
|
+
if (settings.mode === "queue") {
|
|
598
|
+
if (target.kind !== "track" && target.kind !== "episode") {
|
|
599
|
+
throw new Error("only tracks and episodes can be queued");
|
|
600
|
+
}
|
|
601
|
+
await command("POST", "/me/player/queue", { uri: target.uri });
|
|
602
|
+
return { label: "Added to the queue" };
|
|
603
|
+
}
|
|
604
|
+
await command("PUT", "/me/player/play", {}, playBody(target.uri, target.kind));
|
|
605
|
+
if (settings.shuffle) await command("PUT", "/me/player/shuffle", { state: "true" });
|
|
606
|
+
return { label: `Play ${target.kind}` };
|
|
607
|
+
},
|
|
608
|
+
look: (s) => key(s.mode === "queue" ? "lucide/list-end" : "lucide/list-music", s.text),
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
const seek = defineAction({
|
|
612
|
+
id: "seek",
|
|
613
|
+
name: "Seek",
|
|
614
|
+
description: "Jumps forward or back in the track.",
|
|
615
|
+
category: "Spotify",
|
|
616
|
+
icon: "fast-forward",
|
|
617
|
+
slots: ["key", "sensor"],
|
|
618
|
+
settings: {
|
|
619
|
+
direction: {
|
|
620
|
+
type: "select",
|
|
621
|
+
label: "Direction",
|
|
622
|
+
default: "forward",
|
|
623
|
+
options: [
|
|
624
|
+
{ value: "forward", label: "Forward" },
|
|
625
|
+
{ value: "back", label: "Back" },
|
|
626
|
+
{ value: "start", label: "To the start" },
|
|
627
|
+
],
|
|
628
|
+
},
|
|
629
|
+
seconds: {
|
|
630
|
+
type: "number",
|
|
631
|
+
label: "Seconds",
|
|
632
|
+
default: 15,
|
|
633
|
+
min: 1,
|
|
634
|
+
max: 600,
|
|
635
|
+
visibleIf: { direction: ["forward", "back"] },
|
|
636
|
+
},
|
|
637
|
+
},
|
|
638
|
+
run: async ({ settings }) => {
|
|
639
|
+
const { positionMs, durationMs } = await current();
|
|
640
|
+
const jump = settings.seconds * 1000;
|
|
641
|
+
const wanted =
|
|
642
|
+
settings.direction === "start"
|
|
643
|
+
? 0
|
|
644
|
+
: positionMs + (settings.direction === "forward" ? jump : -jump);
|
|
645
|
+
const to = Math.round(Math.min(Math.max(0, durationMs - 1000), Math.max(0, wanted)));
|
|
646
|
+
const go = (ms: number) => command("PUT", "/me/player/seek", { position_ms: String(ms) });
|
|
647
|
+
await go(to);
|
|
648
|
+
return { label: `Seek to ${Math.round(to / 1000)} s`, undo: () => go(positionMs) };
|
|
649
|
+
},
|
|
650
|
+
look: (s) =>
|
|
651
|
+
key(
|
|
652
|
+
s.direction === "start"
|
|
653
|
+
? "lucide/undo-2"
|
|
654
|
+
: s.direction === "forward"
|
|
655
|
+
? "lucide/fast-forward"
|
|
656
|
+
: "lucide/rewind",
|
|
657
|
+
s.direction === "start" ? "" : `${s.direction === "forward" ? "+" : "−"}${s.seconds}s`,
|
|
658
|
+
),
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
const transfer = (id: string) => command("PUT", "/me/player", {}, { device_ids: [id], play: true });
|
|
662
|
+
|
|
663
|
+
const device = defineAction({
|
|
664
|
+
id: "device",
|
|
665
|
+
name: "Play on a device",
|
|
666
|
+
description: "Moves playback to another speaker, phone or computer.",
|
|
667
|
+
category: "Spotify",
|
|
668
|
+
icon: "speaker",
|
|
669
|
+
slots: ["key", "sensor"],
|
|
670
|
+
settings: {
|
|
671
|
+
device: {
|
|
672
|
+
type: "select",
|
|
673
|
+
label: "Device",
|
|
674
|
+
options: [],
|
|
675
|
+
source: "devices",
|
|
676
|
+
description: "Only devices with Spotify open are listed.",
|
|
677
|
+
},
|
|
678
|
+
text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
|
|
679
|
+
},
|
|
680
|
+
run: async ({ settings }) => {
|
|
681
|
+
if (!settings.device) throw new Error("Pick a device in the key's settings");
|
|
682
|
+
const before = (await readPlayer()).deviceId;
|
|
683
|
+
await transfer(settings.device);
|
|
684
|
+
return {
|
|
685
|
+
label: "Moved playback",
|
|
686
|
+
...(before && before !== settings.device && { undo: () => transfer(before) }),
|
|
687
|
+
};
|
|
688
|
+
},
|
|
689
|
+
look: (s) => key("lucide/speaker", s.text),
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
// -- Triggers -----------------------------------------------------------------------------------
|
|
693
|
+
|
|
694
|
+
const trackChanged = defineTrigger({
|
|
695
|
+
id: "track-changed",
|
|
696
|
+
name: "When the track changes",
|
|
697
|
+
description: "Fires with the new track whenever something else starts playing.",
|
|
698
|
+
subscribe: ({ fire }) => {
|
|
699
|
+
let uri: string | undefined;
|
|
700
|
+
return player.listen((p) => {
|
|
701
|
+
const next = p?.uri ?? "";
|
|
702
|
+
// The first reading is where things stand, not a change.
|
|
703
|
+
if (uri !== undefined && next && next !== uri) fire(p);
|
|
704
|
+
if (p) uri = next;
|
|
705
|
+
});
|
|
706
|
+
},
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
// -- Plugin -------------------------------------------------------------------------------------
|
|
710
|
+
|
|
711
|
+
const stateOf = (id: keyof Player, name: string, type: StateDef["type"]): StateDef => ({
|
|
712
|
+
id,
|
|
713
|
+
name,
|
|
714
|
+
type,
|
|
715
|
+
start: (set) => player.listen((p) => set(p?.[id])),
|
|
716
|
+
});
|
|
717
|
+
|
|
718
|
+
const playlistOptions = async (writable: boolean): Promise<SelectOption[]> =>
|
|
719
|
+
(await playlists())
|
|
720
|
+
.filter((p) => !writable || p.writable)
|
|
721
|
+
.map((p) => ({ value: writable ? p.id : p.uri, label: p.name }));
|
|
722
|
+
|
|
723
|
+
export default definePlugin({
|
|
724
|
+
id: "@sdeck/plugin-spotify",
|
|
725
|
+
name: "Spotify",
|
|
726
|
+
version: "0.2.0",
|
|
727
|
+
namespace: "spotify",
|
|
728
|
+
description:
|
|
729
|
+
"Now playing, playback, Liked Songs, playlists and devices through the Spotify Web API.",
|
|
730
|
+
author: "sdeck",
|
|
731
|
+
permissions: ["network"],
|
|
732
|
+
settings: {
|
|
733
|
+
clientId: {
|
|
734
|
+
type: "text",
|
|
735
|
+
label: "Client ID",
|
|
736
|
+
description:
|
|
737
|
+
"Create an app at developer.spotify.com and add the redirect URI http://127.0.0.1:43821/callback (with your port).",
|
|
738
|
+
},
|
|
739
|
+
port: {
|
|
740
|
+
type: "number",
|
|
741
|
+
label: "Sign-in port",
|
|
742
|
+
default: DEFAULT_PORT,
|
|
743
|
+
min: 1024,
|
|
744
|
+
max: 65535,
|
|
745
|
+
},
|
|
746
|
+
},
|
|
747
|
+
onboarding: {
|
|
748
|
+
intro: "Spotify lets apps in only with an app of your own. It takes a minute.",
|
|
749
|
+
steps: [
|
|
750
|
+
{
|
|
751
|
+
id: "app",
|
|
752
|
+
title: "Create a Spotify app",
|
|
753
|
+
body: "Open the Spotify developer dashboard, sign in and press **Create app**. Give it any name, add the redirect URI `http://127.0.0.1:43821/callback`, tick **Web API**, and save.\n\nThen copy the app's **Client ID** here.",
|
|
754
|
+
link: {
|
|
755
|
+
label: "Spotify developer dashboard",
|
|
756
|
+
url: "https://developer.spotify.com/dashboard",
|
|
757
|
+
},
|
|
758
|
+
settings: ["clientId"],
|
|
759
|
+
},
|
|
760
|
+
{
|
|
761
|
+
id: "sign-in",
|
|
762
|
+
title: "Sign in",
|
|
763
|
+
body: "Allow sdeck in the browser that opens. Controlling playback needs Spotify Premium.",
|
|
764
|
+
command: "sign-in",
|
|
765
|
+
done: (activated) => activated.secrets.get("refreshToken") !== undefined,
|
|
766
|
+
},
|
|
767
|
+
],
|
|
768
|
+
starterPage: {
|
|
769
|
+
name: "Spotify",
|
|
770
|
+
keys: {
|
|
771
|
+
0: { action: "previous" },
|
|
772
|
+
1: { action: "play-pause" },
|
|
773
|
+
2: { action: "next" },
|
|
774
|
+
3: { action: "like" },
|
|
775
|
+
4: { action: "volume", settings: { operation: "down" } },
|
|
776
|
+
5: { action: "volume", settings: { operation: "up" } },
|
|
777
|
+
6: { action: "shuffle" },
|
|
778
|
+
7: { action: "repeat" },
|
|
779
|
+
},
|
|
780
|
+
window: { action: "now-playing" },
|
|
781
|
+
},
|
|
782
|
+
},
|
|
783
|
+
commands: [
|
|
784
|
+
{
|
|
785
|
+
id: "sign-in",
|
|
786
|
+
name: "Sign in",
|
|
787
|
+
description: "Opens Spotify in your browser to allow access.",
|
|
788
|
+
run: (activated) => {
|
|
789
|
+
signingIn?.cancel();
|
|
790
|
+
signingIn = spotify.signIn(Number(activated.settings().port));
|
|
791
|
+
activated.status("Waiting for you to allow access in the browser", "info");
|
|
792
|
+
signingIn.done.then(
|
|
793
|
+
() => {
|
|
794
|
+
activated.status("Signed in to Spotify", "ok");
|
|
795
|
+
// Perhaps as someone else.
|
|
796
|
+
me = undefined;
|
|
797
|
+
pollNow();
|
|
798
|
+
},
|
|
799
|
+
(error: Error) => activated.status(error.message, "error"),
|
|
800
|
+
);
|
|
801
|
+
return signingIn.url;
|
|
802
|
+
},
|
|
803
|
+
},
|
|
804
|
+
{
|
|
805
|
+
id: "sign-out",
|
|
806
|
+
name: "Sign out",
|
|
807
|
+
run: async (activated) => {
|
|
808
|
+
signingIn?.cancel();
|
|
809
|
+
await spotify.signOut();
|
|
810
|
+
me = undefined;
|
|
811
|
+
activated.status("Signed out", "info");
|
|
812
|
+
pollNow();
|
|
813
|
+
},
|
|
814
|
+
},
|
|
815
|
+
],
|
|
816
|
+
actions: [
|
|
817
|
+
playPause,
|
|
818
|
+
next,
|
|
819
|
+
previous,
|
|
820
|
+
nowPlaying,
|
|
821
|
+
like,
|
|
822
|
+
addToPlaylist,
|
|
823
|
+
play,
|
|
824
|
+
seek,
|
|
825
|
+
volume,
|
|
826
|
+
shuffle,
|
|
827
|
+
repeat,
|
|
828
|
+
device,
|
|
829
|
+
],
|
|
830
|
+
triggers: [trackChanged],
|
|
831
|
+
optionSources: {
|
|
832
|
+
playlists: () => playlistOptions(true),
|
|
833
|
+
library: () => playlistOptions(false),
|
|
834
|
+
devices: async () =>
|
|
835
|
+
parseDevices(await spotify.request("GET", "/me/player/devices")).map((d) => ({
|
|
836
|
+
value: d.id,
|
|
837
|
+
label: `${d.name}${d.active ? " (playing)" : ""}`,
|
|
838
|
+
})),
|
|
839
|
+
},
|
|
840
|
+
state: [
|
|
841
|
+
stateOf("playing", "Playing", "boolean"),
|
|
842
|
+
stateOf("track", "Track", "string"),
|
|
843
|
+
stateOf("artist", "Artist", "string"),
|
|
844
|
+
stateOf("album", "Album", "string"),
|
|
845
|
+
stateOf("art", "Cover art", "string"),
|
|
846
|
+
stateOf("progress", "Progress", "number"),
|
|
847
|
+
stateOf("volume", "Volume", "number"),
|
|
848
|
+
stateOf("shuffle", "Shuffle", "boolean"),
|
|
849
|
+
stateOf("repeat", "Repeat", "string"),
|
|
850
|
+
stateOf("device", "Device", "string"),
|
|
851
|
+
stateOf("uri", "Track URI", "string"),
|
|
852
|
+
{
|
|
853
|
+
id: "liked",
|
|
854
|
+
name: "Liked",
|
|
855
|
+
type: "boolean",
|
|
856
|
+
description: "Whether what is playing is in Liked Songs.",
|
|
857
|
+
start: (set) => liked.listen(set),
|
|
858
|
+
},
|
|
859
|
+
],
|
|
860
|
+
activate(activated) {
|
|
861
|
+
context = activated;
|
|
862
|
+
activated.status(
|
|
863
|
+
activated.secrets.get("refreshToken")
|
|
864
|
+
? "Signed in to Spotify"
|
|
865
|
+
: "Set your client id, then sign in",
|
|
866
|
+
"info",
|
|
867
|
+
);
|
|
868
|
+
return () => {
|
|
869
|
+
signingIn?.cancel();
|
|
870
|
+
context = undefined;
|
|
871
|
+
};
|
|
872
|
+
},
|
|
873
|
+
});
|