@sdeck/plugin-spotify 0.3.0 → 0.4.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/src/index.tsx CHANGED
@@ -1,22 +1,24 @@
1
1
  import {
2
- defineAction,
3
- definePlugin,
4
- defineTrigger,
5
- type PluginContext,
2
+ createPlugin,
3
+ following,
4
+ Permissions,
6
5
  type SelectOption,
7
6
  Shared,
8
- type StateDef,
9
- useKeyPress,
10
- useSensorPress,
7
+ setting,
8
+ usePress,
11
9
  } from "@sdeck/plugin";
12
10
  import {
11
+ captionLayer,
13
12
  type ImageLayer,
14
13
  iconLayer,
15
14
  iconLook,
16
- type Layer,
15
+ iconSize,
17
16
  type Look,
18
- textLayer,
17
+ meterLayer,
18
+ surface,
19
+ volumeStepLayers,
19
20
  } from "@sdeck/schema";
21
+ import { z } from "zod";
20
22
  import {
21
23
  type Method,
22
24
  type Player,
@@ -31,23 +33,45 @@ import {
31
33
  SpotifyClient,
32
34
  spotifyUri,
33
35
  } from "./api.ts";
34
-
35
- import { BACKGROUND, disc, FAINT, GREEN, MUTED, NowPlaying } from "./panels.tsx";
36
+ import { BACKGROUND, disc, GREEN, MUTED, NowPlaying } from "./panels.tsx";
36
37
 
37
38
  export * from "./api.ts";
38
39
 
39
40
  export const DEFAULT_PORT = 43821;
41
+
42
+ const plugin = createPlugin({
43
+ id: "@sdeck/plugin-spotify",
44
+ name: "Spotify",
45
+ version: "0.4.0",
46
+ namespace: "spotify",
47
+ description:
48
+ "Now playing, playback, Liked Songs, playlists and devices through the Spotify Web API.",
49
+ author: "sdeck",
50
+ permissions: [Permissions.network],
51
+ settings: {
52
+ clientId: setting.text("Client ID", {
53
+ required: true,
54
+ validate: z
55
+ .string()
56
+ .trim()
57
+ .regex(/^[0-9a-f]{32}$/i, "should be 32 letters and digits, from your app's settings"),
58
+ description:
59
+ "Create an app at developer.spotify.com and add the redirect URI http://127.0.0.1:43821/callback (with your port).",
60
+ }),
61
+ port: setting.number("Sign-in port", { default: DEFAULT_PORT, min: 1024, max: 65535 }),
62
+ },
63
+ });
64
+
40
65
  const POLL_MS = 3000;
41
66
 
42
- let context: PluginContext | undefined;
43
67
  let signingIn: SignIn | undefined;
44
68
 
45
69
  const spotify = new SpotifyClient({
46
- clientId: () => String(context?.settings().clientId ?? "").trim(),
70
+ clientId: () => plugin.context?.settings().clientId.trim() ?? "",
47
71
  tokens: {
48
- get: () => context?.secrets.get("refreshToken"),
72
+ get: () => plugin.context?.secrets.get("refreshToken"),
49
73
  set: async (token) => {
50
- await context?.secrets.set("refreshToken", token);
74
+ await plugin.context?.secrets.set("refreshToken", token);
51
75
  },
52
76
  },
53
77
  });
@@ -74,12 +98,15 @@ const player = new Shared<Player | undefined>((emit) => {
74
98
  // Look again right after the track ends, rather than up to a whole wait later.
75
99
  const left = next.durationMs - next.positionMs;
76
100
  if (next.playing && left > 0) wait = Math.min(wait, left + 400);
77
- context?.status("Signed in to Spotify", "ok");
101
+ plugin.context?.status("Signed in to Spotify", "ok");
78
102
  } catch (error) {
79
103
  if (!stopped) emit(undefined);
80
104
  if (error instanceof RateLimited) wait = error.retryAfterMs;
81
105
  else if (error instanceof SignedOut) wait = 10_000;
82
- context?.status((error as Error).message, error instanceof SignedOut ? "info" : "error");
106
+ plugin.context?.status(
107
+ (error as Error).message,
108
+ error instanceof SignedOut ? "info" : "error",
109
+ );
83
110
  }
84
111
  running = false;
85
112
  if (!stopped) timer = setTimeout(tick, wait);
@@ -185,6 +212,103 @@ async function playlists(): Promise<Playlist[]> {
185
212
  return all;
186
213
  }
187
214
 
215
+ const playlistOptions = async (writable: boolean): Promise<SelectOption[]> =>
216
+ (await playlists())
217
+ .filter((p) => !writable || p.writable)
218
+ .map((p) => ({ value: writable ? p.id : p.uri, label: p.name }));
219
+
220
+ const sources = {
221
+ playlists: plugin.source("playlists", () => playlistOptions(true)),
222
+ library: plugin.source("library", () => playlistOptions(false)),
223
+ devices: plugin.source("devices", async () =>
224
+ parseDevices(await spotify.request("GET", "/me/player/devices")).map((d) => ({
225
+ value: d.id,
226
+ label: `${d.name}${d.active ? " (playing)" : ""}`,
227
+ })),
228
+ ),
229
+ };
230
+
231
+ // -- Live values --------------------------------------------------------------------------------
232
+
233
+ const from = <T,>(pick: (p: Player) => T | undefined) => ({ start: following(player, pick) });
234
+
235
+ const values = {
236
+ playing: plugin.state.boolean(
237
+ "playing",
238
+ "Playing",
239
+ from((p) => p.playing),
240
+ ),
241
+ track: plugin.state.string(
242
+ "track",
243
+ "Track",
244
+ from((p) => p.track),
245
+ ),
246
+ artist: plugin.state.string(
247
+ "artist",
248
+ "Artist",
249
+ from((p) => p.artist),
250
+ ),
251
+ album: plugin.state.string(
252
+ "album",
253
+ "Album",
254
+ from((p) => p.album),
255
+ ),
256
+ art: plugin.state.string(
257
+ "art",
258
+ "Cover art",
259
+ from((p) => p.art),
260
+ ),
261
+ progress: plugin.state.number(
262
+ "progress",
263
+ "Progress",
264
+ from((p) => p.progress),
265
+ ),
266
+ position: plugin.state.number("position", "Position", {
267
+ unit: "s",
268
+ ...from((p) => p.position),
269
+ }),
270
+ duration: plugin.state.number("duration", "Duration", {
271
+ unit: "s",
272
+ ...from((p) => p.duration),
273
+ }),
274
+ startedAt: plugin.state.number("startedAt", "Started at", {
275
+ description:
276
+ "When the track would have started to be where it is now, in ms since 1970. Only while playing: now() - spotify.startedAt is the exact position.",
277
+ ...from((p) => p.startedAt),
278
+ }),
279
+ volume: plugin.state.number(
280
+ "volume",
281
+ "Volume",
282
+ from((p) => p.volume),
283
+ ),
284
+ shuffle: plugin.state.boolean(
285
+ "shuffle",
286
+ "Shuffle",
287
+ from((p) => p.shuffle),
288
+ ),
289
+ repeat: plugin.state.string(
290
+ "repeat",
291
+ "Repeat",
292
+ from((p) => p.repeat),
293
+ ),
294
+ device: plugin.state.string(
295
+ "device",
296
+ "Device",
297
+ from((p) => p.device),
298
+ ),
299
+ uri: plugin.state.string(
300
+ "uri",
301
+ "Track URI",
302
+ from((p) => p.uri),
303
+ ),
304
+ liked: plugin.state.boolean("liked", "Liked", {
305
+ description: "Whether what is playing is in Liked Songs.",
306
+ start: following(liked, (is) => is),
307
+ }),
308
+ };
309
+
310
+ // -- Looks --------------------------------------------------------------------------------------
311
+
188
312
  const key = (icon: string, caption = "", color = "#ffffff"): Look =>
189
313
  iconLook({ icon, caption, background: BACKGROUND, color });
190
314
 
@@ -199,15 +323,15 @@ const switched = (
199
323
  off: string,
200
324
  colors: { on: string; off: string },
201
325
  ): ImageLayer[] => [
202
- iconLayer("on", on, { color: colors.on, size: 58, visible: active }),
203
- iconLayer("off", off, { color: colors.off, size: 58, visible: `!(${active})` }),
326
+ iconLayer("on", on, { color: colors.on, size: iconSize(false), visible: active }),
327
+ iconLayer("off", off, { color: colors.off, size: iconSize(false), visible: `!(${active})` }),
204
328
  ];
205
329
 
206
330
  // -- Actions ------------------------------------------------------------------------------------
207
331
 
208
332
  const setPlaying = (play: boolean) => command("PUT", play ? "/me/player/play" : "/me/player/pause");
209
333
 
210
- const playPause = defineAction({
334
+ const playPause = plugin.action({
211
335
  id: "play-pause",
212
336
  name: "Play / pause",
213
337
  description: "Shows the cover of what is playing; pressing it plays or pauses.",
@@ -215,7 +339,7 @@ const playPause = defineAction({
215
339
  icon: "play",
216
340
  slots: ["key", "sensor"],
217
341
  settings: {
218
- cover: { type: "boolean", label: "Show the cover art", default: true, appearance: true },
342
+ cover: setting.boolean("Show the cover art", { default: true, appearance: true }),
219
343
  },
220
344
  run: async () => {
221
345
  const before = (await readPlayer()).playing;
@@ -233,36 +357,39 @@ const playPause = defineAction({
233
357
  iconLayer("pause", "tb/TbPlayerPauseFilled", {
234
358
  color: "#000000",
235
359
  frame: centered(34),
236
- visible: `(${visible}) && spotify.playing`,
360
+ visible: `(${visible}) && ${values.playing.key}`,
237
361
  }),
238
362
  iconLayer("play", "tb/TbPlayerPlayFilled", {
239
363
  color: "#000000",
240
364
  frame: { ...centered(34), x: 35 },
241
- visible: `(${visible}) && !spotify.playing`,
365
+ visible: `(${visible}) && !${values.playing.key}`,
242
366
  }),
243
367
  ];
244
- if (!s.cover) return { background: BACKGROUND, layers: button("true") };
368
+ if (!s.cover) return { background: surface(BACKGROUND), layers: button("true") };
245
369
  return {
246
- background: BACKGROUND,
370
+ background: surface(BACKGROUND),
247
371
  layers: [
248
- iconLayer("cover", "{{spotify.art}}", { frame: centered(100), visible: "spotify.art" }),
372
+ iconLayer("cover", values.art.template, {
373
+ frame: centered(100),
374
+ visible: values.art.key,
375
+ }),
249
376
  // Over a cover, a paused track gets a play button; playing shows just the art.
250
377
  iconLayer("shade", disc("#000000", 0.6), {
251
378
  frame: centered(48),
252
- visible: "spotify.art && !spotify.playing",
379
+ visible: `${values.art.key} && !${values.playing.key}`,
253
380
  }),
254
381
  iconLayer("resume", "tb/TbPlayerPlayFilled", {
255
382
  frame: { ...centered(24), x: 39 },
256
- visible: "spotify.art && !spotify.playing",
383
+ visible: `${values.art.key} && !${values.playing.key}`,
257
384
  }),
258
- ...button("!spotify.art"),
385
+ ...button(`!${values.art.key}`),
259
386
  ],
260
387
  };
261
388
  },
262
389
  });
263
390
 
264
391
  const skip = (id: "next" | "previous", name: string, icon: string, back: "next" | "previous") =>
265
- defineAction({
392
+ plugin.action({
266
393
  id,
267
394
  name,
268
395
  category: "Spotify",
@@ -278,7 +405,7 @@ const skip = (id: "next" | "previous", name: string, icon: string, back: "next"
278
405
  const next = skip("next", "Next track", "skip-forward", "previous");
279
406
  const previous = skip("previous", "Previous track", "skip-back", "next");
280
407
 
281
- const nowPlaying = defineAction({
408
+ const nowPlaying = plugin.action({
282
409
  id: "now-playing",
283
410
  name: "Now playing",
284
411
  description: "The current track and artist, with how far through it is.",
@@ -286,17 +413,12 @@ const nowPlaying = defineAction({
286
413
  icon: "music",
287
414
  slots: ["window", "key", "sensor"],
288
415
  settings: {
289
- press: {
290
- type: "select",
291
- label: "When pressed",
292
- default: "play-pause",
293
- options: [
294
- { value: "play-pause", label: "Play or pause" },
295
- { value: "next", label: "Next track" },
296
- { value: "like", label: "Like or unlike" },
297
- { value: "none", label: "Nothing" },
298
- ],
299
- },
416
+ press: setting.select("When pressed", {
417
+ "play-pause": "Play or pause",
418
+ next: "Next track",
419
+ like: "Like or unlike",
420
+ none: "Nothing",
421
+ }),
300
422
  },
301
423
  display: true,
302
424
  run: async () => ({ result: await readPlayer() }),
@@ -312,13 +434,7 @@ const nowPlaying = defineAction({
312
434
  : readPlayer().then((p) => setPlaying(!p.playing));
313
435
  done.catch((error: Error) => plugin.log("now playing:", error.message));
314
436
  };
315
- // Each hook listens only in its own kind of slot.
316
- useKeyPress(slot.kind === "key" ? act : undefined, {
317
- key: slot.kind === "key" ? slot.index : -1,
318
- });
319
- useSensorPress(slot.kind === "sensor" ? act : undefined, {
320
- sensor: slot.kind === "sensor" ? slot.index : -1,
321
- });
437
+ usePress(act);
322
438
  return <NowPlaying kind={slot.kind} />;
323
439
  },
324
440
  });
@@ -326,40 +442,31 @@ const nowPlaying = defineAction({
326
442
  /** The level to go back to after muting. */
327
443
  let unmuted = 50;
328
444
 
329
- const volume = defineAction({
445
+ const volume = plugin.action({
330
446
  id: "volume",
331
447
  name: "Spotify volume",
332
448
  category: "Spotify",
333
449
  icon: "volume-1",
334
450
  slots: ["key", "sensor"],
335
451
  settings: {
336
- operation: {
337
- type: "select",
338
- label: "When pressed",
339
- default: "up",
340
- options: [
341
- { value: "up", label: "Volume up" },
342
- { value: "down", label: "Volume down" },
343
- { value: "set", label: "Set a level" },
344
- { value: "mute", label: "Mute / unmute" },
345
- ],
346
- },
347
- step: {
348
- type: "number",
349
- label: "Step (%)",
452
+ operation: setting.select("When pressed", {
453
+ up: "Volume up",
454
+ down: "Volume down",
455
+ set: "Set a level",
456
+ mute: "Mute / unmute",
457
+ }),
458
+ step: setting.number("Step (%)", {
350
459
  default: 10,
351
460
  min: 1,
352
461
  max: 50,
353
462
  visibleIf: { operation: ["up", "down"] },
354
- },
355
- level: {
356
- type: "number",
357
- label: "Level (%)",
463
+ }),
464
+ level: setting.number("Level (%)", {
358
465
  default: 50,
359
466
  min: 0,
360
467
  max: 100,
361
468
  visibleIf: { operation: "set" },
362
- },
469
+ }),
363
470
  },
364
471
  run: async ({ settings }) => {
365
472
  const before = (await readPlayer()).volume;
@@ -380,53 +487,39 @@ const volume = defineAction({
380
487
  await set(level);
381
488
  return { result: level, label: `Spotify volume ${level}%`, undo: () => set(before) };
382
489
  },
383
- look: (s): Look => {
384
- const icon =
385
- s.operation === "mute"
386
- ? "lucide/volume-x"
387
- : s.operation === "down"
388
- ? "lucide/volume-1"
389
- : "lucide/volume-2";
390
- const level: Layer = {
391
- id: "level",
392
- type: "bar",
393
- value: "spotify.volume ?? 0",
394
- color: GREEN,
395
- track: FAINT,
396
- position: "bottom",
397
- thickness: 6,
398
- };
399
- if (s.operation === "mute") {
400
- return {
401
- background: BACKGROUND,
402
- layers: [
403
- ...switched("spotify.volume == 0", icon, "lucide/volume-2", {
404
- on: "#f87171",
405
- off: "#ffffff",
406
- }),
407
- level,
408
- ],
409
- };
490
+ look: (s, slot): Look => {
491
+ const background = surface(BACKGROUND);
492
+ const level = meterLayer("level", `${values.volume.key} ?? 0`, { color: GREEN });
493
+ switch (s.operation) {
494
+ case "mute":
495
+ return {
496
+ background,
497
+ layers: [
498
+ ...switched(`${values.volume.key} == 0`, "lucide/volume-x", "lucide/volume-2", {
499
+ on: "#f87171",
500
+ off: "#ffffff",
501
+ }),
502
+ level,
503
+ ],
504
+ };
505
+ case "set":
506
+ return {
507
+ background,
508
+ layers: [
509
+ iconLayer("icon", "lucide/volume-2", { color: "#ffffff", size: 42 }),
510
+ captionLayer("label", `${s.level}%`, { color: MUTED, size: 14 }),
511
+ level,
512
+ ],
513
+ };
514
+ default: {
515
+ const step = s.operation === "up" ? "plus" : "minus";
516
+ return { background, layers: [...volumeStepLayers(step, slot, { center: 46 }), level] };
517
+ }
410
518
  }
411
- // Louder and quieter tell themselves apart by their icon; a set level names it.
412
- return {
413
- background: BACKGROUND,
414
- layers: [
415
- iconLayer("icon", icon, {
416
- color: "#ffffff",
417
- size: s.operation === "set" ? 42 : 52,
418
- position: s.operation === "set" ? "top" : "middle",
419
- }),
420
- ...(s.operation === "set"
421
- ? [textLayer("label", `${s.level}%`, { color: MUTED, size: 14, position: "bottom" })]
422
- : []),
423
- level,
424
- ],
425
- };
426
519
  },
427
520
  });
428
521
 
429
- const shuffle = defineAction({
522
+ const shuffle = plugin.action({
430
523
  id: "shuffle",
431
524
  name: "Shuffle",
432
525
  category: "Spotify",
@@ -439,13 +532,13 @@ const shuffle = defineAction({
439
532
  return { result: !before, label: `Shuffle ${before ? "off" : "on"}`, undo: () => set(before) };
440
533
  },
441
534
  look: () => ({
442
- background: BACKGROUND,
535
+ background: surface(BACKGROUND),
443
536
  layers: [
444
- ...switched("spotify.shuffle", "lucide/shuffle", "lucide/shuffle", {
537
+ ...switched(values.shuffle.key, "lucide/shuffle", "lucide/shuffle", {
445
538
  on: GREEN,
446
539
  off: MUTED,
447
540
  }),
448
- dot("spotify.shuffle"),
541
+ dot(values.shuffle.key),
449
542
  ],
450
543
  }),
451
544
  });
@@ -455,7 +548,9 @@ export function nextRepeat(mode: Player["repeat"]): Player["repeat"] {
455
548
  return mode === "off" ? "context" : mode === "context" ? "track" : "off";
456
549
  }
457
550
 
458
- const repeat = defineAction({
551
+ const repeating = `${values.repeat.key} == "context" || ${values.repeat.key} == "track"`;
552
+
553
+ const repeat = plugin.action({
459
554
  id: "repeat",
460
555
  name: "Repeat",
461
556
  description: "Cycles repeat: off, the playlist, one track.",
@@ -470,29 +565,29 @@ const repeat = defineAction({
470
565
  return { result: state, label: `Repeat ${state}`, undo: () => set(before) };
471
566
  },
472
567
  look: () => ({
473
- background: BACKGROUND,
568
+ background: surface(BACKGROUND),
474
569
  layers: [
475
570
  iconLayer("off", "lucide/repeat", {
476
571
  color: MUTED,
477
- size: 58,
478
- visible: 'spotify.repeat != "context" && spotify.repeat != "track"',
572
+ size: iconSize(false),
573
+ visible: `!(${repeating})`,
479
574
  }),
480
575
  iconLayer("all", "lucide/repeat", {
481
576
  color: GREEN,
482
- size: 58,
483
- visible: 'spotify.repeat == "context"',
577
+ size: iconSize(false),
578
+ visible: `${values.repeat.key} == "context"`,
484
579
  }),
485
580
  iconLayer("one", "lucide/repeat-1", {
486
581
  color: GREEN,
487
- size: 58,
488
- visible: 'spotify.repeat == "track"',
582
+ size: iconSize(false),
583
+ visible: `${values.repeat.key} == "track"`,
489
584
  }),
490
- dot('spotify.repeat == "context" || spotify.repeat == "track"'),
585
+ dot(repeating),
491
586
  ],
492
587
  }),
493
588
  });
494
589
 
495
- const like = defineAction({
590
+ const like = plugin.action({
496
591
  id: "like",
497
592
  name: "Like",
498
593
  description: "Adds what is playing to Liked Songs, or takes it out. Lit while it is liked.",
@@ -500,16 +595,11 @@ const like = defineAction({
500
595
  icon: "heart",
501
596
  slots: ["key", "sensor"],
502
597
  settings: {
503
- mode: {
504
- type: "select",
505
- label: "When pressed",
506
- default: "toggle",
507
- options: [
508
- { value: "toggle", label: "Like / unlike" },
509
- { value: "like", label: "Like" },
510
- { value: "unlike", label: "Unlike" },
511
- ],
512
- },
598
+ mode: setting.select("When pressed", {
599
+ toggle: "Like / unlike",
600
+ like: "Like",
601
+ unlike: "Unlike",
602
+ }),
513
603
  },
514
604
  run: async ({ settings }) => {
515
605
  const { uri, track } = await current();
@@ -523,15 +613,15 @@ const like = defineAction({
523
613
  };
524
614
  },
525
615
  look: () => ({
526
- background: BACKGROUND,
527
- layers: switched("spotify.liked == true", "tb/TbHeartFilled", "tb/TbHeart", {
616
+ background: surface(BACKGROUND),
617
+ layers: switched(`${values.liked.key} == true`, "tb/TbHeartFilled", "tb/TbHeart", {
528
618
  on: GREEN,
529
619
  off: MUTED,
530
620
  }),
531
621
  }),
532
622
  });
533
623
 
534
- const addToPlaylist = defineAction({
624
+ const addToPlaylist = plugin.action({
535
625
  id: "add-to-playlist",
536
626
  name: "Add to playlist",
537
627
  description: "Adds what is playing to one of your playlists.",
@@ -539,17 +629,13 @@ const addToPlaylist = defineAction({
539
629
  icon: "list-plus",
540
630
  slots: ["key", "sensor"],
541
631
  settings: {
542
- playlist: {
543
- type: "select",
544
- label: "Playlist",
545
- options: [],
546
- source: "playlists",
632
+ playlist: setting.pick("Playlist", sources.playlists, {
633
+ required: true,
547
634
  description: "Yours, and ones you collaborate on.",
548
- },
549
- text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
635
+ }),
636
+ text: setting.text("Text", { placeholder: "Shown under the icon", appearance: true }),
550
637
  },
551
638
  run: async ({ settings }) => {
552
- if (!settings.playlist) throw new Error("Pick a playlist in the key's settings");
553
639
  const { uri, track } = await current();
554
640
  await spotify.request(
555
641
  "POST",
@@ -565,7 +651,7 @@ const addToPlaylist = defineAction({
565
651
  look: (s) => key("lucide/list-plus", s.text),
566
652
  });
567
653
 
568
- const play = defineAction({
654
+ const play = plugin.action({
569
655
  id: "play",
570
656
  name: "Play",
571
657
  description: "Plays a playlist, album, artist, track or episode, or adds it to the queue.",
@@ -573,29 +659,20 @@ const play = defineAction({
573
659
  icon: "list-music",
574
660
  slots: ["key", "sensor"],
575
661
  settings: {
576
- item: {
577
- type: "text",
578
- label: "What to play",
579
- source: "library",
662
+ item: setting.text("What to play", {
663
+ source: sources.library.id,
664
+ required: true,
665
+ validate: (item) =>
666
+ spotifyUri(item) ? undefined : "should be a Spotify link or spotify: URI",
580
667
  placeholder: "A Spotify link, or pick a playlist",
581
668
  description: "In Spotify: Share → Copy link.",
582
- },
583
- mode: {
584
- type: "select",
585
- label: "When pressed",
586
- default: "play",
587
- options: [
588
- { value: "play", label: "Play now" },
589
- { value: "queue", label: "Add to the queue (tracks and episodes)" },
590
- ],
591
- },
592
- shuffle: {
593
- type: "boolean",
594
- label: "Shuffle",
595
- default: false,
596
- visibleIf: { mode: "play" },
597
- },
598
- text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
669
+ }),
670
+ mode: setting.select("When pressed", {
671
+ play: "Play now",
672
+ queue: "Add to the queue (tracks and episodes)",
673
+ }),
674
+ shuffle: setting.boolean("Shuffle", { default: false, visibleIf: { mode: "play" } }),
675
+ text: setting.text("Text", { placeholder: "Shown under the icon", appearance: true }),
599
676
  },
600
677
  run: async ({ settings }) => {
601
678
  const target = spotifyUri(settings.item);
@@ -614,7 +691,7 @@ const play = defineAction({
614
691
  look: (s) => key(s.mode === "queue" ? "lucide/list-end" : "lucide/list-music", s.text),
615
692
  });
616
693
 
617
- const seek = defineAction({
694
+ const seek = plugin.action({
618
695
  id: "seek",
619
696
  name: "Seek",
620
697
  description: "Jumps forward or back in the track.",
@@ -622,24 +699,17 @@ const seek = defineAction({
622
699
  icon: "fast-forward",
623
700
  slots: ["key", "sensor"],
624
701
  settings: {
625
- direction: {
626
- type: "select",
627
- label: "Direction",
628
- default: "forward",
629
- options: [
630
- { value: "forward", label: "Forward" },
631
- { value: "back", label: "Back" },
632
- { value: "start", label: "To the start" },
633
- ],
634
- },
635
- seconds: {
636
- type: "number",
637
- label: "Seconds",
702
+ direction: setting.select("Direction", {
703
+ forward: "Forward",
704
+ back: "Back",
705
+ start: "To the start",
706
+ }),
707
+ seconds: setting.number("Seconds", {
638
708
  default: 15,
639
709
  min: 1,
640
710
  max: 600,
641
711
  visibleIf: { direction: ["forward", "back"] },
642
- },
712
+ }),
643
713
  },
644
714
  run: async ({ settings }) => {
645
715
  const { positionMs, durationMs } = await current();
@@ -666,7 +736,7 @@ const seek = defineAction({
666
736
 
667
737
  const transfer = (id: string) => command("PUT", "/me/player", {}, { device_ids: [id], play: true });
668
738
 
669
- const device = defineAction({
739
+ const device = plugin.action({
670
740
  id: "device",
671
741
  name: "Play on a device",
672
742
  description: "Moves playback to another speaker, phone or computer.",
@@ -674,17 +744,13 @@ const device = defineAction({
674
744
  icon: "speaker",
675
745
  slots: ["key", "sensor"],
676
746
  settings: {
677
- device: {
678
- type: "select",
679
- label: "Device",
680
- options: [],
681
- source: "devices",
747
+ device: setting.pick("Device", sources.devices, {
748
+ required: true,
682
749
  description: "Only devices with Spotify open are listed.",
683
- },
684
- text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true },
750
+ }),
751
+ text: setting.text("Text", { placeholder: "Shown under the icon", appearance: true }),
685
752
  },
686
753
  run: async ({ settings }) => {
687
- if (!settings.device) throw new Error("Pick a device in the key's settings");
688
754
  const before = (await readPlayer()).deviceId;
689
755
  await transfer(settings.device);
690
756
  return {
@@ -697,7 +763,7 @@ const device = defineAction({
697
763
 
698
764
  // -- Triggers -----------------------------------------------------------------------------------
699
765
 
700
- const trackChanged = defineTrigger({
766
+ const trackChanged = plugin.trigger({
701
767
  id: "track-changed",
702
768
  name: "When the track changes",
703
769
  description: "Fires with the new track whenever something else starts playing.",
@@ -714,42 +780,40 @@ const trackChanged = defineTrigger({
714
780
 
715
781
  // -- Plugin -------------------------------------------------------------------------------------
716
782
 
717
- const stateOf = (id: keyof Player, name: string, type: StateDef["type"]): StateDef => ({
718
- id,
719
- name,
720
- type,
721
- start: (set) => player.listen((p) => set(p?.[id])),
783
+ const signIn = plugin.command({
784
+ id: "sign-in",
785
+ name: "Sign in",
786
+ description: "Opens Spotify in your browser to allow access.",
787
+ run: (context) => {
788
+ signingIn?.cancel();
789
+ signingIn = spotify.signIn(context.settings().port);
790
+ context.status("Waiting for you to allow access in the browser", "info");
791
+ signingIn.done.then(
792
+ () => {
793
+ context.status("Signed in to Spotify", "ok");
794
+ // Perhaps as someone else.
795
+ me = undefined;
796
+ pollNow();
797
+ },
798
+ (error: Error) => context.status(error.message, "error"),
799
+ );
800
+ return signingIn.url;
801
+ },
722
802
  });
723
803
 
724
- const playlistOptions = async (writable: boolean): Promise<SelectOption[]> =>
725
- (await playlists())
726
- .filter((p) => !writable || p.writable)
727
- .map((p) => ({ value: writable ? p.id : p.uri, label: p.name }));
728
-
729
- export default definePlugin({
730
- id: "@sdeck/plugin-spotify",
731
- name: "Spotify",
732
- version: "0.3.0",
733
- namespace: "spotify",
734
- description:
735
- "Now playing, playback, Liked Songs, playlists and devices through the Spotify Web API.",
736
- author: "sdeck",
737
- permissions: ["network"],
738
- settings: {
739
- clientId: {
740
- type: "text",
741
- label: "Client ID",
742
- description:
743
- "Create an app at developer.spotify.com and add the redirect URI http://127.0.0.1:43821/callback (with your port).",
744
- },
745
- port: {
746
- type: "number",
747
- label: "Sign-in port",
748
- default: DEFAULT_PORT,
749
- min: 1024,
750
- max: 65535,
751
- },
804
+ const signOut = plugin.command({
805
+ id: "sign-out",
806
+ name: "Sign out",
807
+ run: async (context) => {
808
+ signingIn?.cancel();
809
+ await spotify.signOut();
810
+ me = undefined;
811
+ context.status("Signed out", "info");
812
+ pollNow();
752
813
  },
814
+ });
815
+
816
+ export default plugin.define({
753
817
  onboarding: {
754
818
  intro: "Spotify lets apps in only with an app of your own. It takes a minute.",
755
819
  steps: [
@@ -786,39 +850,7 @@ export default definePlugin({
786
850
  window: { action: "now-playing" },
787
851
  },
788
852
  },
789
- commands: [
790
- {
791
- id: "sign-in",
792
- name: "Sign in",
793
- description: "Opens Spotify in your browser to allow access.",
794
- run: (activated) => {
795
- signingIn?.cancel();
796
- signingIn = spotify.signIn(Number(activated.settings().port));
797
- activated.status("Waiting for you to allow access in the browser", "info");
798
- signingIn.done.then(
799
- () => {
800
- activated.status("Signed in to Spotify", "ok");
801
- // Perhaps as someone else.
802
- me = undefined;
803
- pollNow();
804
- },
805
- (error: Error) => activated.status(error.message, "error"),
806
- );
807
- return signingIn.url;
808
- },
809
- },
810
- {
811
- id: "sign-out",
812
- name: "Sign out",
813
- run: async (activated) => {
814
- signingIn?.cancel();
815
- await spotify.signOut();
816
- me = undefined;
817
- activated.status("Signed out", "info");
818
- pollNow();
819
- },
820
- },
821
- ],
853
+ commands: [signIn, signOut],
822
854
  actions: [
823
855
  playPause,
824
856
  next,
@@ -834,44 +866,9 @@ export default definePlugin({
834
866
  device,
835
867
  ],
836
868
  triggers: [trackChanged],
837
- optionSources: {
838
- playlists: () => playlistOptions(true),
839
- library: () => playlistOptions(false),
840
- devices: async () =>
841
- parseDevices(await spotify.request("GET", "/me/player/devices")).map((d) => ({
842
- value: d.id,
843
- label: `${d.name}${d.active ? " (playing)" : ""}`,
844
- })),
845
- },
846
- state: [
847
- stateOf("playing", "Playing", "boolean"),
848
- stateOf("track", "Track", "string"),
849
- stateOf("artist", "Artist", "string"),
850
- stateOf("album", "Album", "string"),
851
- stateOf("art", "Cover art", "string"),
852
- stateOf("progress", "Progress", "number"),
853
- { ...stateOf("position", "Position", "number"), unit: "s" },
854
- { ...stateOf("duration", "Duration", "number"), unit: "s" },
855
- {
856
- ...stateOf("startedAt", "Started at", "number"),
857
- description:
858
- "When the track would have started to be where it is now, in ms since 1970. Only while playing: now() - spotify.startedAt is the exact position.",
859
- },
860
- stateOf("volume", "Volume", "number"),
861
- stateOf("shuffle", "Shuffle", "boolean"),
862
- stateOf("repeat", "Repeat", "string"),
863
- stateOf("device", "Device", "string"),
864
- stateOf("uri", "Track URI", "string"),
865
- {
866
- id: "liked",
867
- name: "Liked",
868
- type: "boolean",
869
- description: "Whether what is playing is in Liked Songs.",
870
- start: (set) => liked.listen(set),
871
- },
872
- ],
869
+ sources: Object.values(sources),
870
+ state: Object.values(values),
873
871
  activate(activated) {
874
- context = activated;
875
872
  activated.status(
876
873
  activated.secrets.get("refreshToken")
877
874
  ? "Signed in to Spotify"
@@ -880,7 +877,6 @@ export default definePlugin({
880
877
  );
881
878
  return () => {
882
879
  signingIn?.cancel();
883
- context = undefined;
884
880
  };
885
881
  },
886
882
  });