@sdeck/plugin-spotify 0.2.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
  });
@@ -66,14 +90,23 @@ const player = new Shared<Player | undefined>((emit) => {
66
90
  clearTimeout(timer);
67
91
  let wait = POLL_MS;
68
92
  try {
69
- const next = parsePlayer(await spotify.request("GET", "/me/player"));
93
+ const asked = Date.now();
94
+ const body = await spotify.request("GET", "/me/player");
95
+ // Spotify read the position about halfway through the request.
96
+ const next = parsePlayer(body, (asked + Date.now()) / 2);
70
97
  if (!stopped) emit(next);
71
- context?.status("Signed in to Spotify", "ok");
98
+ // Look again right after the track ends, rather than up to a whole wait later.
99
+ const left = next.durationMs - next.positionMs;
100
+ if (next.playing && left > 0) wait = Math.min(wait, left + 400);
101
+ plugin.context?.status("Signed in to Spotify", "ok");
72
102
  } catch (error) {
73
103
  if (!stopped) emit(undefined);
74
104
  if (error instanceof RateLimited) wait = error.retryAfterMs;
75
105
  else if (error instanceof SignedOut) wait = 10_000;
76
- 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
+ );
77
110
  }
78
111
  running = false;
79
112
  if (!stopped) timer = setTimeout(tick, wait);
@@ -179,6 +212,103 @@ async function playlists(): Promise<Playlist[]> {
179
212
  return all;
180
213
  }
181
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
+
182
312
  const key = (icon: string, caption = "", color = "#ffffff"): Look =>
183
313
  iconLook({ icon, caption, background: BACKGROUND, color });
184
314
 
@@ -193,15 +323,15 @@ const switched = (
193
323
  off: string,
194
324
  colors: { on: string; off: string },
195
325
  ): ImageLayer[] => [
196
- iconLayer("on", on, { color: colors.on, size: 58, visible: active }),
197
- 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})` }),
198
328
  ];
199
329
 
200
330
  // -- Actions ------------------------------------------------------------------------------------
201
331
 
202
332
  const setPlaying = (play: boolean) => command("PUT", play ? "/me/player/play" : "/me/player/pause");
203
333
 
204
- const playPause = defineAction({
334
+ const playPause = plugin.action({
205
335
  id: "play-pause",
206
336
  name: "Play / pause",
207
337
  description: "Shows the cover of what is playing; pressing it plays or pauses.",
@@ -209,7 +339,7 @@ const playPause = defineAction({
209
339
  icon: "play",
210
340
  slots: ["key", "sensor"],
211
341
  settings: {
212
- cover: { type: "boolean", label: "Show the cover art", default: true, appearance: true },
342
+ cover: setting.boolean("Show the cover art", { default: true, appearance: true }),
213
343
  },
214
344
  run: async () => {
215
345
  const before = (await readPlayer()).playing;
@@ -227,36 +357,39 @@ const playPause = defineAction({
227
357
  iconLayer("pause", "tb/TbPlayerPauseFilled", {
228
358
  color: "#000000",
229
359
  frame: centered(34),
230
- visible: `(${visible}) && spotify.playing`,
360
+ visible: `(${visible}) && ${values.playing.key}`,
231
361
  }),
232
362
  iconLayer("play", "tb/TbPlayerPlayFilled", {
233
363
  color: "#000000",
234
364
  frame: { ...centered(34), x: 35 },
235
- visible: `(${visible}) && !spotify.playing`,
365
+ visible: `(${visible}) && !${values.playing.key}`,
236
366
  }),
237
367
  ];
238
- if (!s.cover) return { background: BACKGROUND, layers: button("true") };
368
+ if (!s.cover) return { background: surface(BACKGROUND), layers: button("true") };
239
369
  return {
240
- background: BACKGROUND,
370
+ background: surface(BACKGROUND),
241
371
  layers: [
242
- 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
+ }),
243
376
  // Over a cover, a paused track gets a play button; playing shows just the art.
244
377
  iconLayer("shade", disc("#000000", 0.6), {
245
378
  frame: centered(48),
246
- visible: "spotify.art && !spotify.playing",
379
+ visible: `${values.art.key} && !${values.playing.key}`,
247
380
  }),
248
381
  iconLayer("resume", "tb/TbPlayerPlayFilled", {
249
382
  frame: { ...centered(24), x: 39 },
250
- visible: "spotify.art && !spotify.playing",
383
+ visible: `${values.art.key} && !${values.playing.key}`,
251
384
  }),
252
- ...button("!spotify.art"),
385
+ ...button(`!${values.art.key}`),
253
386
  ],
254
387
  };
255
388
  },
256
389
  });
257
390
 
258
391
  const skip = (id: "next" | "previous", name: string, icon: string, back: "next" | "previous") =>
259
- defineAction({
392
+ plugin.action({
260
393
  id,
261
394
  name,
262
395
  category: "Spotify",
@@ -272,7 +405,7 @@ const skip = (id: "next" | "previous", name: string, icon: string, back: "next"
272
405
  const next = skip("next", "Next track", "skip-forward", "previous");
273
406
  const previous = skip("previous", "Previous track", "skip-back", "next");
274
407
 
275
- const nowPlaying = defineAction({
408
+ const nowPlaying = plugin.action({
276
409
  id: "now-playing",
277
410
  name: "Now playing",
278
411
  description: "The current track and artist, with how far through it is.",
@@ -280,17 +413,12 @@ const nowPlaying = defineAction({
280
413
  icon: "music",
281
414
  slots: ["window", "key", "sensor"],
282
415
  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
- },
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
+ }),
294
422
  },
295
423
  display: true,
296
424
  run: async () => ({ result: await readPlayer() }),
@@ -306,13 +434,7 @@ const nowPlaying = defineAction({
306
434
  : readPlayer().then((p) => setPlaying(!p.playing));
307
435
  done.catch((error: Error) => plugin.log("now playing:", error.message));
308
436
  };
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
- });
437
+ usePress(act);
316
438
  return <NowPlaying kind={slot.kind} />;
317
439
  },
318
440
  });
@@ -320,40 +442,31 @@ const nowPlaying = defineAction({
320
442
  /** The level to go back to after muting. */
321
443
  let unmuted = 50;
322
444
 
323
- const volume = defineAction({
445
+ const volume = plugin.action({
324
446
  id: "volume",
325
447
  name: "Spotify volume",
326
448
  category: "Spotify",
327
449
  icon: "volume-1",
328
450
  slots: ["key", "sensor"],
329
451
  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 (%)",
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 (%)", {
344
459
  default: 10,
345
460
  min: 1,
346
461
  max: 50,
347
462
  visibleIf: { operation: ["up", "down"] },
348
- },
349
- level: {
350
- type: "number",
351
- label: "Level (%)",
463
+ }),
464
+ level: setting.number("Level (%)", {
352
465
  default: 50,
353
466
  min: 0,
354
467
  max: 100,
355
468
  visibleIf: { operation: "set" },
356
- },
469
+ }),
357
470
  },
358
471
  run: async ({ settings }) => {
359
472
  const before = (await readPlayer()).volume;
@@ -374,53 +487,39 @@ const volume = defineAction({
374
487
  await set(level);
375
488
  return { result: level, label: `Spotify volume ${level}%`, undo: () => set(before) };
376
489
  },
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
- };
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
+ }
404
518
  }
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
519
  },
421
520
  });
422
521
 
423
- const shuffle = defineAction({
522
+ const shuffle = plugin.action({
424
523
  id: "shuffle",
425
524
  name: "Shuffle",
426
525
  category: "Spotify",
@@ -433,13 +532,13 @@ const shuffle = defineAction({
433
532
  return { result: !before, label: `Shuffle ${before ? "off" : "on"}`, undo: () => set(before) };
434
533
  },
435
534
  look: () => ({
436
- background: BACKGROUND,
535
+ background: surface(BACKGROUND),
437
536
  layers: [
438
- ...switched("spotify.shuffle", "lucide/shuffle", "lucide/shuffle", {
537
+ ...switched(values.shuffle.key, "lucide/shuffle", "lucide/shuffle", {
439
538
  on: GREEN,
440
539
  off: MUTED,
441
540
  }),
442
- dot("spotify.shuffle"),
541
+ dot(values.shuffle.key),
443
542
  ],
444
543
  }),
445
544
  });
@@ -449,7 +548,9 @@ export function nextRepeat(mode: Player["repeat"]): Player["repeat"] {
449
548
  return mode === "off" ? "context" : mode === "context" ? "track" : "off";
450
549
  }
451
550
 
452
- const repeat = defineAction({
551
+ const repeating = `${values.repeat.key} == "context" || ${values.repeat.key} == "track"`;
552
+
553
+ const repeat = plugin.action({
453
554
  id: "repeat",
454
555
  name: "Repeat",
455
556
  description: "Cycles repeat: off, the playlist, one track.",
@@ -464,29 +565,29 @@ const repeat = defineAction({
464
565
  return { result: state, label: `Repeat ${state}`, undo: () => set(before) };
465
566
  },
466
567
  look: () => ({
467
- background: BACKGROUND,
568
+ background: surface(BACKGROUND),
468
569
  layers: [
469
570
  iconLayer("off", "lucide/repeat", {
470
571
  color: MUTED,
471
- size: 58,
472
- visible: 'spotify.repeat != "context" && spotify.repeat != "track"',
572
+ size: iconSize(false),
573
+ visible: `!(${repeating})`,
473
574
  }),
474
575
  iconLayer("all", "lucide/repeat", {
475
576
  color: GREEN,
476
- size: 58,
477
- visible: 'spotify.repeat == "context"',
577
+ size: iconSize(false),
578
+ visible: `${values.repeat.key} == "context"`,
478
579
  }),
479
580
  iconLayer("one", "lucide/repeat-1", {
480
581
  color: GREEN,
481
- size: 58,
482
- visible: 'spotify.repeat == "track"',
582
+ size: iconSize(false),
583
+ visible: `${values.repeat.key} == "track"`,
483
584
  }),
484
- dot('spotify.repeat == "context" || spotify.repeat == "track"'),
585
+ dot(repeating),
485
586
  ],
486
587
  }),
487
588
  });
488
589
 
489
- const like = defineAction({
590
+ const like = plugin.action({
490
591
  id: "like",
491
592
  name: "Like",
492
593
  description: "Adds what is playing to Liked Songs, or takes it out. Lit while it is liked.",
@@ -494,16 +595,11 @@ const like = defineAction({
494
595
  icon: "heart",
495
596
  slots: ["key", "sensor"],
496
597
  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
- },
598
+ mode: setting.select("When pressed", {
599
+ toggle: "Like / unlike",
600
+ like: "Like",
601
+ unlike: "Unlike",
602
+ }),
507
603
  },
508
604
  run: async ({ settings }) => {
509
605
  const { uri, track } = await current();
@@ -517,15 +613,15 @@ const like = defineAction({
517
613
  };
518
614
  },
519
615
  look: () => ({
520
- background: BACKGROUND,
521
- layers: switched("spotify.liked == true", "tb/TbHeartFilled", "tb/TbHeart", {
616
+ background: surface(BACKGROUND),
617
+ layers: switched(`${values.liked.key} == true`, "tb/TbHeartFilled", "tb/TbHeart", {
522
618
  on: GREEN,
523
619
  off: MUTED,
524
620
  }),
525
621
  }),
526
622
  });
527
623
 
528
- const addToPlaylist = defineAction({
624
+ const addToPlaylist = plugin.action({
529
625
  id: "add-to-playlist",
530
626
  name: "Add to playlist",
531
627
  description: "Adds what is playing to one of your playlists.",
@@ -533,17 +629,13 @@ const addToPlaylist = defineAction({
533
629
  icon: "list-plus",
534
630
  slots: ["key", "sensor"],
535
631
  settings: {
536
- playlist: {
537
- type: "select",
538
- label: "Playlist",
539
- options: [],
540
- source: "playlists",
632
+ playlist: setting.pick("Playlist", sources.playlists, {
633
+ required: true,
541
634
  description: "Yours, and ones you collaborate on.",
542
- },
543
- 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 }),
544
637
  },
545
638
  run: async ({ settings }) => {
546
- if (!settings.playlist) throw new Error("Pick a playlist in the key's settings");
547
639
  const { uri, track } = await current();
548
640
  await spotify.request(
549
641
  "POST",
@@ -559,7 +651,7 @@ const addToPlaylist = defineAction({
559
651
  look: (s) => key("lucide/list-plus", s.text),
560
652
  });
561
653
 
562
- const play = defineAction({
654
+ const play = plugin.action({
563
655
  id: "play",
564
656
  name: "Play",
565
657
  description: "Plays a playlist, album, artist, track or episode, or adds it to the queue.",
@@ -567,29 +659,20 @@ const play = defineAction({
567
659
  icon: "list-music",
568
660
  slots: ["key", "sensor"],
569
661
  settings: {
570
- item: {
571
- type: "text",
572
- label: "What to play",
573
- 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",
574
667
  placeholder: "A Spotify link, or pick a playlist",
575
668
  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 },
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 }),
593
676
  },
594
677
  run: async ({ settings }) => {
595
678
  const target = spotifyUri(settings.item);
@@ -608,7 +691,7 @@ const play = defineAction({
608
691
  look: (s) => key(s.mode === "queue" ? "lucide/list-end" : "lucide/list-music", s.text),
609
692
  });
610
693
 
611
- const seek = defineAction({
694
+ const seek = plugin.action({
612
695
  id: "seek",
613
696
  name: "Seek",
614
697
  description: "Jumps forward or back in the track.",
@@ -616,24 +699,17 @@ const seek = defineAction({
616
699
  icon: "fast-forward",
617
700
  slots: ["key", "sensor"],
618
701
  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",
702
+ direction: setting.select("Direction", {
703
+ forward: "Forward",
704
+ back: "Back",
705
+ start: "To the start",
706
+ }),
707
+ seconds: setting.number("Seconds", {
632
708
  default: 15,
633
709
  min: 1,
634
710
  max: 600,
635
711
  visibleIf: { direction: ["forward", "back"] },
636
- },
712
+ }),
637
713
  },
638
714
  run: async ({ settings }) => {
639
715
  const { positionMs, durationMs } = await current();
@@ -660,7 +736,7 @@ const seek = defineAction({
660
736
 
661
737
  const transfer = (id: string) => command("PUT", "/me/player", {}, { device_ids: [id], play: true });
662
738
 
663
- const device = defineAction({
739
+ const device = plugin.action({
664
740
  id: "device",
665
741
  name: "Play on a device",
666
742
  description: "Moves playback to another speaker, phone or computer.",
@@ -668,17 +744,13 @@ const device = defineAction({
668
744
  icon: "speaker",
669
745
  slots: ["key", "sensor"],
670
746
  settings: {
671
- device: {
672
- type: "select",
673
- label: "Device",
674
- options: [],
675
- source: "devices",
747
+ device: setting.pick("Device", sources.devices, {
748
+ required: true,
676
749
  description: "Only devices with Spotify open are listed.",
677
- },
678
- 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 }),
679
752
  },
680
753
  run: async ({ settings }) => {
681
- if (!settings.device) throw new Error("Pick a device in the key's settings");
682
754
  const before = (await readPlayer()).deviceId;
683
755
  await transfer(settings.device);
684
756
  return {
@@ -691,7 +763,7 @@ const device = defineAction({
691
763
 
692
764
  // -- Triggers -----------------------------------------------------------------------------------
693
765
 
694
- const trackChanged = defineTrigger({
766
+ const trackChanged = plugin.trigger({
695
767
  id: "track-changed",
696
768
  name: "When the track changes",
697
769
  description: "Fires with the new track whenever something else starts playing.",
@@ -708,42 +780,40 @@ const trackChanged = defineTrigger({
708
780
 
709
781
  // -- Plugin -------------------------------------------------------------------------------------
710
782
 
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])),
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
+ },
716
802
  });
717
803
 
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
- },
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();
746
813
  },
814
+ });
815
+
816
+ export default plugin.define({
747
817
  onboarding: {
748
818
  intro: "Spotify lets apps in only with an app of your own. It takes a minute.",
749
819
  steps: [
@@ -780,39 +850,7 @@ export default definePlugin({
780
850
  window: { action: "now-playing" },
781
851
  },
782
852
  },
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
- ],
853
+ commands: [signIn, signOut],
816
854
  actions: [
817
855
  playPause,
818
856
  next,
@@ -828,37 +866,9 @@ export default definePlugin({
828
866
  device,
829
867
  ],
830
868
  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
- ],
869
+ sources: Object.values(sources),
870
+ state: Object.values(values),
860
871
  activate(activated) {
861
- context = activated;
862
872
  activated.status(
863
873
  activated.secrets.get("refreshToken")
864
874
  ? "Signed in to Spotify"
@@ -867,7 +877,6 @@ export default definePlugin({
867
877
  );
868
878
  return () => {
869
879
  signingIn?.cancel();
870
- context = undefined;
871
880
  };
872
881
  },
873
882
  });