Add an iOS Spotify integration

This commit is contained in:
James Babcock committed 2026-10-24 00:18:04 -07:00
1 parent e36fb14a34
commit c9cf29e5c0
32 files changed
+3176 -50

No files matched your search

+43 -2
View File
@@ -6,6 +6,9 @@ import {
type MediaBrowserApp,
type MediaBrowserBridge,
} from "./media-types";
import { spotifyService } from "./spotify.ios";
import type { SpotifyLibrary } from "./spotify-library";
import { SPOTIFY_PACKAGE } from "./spotify-player";
export type { MediaBrowseItem, MediaBrowserApp } from "./media-types";
@@ -30,7 +33,7 @@ export class AppleMusicBrowserBridge implements MediaBrowserBridge {
connect(app: MediaBrowserApp): Promise<string> {
this.disconnect();
if (app.packageName !== APPLE_MUSIC_PACKAGE) return Promise.reject(new Error("Only Apple Music can be browsed on iOS"));
if (app.packageName !== APPLE_MUSIC_PACKAGE) return Promise.reject(new Error("Not an Apple Music library"));
if (!FaceclawAppleMusic.shared().hasPermission()) return Promise.reject(new Error("Apple Music access is not allowed"));
this.connected = true;
return Promise.resolve("root");
@@ -67,4 +70,42 @@ export class AppleMusicBrowserBridge implements MediaBrowserBridge {
}
}
export const mediaBrowserBridge: MediaBrowserBridge = new AppleMusicBrowserBridge();
/** Apple Music's library, plus the Spotify library once signed in. */
export class IosMediaBrowserBridge implements MediaBrowserBridge {
private current: MediaBrowserBridge | null = null;
constructor(
private readonly appleMusic: AppleMusicBrowserBridge,
private readonly spotify: () => SpotifyLibrary | null,
) {}
listBrowsableApps(): MediaBrowserApp[] {
return [...this.appleMusic.listBrowsableApps(), ...(this.spotify()?.listBrowsableApps() ?? [])];
}
connect(app: MediaBrowserApp): Promise<string> {
this.disconnect();
const library = app.packageName === SPOTIFY_PACKAGE ? this.spotify() : this.appleMusic;
if (!library) return Promise.reject(new Error(`${app.appName} can't be browsed`));
this.current = library;
return library.connect(app);
}
browse(parentId: string): Promise<MediaBrowseItem[]> {
return this.current ? this.current.browse(parentId) : Promise.reject(new Error("Not connected"));
}
playFromMediaId(mediaId: string): void {
this.current?.playFromMediaId(mediaId);
}
disconnect(): void {
this.current?.disconnect();
this.current = null;
}
}
export const mediaBrowserBridge: MediaBrowserBridge = new IosMediaBrowserBridge(
new AppleMusicBrowserBridge(),
() => spotifyService()?.library ?? null,
);
+195 -5
View File
@@ -11,6 +11,8 @@ import {
type MediaPlaybackState,
type MediaQueueItem,
} from "./media-types";
import { spotifyService } from "./spotify.ios";
import type { SpotifyPlayer } from "./spotify-player";
export type { MediaControllerState, MediaPlaybackState, MediaQueueItem } from "./media-types";
@@ -88,7 +90,7 @@ export class AppleMusicControllerBridge implements MediaControllerBridge {
onStateChange(listener: (state: MediaControllerState) => void): () => void {
void this.start();
this.stateListeners.add(listener);
this.pollTimer ??= setInterval(() => this.refresh(), POLL_MS);
this.pollTimer ??= setInterval(() => this.publish(), POLL_MS);
listener(this.snapshot());
return () => {
this.stateListeners.delete(listener);
@@ -142,7 +144,7 @@ export class AppleMusicControllerBridge implements MediaControllerBridge {
if (this.hasAccess()) return Promise.resolve(true);
this.pendingAccess ??= this.askForAccess().finally(() => {
this.pendingAccess = null;
this.refresh();
this.publish();
});
return this.pendingAccess;
}
@@ -187,12 +189,12 @@ export class AppleMusicControllerBridge implements MediaControllerBridge {
const music = FaceclawAppleMusic.shared();
if (!this.bound) {
this.bound = true;
music.changeHandler = () => this.refresh();
music.changeHandler = () => this.publish();
}
return music;
}
private refresh(): void {
private publish(): void {
if (!this.stateListeners.size) return;
const state = this.snapshot();
const signature = stateSignature(state);
@@ -228,4 +230,192 @@ export class AppleMusicControllerBridge implements MediaControllerBridge {
}
}
export const mediaControllerBridge: MediaControllerBridge = new AppleMusicControllerBridge();
export type IosMediaSource = "apple-music" | "spotify";
/**
* Which player to follow: the one playing; with both playing, the current
* choice (no flapping); with neither, the one that played last, and before
* either has played this run, Spotify when it reports a session (its player
* reports only a recently active one, while the system Music player keeps
* its last item for days).
*/
export function chooseMediaSource(
current: IosMediaSource,
appleMusic: MediaControllerState,
spotify: MediaControllerState | null,
appleMusicLastPlayingAtMs: number,
spotifyLastPlayingAtMs: number,
): IosMediaSource {
if (!spotify?.accessEnabled) return "apple-music";
if (!appleMusic.accessEnabled) return "spotify";
const applePlaying = appleMusic.playbackState === "playing";
const spotifyPlaying = spotify.playbackState === "playing";
if (applePlaying && spotifyPlaying) return current;
if (applePlaying) return "apple-music";
if (spotifyPlaying) return "spotify";
if (appleMusicLastPlayingAtMs !== spotifyLastPlayingAtMs) {
return spotifyLastPlayingAtMs > appleMusicLastPlayingAtMs ? "spotify" : "apple-music";
}
return spotify.available ? "spotify" : "apple-music";
}
/**
* The iOS Music bridge: Apple Music (the system player), plus Spotify once
* signed in (its Web API: playback on this phone or any Spotify Connect
* device). The state and every command follow one of them, by
* chooseMediaSource.
*/
export class IosMediaControllerBridge implements MediaControllerBridge {
readonly accessPrompt =
"Faceclaw needs access to Apple Music to show and control what's playing. Tap, then allow access on your phone. For Spotify, sign in from the app menu instead.";
readonly accessLabel: string;
readonly accessAction: string;
private source: IosMediaSource = "apple-music";
private appleMusicLastPlayingAtMs = 0;
private readonly listeners = new Set<(state: MediaControllerState) => void>();
private unsubscribeSources: Array<() => void> = [];
/** The source and its artVersion the composite artVersion was bumped for. */
private artKey = "";
private artVersion = 0;
constructor(
private readonly appleMusic: AppleMusicControllerBridge,
private readonly spotify: () => SpotifyPlayer | null,
private readonly now: () => number = Date.now,
) {
this.accessLabel = appleMusic.accessLabel;
this.accessAction = appleMusic.accessAction;
}
get skipRebuildsQueue(): boolean {
return this.active().skipRebuildsQueue;
}
onStateChange(listener: (state: MediaControllerState) => void): () => void {
if (!this.listeners.size) {
const update = () => this.emit();
const spotify = this.spotify();
this.unsubscribeSources = [this.appleMusic.onStateChange(update), ...(spotify ? [spotify.onStateChange(update)] : [])];
}
this.listeners.add(listener);
listener(this.snapshot());
return () => {
this.listeners.delete(listener);
if (this.listeners.size) return;
for (const unsubscribe of this.unsubscribeSources) unsubscribe();
this.unsubscribeSources = [];
};
}
snapshot(): MediaControllerState {
const appleMusic = this.appleMusic.snapshot();
const spotify = this.spotify()?.snapshot() ?? null;
this.select(appleMusic, spotify);
const state = this.source === "spotify" && spotify ? spotify : appleMusic;
// Changes with the source as well as with that source's art.
const artKey = `${this.source}:${state.artVersion}`;
if (artKey !== this.artKey) {
this.artKey = artKey;
this.artVersion++;
}
return {
...state,
status: state.available ? state.status : idleStatus(appleMusic, spotify, state),
artVersion: this.artVersion,
// A Spotify command can fail while Apple Music is the one shown (playing from the Spotify library).
notice: spotify?.notice || state.notice || "",
};
}
async start(): Promise<void> {
await this.appleMusic.start();
}
async stop(): Promise<void> {
await this.appleMusic.stop();
}
playPause(): Promise<void> {
return this.active().playPause();
}
skipNext(): Promise<void> {
return this.active().skipNext();
}
skipPrevious(): Promise<void> {
return this.active().skipPrevious();
}
/** Apple Music's media-library permission (what requestAccess asks for); Spotify signs in from the Music menu. */
hasAccess(): boolean {
return this.appleMusic.hasAccess();
}
requestAccess(): Promise<boolean> {
return this.appleMusic.requestAccess();
}
skipToQueueItem(id: number): Promise<void> {
return this.active().skipToQueueItem(id);
}
getMediaVolumePercent(): number {
return this.active().getMediaVolumePercent();
}
setMediaVolumePercent(volumePercent: number): void {
this.active().setMediaVolumePercent(volumePercent);
}
getAlbumArt(maxSize: number): GrayImage | null {
return this.active().getAlbumArt(maxSize);
}
getQueue(): MediaQueueItem[] {
return this.active().getQueue();
}
async sendCustomAction(action: string): Promise<void> {
await this.active().sendCustomAction?.(action);
}
async refresh(): Promise<void> {
await this.spotify()?.refresh();
}
private active(): MediaControllerBridge {
const spotify = this.spotify();
this.select(this.appleMusic.snapshot(), spotify?.snapshot() ?? null);
return this.source === "spotify" && spotify ? spotify : this.appleMusic;
}
private select(appleMusic: MediaControllerState, spotify: MediaControllerState | null): void {
if (appleMusic.playbackState === "playing") this.appleMusicLastPlayingAtMs = this.now();
this.source = chooseMediaSource(this.source, appleMusic, spotify, this.appleMusicLastPlayingAtMs,
this.spotify()?.lastPlayingAtMs ?? 0);
}
/**
* Forward every source update: each source already drops repeats, and
* Spotify also signals changes that are not in the state (its queue).
*/
private emit(): void {
if (!this.listeners.size) return;
const state = this.snapshot();
for (const listener of this.listeners) listener(state);
}
}
/** The no-session line: which players were checked. */
function idleStatus(appleMusic: MediaControllerState, spotify: MediaControllerState | null, shown: MediaControllerState): string {
if (appleMusic.accessEnabled && spotify?.accessEnabled) return "Nothing is playing.";
return shown.status;
}
export const appleMusicControllerBridge = new AppleMusicControllerBridge();
export const mediaControllerBridge: MediaControllerBridge = new IosMediaControllerBridge(
appleMusicControllerBridge,
() => spotifyService()?.player ?? null,
);
+23 -1
View File
@@ -3,7 +3,8 @@ import type { GrayImage } from "../graphics/image";
/**
* Shapes shared by the media bridges: media-controller.ts / media-browser.ts
* drive Android media sessions and MediaBrowserServices; their .ios.ts
* counterparts drive Apple Music through the MediaPlayer framework.
* counterparts drive Apple Music through the MediaPlayer framework and
* Spotify through its Web API.
*/
/** The player behind the iOS bridges: the system Music app. */
@@ -13,9 +14,19 @@ export const APPLE_MUSIC_PACKAGE = "com.apple.Music";
export type MediaQueueItem = {
id: number;
title: string;
/** Usually the artist; absent when the player gives none. */
subtitle?: string;
active: boolean;
};
/** A player-specific action beyond the transport controls (Spotify's shuffle, repeat, like). */
export type MediaCustomAction = {
/** Stable id to send back with sendCustomAction. */
action: string;
/** The row label, naming the current state where there is one ("Shuffle: on"). */
name: string;
};
export type MediaPlaybackState =
| "notification-access-required"
| "idle"
@@ -47,6 +58,10 @@ export type MediaControllerState = {
* players re-publish the same strings with a different bitmap.
*/
artVersion: number;
/** Player-specific actions (see sendCustomAction); absent when the player offers none. */
customActions?: MediaCustomAction[];
/** A short-lived message about a command that failed (Spotify needs Premium, ...); absent or "" otherwise. */
notice?: string;
};
export const DEFAULT_MEDIA_STATE: MediaControllerState = {
@@ -113,6 +128,13 @@ export interface MediaControllerBridge {
getAlbumArt(maxSize: number): GrayImage | null;
/** The player's queue (playlist), empty when the player exposes none. */
getQueue(): MediaQueueItem[];
/** Run one of the state's customActions. */
sendCustomAction?(action: string): Promise<void>;
/**
* Re-read the player now, for one-off readers (the assistant) when no
* listener keeps the state current; absent when snapshots are always live.
*/
refresh?(): Promise<void>;
}
export type MediaBrowserApp = {
+273
View File
@@ -0,0 +1,273 @@
import { getStringSetting, setStringSetting } from "./settings-store";
import { buildQuery, SpotifyApiError, SpotifyClient, type SpotifyFetch, type SpotifyTokenSource } from "./spotify-web-api";
/**
* Spotify sign-in: OAuth authorization code with PKCE against the user's own
* client ID (no client secret), redirected to a loopback address that the
* phone catches (FaceclawWebSignIn on iOS). Spotify accepts http only for
* loopback IP literals, and custom-scheme redirects fail with "insecure
* redirect URI" for apps created since 2025, so the redirect is
* http://127.0.0.1 on a fixed port the user registers in the dashboard.
*
* The tokens are stored with the client ID they were issued to; changing the
* client ID setting signs out.
*/
export const SPOTIFY_ACCOUNTS_BASE = "https://accounts.spotify.com";
export const SPOTIFY_REDIRECT_PORT = 43823;
export const SPOTIFY_REDIRECT_PATH = "/spotify-callback";
export const SPOTIFY_REDIRECT_URI = `http://127.0.0.1:${SPOTIFY_REDIRECT_PORT}${SPOTIFY_REDIRECT_PATH}`;
export const SPOTIFY_DASHBOARD_URL = "https://developer.spotify.com/dashboard";
export const SPOTIFY_CLIENT_ID_KEY = "music.spotify.clientId";
export const SPOTIFY_ACCOUNT_KEY = "music.spotify.account";
export const SPOTIFY_SCOPES = [
"user-read-playback-state",
"user-modify-playback-state",
"user-read-currently-playing",
"user-read-recently-played",
"playlist-read-private",
"playlist-read-collaborative",
"user-library-read",
"user-library-modify",
"user-follow-read",
];
/** Refresh this long before Spotify's stated expiry (an hour), so a token never lapses mid-request. */
const EXPIRY_MARGIN_MS = 60_000;
export type SpotifyAccount = {
clientId: string;
accessToken: string;
refreshToken: string;
/** Epoch ms. */
expiresAtMs: number;
userId: string;
displayName: string;
/** "premium", "free", ...; playback control needs premium. */
product: string;
};
export type SpotifyTokens = { accessToken: string; refreshToken: string; expiresAtMs: number };
/** The phone side of a sign-in: PKCE material and the browser sheet that catches the loopback redirect. */
export type WebSignIn = {
/** A fresh PKCE verifier and its S256 challenge. */
createPkce(): { verifier: string; challenge: string };
randomState(): string;
/** Show the provider's page; resolves to the redirect URL, rejects with "cancelled" or why it failed. */
open(authorizeUrl: string, port: number, path: string): Promise<string>;
cancel(): void;
};
export function spotifyClientId(): string {
return getStringSetting(SPOTIFY_CLIENT_ID_KEY, "").trim();
}
export function isValidSpotifyClientId(value: string): boolean {
return /^[0-9a-f]{32}$/i.test(value.trim());
}
/** The stored sign-in, or null when signed out or signed in with another client ID. */
export function readSpotifyAccount(): SpotifyAccount | null {
let raw: any;
try {
raw = JSON.parse(getStringSetting(SPOTIFY_ACCOUNT_KEY, "") || "null");
} catch {
return null;
}
if (!raw || typeof raw.refreshToken !== "string" || !raw.refreshToken) return null;
const clientId = spotifyClientId();
if (!clientId || raw.clientId !== clientId) return null;
return {
clientId,
accessToken: String(raw.accessToken ?? ""),
refreshToken: raw.refreshToken,
expiresAtMs: Number(raw.expiresAtMs) || 0,
userId: String(raw.userId ?? ""),
displayName: String(raw.displayName ?? ""),
product: String(raw.product ?? ""),
};
}
export function saveSpotifyAccount(account: SpotifyAccount | null): void {
setStringSetting(SPOTIFY_ACCOUNT_KEY, account ? JSON.stringify(account) : "");
}
export function spotifyAuthorizeUrl(clientId: string, codeChallenge: string, state: string): string {
return `${SPOTIFY_ACCOUNTS_BASE}/authorize${buildQuery({
response_type: "code",
client_id: clientId,
scope: SPOTIFY_SCOPES.join(" "),
redirect_uri: SPOTIFY_REDIRECT_URI,
state,
code_challenge_method: "S256",
code_challenge: codeChallenge,
})}`;
}
/** The authorization code from Spotify's redirect; throws with a message for the glasses otherwise. */
export function parseSpotifyRedirect(url: string, expectedState: string): string {
const params = parseQueryString(url);
if (params.error) {
throw new Error(params.error === "access_denied" ? "Spotify sign-in was declined." : `Spotify sign-in failed: ${params.error}`);
}
if (params.state !== expectedState) throw new Error("Spotify sign-in failed: the reply didn't match this sign-in. Try again.");
if (!params.code) throw new Error("Spotify sign-in failed: no authorization code in the reply.");
return params.code;
}
/** Query parameters of a URL (not URLSearchParams, which the NativeScript runtime mishandles). */
export function parseQueryString(url: string): Record<string, string> {
const query = url.split("#")[0]!.split("?").slice(1).join("?");
const params: Record<string, string> = {};
for (const part of query.split("&")) {
if (!part) continue;
const separator = part.indexOf("=");
const key = separator < 0 ? part : part.slice(0, separator);
const value = separator < 0 ? "" : part.slice(separator + 1);
try {
params[decodeURIComponent(key.replace(/\+/g, " "))] = decodeURIComponent(value.replace(/\+/g, " "));
} catch {
// Malformed escapes: skip the parameter.
}
}
return params;
}
/** POST to Spotify's token endpoint (authorization_code or refresh_token grant). */
export async function requestSpotifyTokens(
fetchImpl: SpotifyFetch,
params: Record<string, string>,
nowMs: number,
): Promise<SpotifyTokens> {
let status = 0;
let body = "";
try {
const response = await fetchImpl(`${SPOTIFY_ACCOUNTS_BASE}/api/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
body: buildQuery(params).slice(1),
});
status = response.status;
body = await response.text();
} catch (error) {
throw new SpotifyApiError(`Can't reach Spotify: ${(error as Error)?.message ?? error}`, 0);
}
let parsed: any = null;
try {
parsed = JSON.parse(body);
} catch {
// Reported below.
}
if (status >= 200 && status < 300 && typeof parsed?.access_token === "string") {
const expiresIn = Number(parsed.expires_in);
return {
accessToken: parsed.access_token,
// Spotify may rotate the refresh token; "" keeps the current one.
refreshToken: typeof parsed.refresh_token === "string" ? parsed.refresh_token : "",
expiresAtMs: nowMs + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600) * 1000,
};
}
const error = typeof parsed?.error === "string" ? parsed.error : "";
const description = typeof parsed?.error_description === "string" ? parsed.error_description : "";
if (error === "invalid_grant" && params.grant_type === "refresh_token") {
throw new SpotifyApiError("Spotify no longer accepts this sign-in. Sign in again from the Music app menu.", status, error);
}
if (error === "invalid_client") {
throw new SpotifyApiError("Spotify doesn't recognize the client ID. Check it under Spotify in the Music app menu.", status, error);
}
throw new SpotifyApiError(`Spotify sign-in failed: ${description || error || `HTTP ${status}`}`, status, error);
}
/**
* Access tokens for the stored account: the current one until it nears
* expiry, then one refresh shared by every caller waiting on it. A refresh
* Spotify rejects (revoked access) signs out.
*/
export class SpotifySession implements SpotifyTokenSource {
private refreshing: Promise<string> | null = null;
constructor(
private readonly fetchImpl: SpotifyFetch,
private readonly now: () => number = Date.now,
) {}
accessToken(forceRefresh: boolean): Promise<string> {
const account = readSpotifyAccount();
if (!account) return Promise.reject(new SpotifyApiError("Not signed in to Spotify.", 401, "signed_out"));
if (!forceRefresh && account.accessToken && account.expiresAtMs - EXPIRY_MARGIN_MS > this.now()) {
return Promise.resolve(account.accessToken);
}
this.refreshing ??= this.refresh(account).finally(() => {
this.refreshing = null;
});
return this.refreshing;
}
private async refresh(account: SpotifyAccount): Promise<string> {
let tokens: SpotifyTokens;
try {
tokens = await requestSpotifyTokens(this.fetchImpl, {
grant_type: "refresh_token",
refresh_token: account.refreshToken,
client_id: account.clientId,
}, this.now());
} catch (error) {
if (error instanceof SpotifyApiError && error.reason === "invalid_grant" && readSpotifyAccount()?.refreshToken === account.refreshToken) {
saveSpotifyAccount(null);
}
throw error;
}
// A sign-out or another sign-in while this was in flight wins.
if (readSpotifyAccount()?.refreshToken !== account.refreshToken) {
throw new SpotifyApiError("Spotify sign-in changed; try again.", 401, "signed_out");
}
saveSpotifyAccount({
...account,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken || account.refreshToken,
expiresAtMs: tokens.expiresAtMs,
});
return tokens.accessToken;
}
}
/**
* The whole sign-in: the browser sheet, the code exchange and the profile
* lookup; stores and returns the account. Rejects with "cancelled" when the
* user closes the sheet.
*/
export async function signInToSpotify(
fetchImpl: SpotifyFetch,
webSignIn: WebSignIn,
now: () => number = Date.now,
): Promise<SpotifyAccount> {
const clientId = spotifyClientId();
if (!isValidSpotifyClientId(clientId)) throw new Error("Enter your Spotify client ID first.");
const { verifier, challenge } = webSignIn.createPkce();
const state = webSignIn.randomState();
const redirect = await webSignIn.open(spotifyAuthorizeUrl(clientId, challenge, state), SPOTIFY_REDIRECT_PORT, SPOTIFY_REDIRECT_PATH);
const code = parseSpotifyRedirect(redirect, state);
const tokens = await requestSpotifyTokens(fetchImpl, {
grant_type: "authorization_code",
code,
redirect_uri: SPOTIFY_REDIRECT_URI,
client_id: clientId,
code_verifier: verifier,
}, now());
const user = await new SpotifyClient(fetchImpl, { accessToken: async () => tokens.accessToken }).me();
const account: SpotifyAccount = {
clientId,
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
expiresAtMs: tokens.expiresAtMs,
userId: user.id,
displayName: user.displayName,
product: user.product,
};
if (!account.refreshToken) throw new Error("Spotify sign-in failed: no refresh token in the reply.");
saveSpotifyAccount(account);
return account;
}
+157
View File
@@ -0,0 +1,157 @@
import type { MediaBrowseItem, MediaBrowserApp, MediaBrowserBridge } from "./media-types";
import { SPOTIFY_APP_NAME, SPOTIFY_PACKAGE, type SpotifyPlayer } from "./spotify-player";
import type { SpotifyClient, SpotifyItem, SpotifyPlayRequest } from "./spotify-web-api";
export const SPOTIFY_BROWSER_APP: MediaBrowserApp = { packageName: SPOTIFY_PACKAGE, serviceClass: "", appName: SPOTIFY_APP_NAME };
const ROOT_ROWS: MediaBrowseItem[] = [
{ mediaId: "recent", title: "Recently played", subtitle: "", browsable: true, playable: false },
{ mediaId: "playlists", title: "Playlists", subtitle: "", browsable: true, playable: false },
{ mediaId: "liked", title: "Liked Songs", subtitle: "", browsable: true, playable: true },
{ mediaId: "albums", title: "Albums", subtitle: "", browsable: true, playable: false },
{ mediaId: "artists", title: "Artists", subtitle: "", browsable: true, playable: false },
];
/** Separates a track's URI from the context it plays in ("" for none, "liked" for Liked Songs). */
const TRACK_CONTEXT_SEPARATOR = "|";
export type SpotifyLibraryDeps = {
client: SpotifyClient;
player: SpotifyPlayer;
isSignedIn(): boolean;
/** The signed-in user's id (Liked Songs' context URI names it). */
userId(): string;
};
/**
* The signed-in user's Spotify library as a browse tree (Web API):
*
* root -> recent | playlists | liked | albums | artists
* playlist:<id>, album:<id> -> tracks (browsable and playable)
* artist:<id> -> albums
* track:<uri>|<context> -> plays the track within its context
*
* Only playlists the user owns or collaborates on can list their tracks
* (development-mode client IDs, since February 2026); others are play-only.
*/
export class SpotifyLibrary implements MediaBrowserBridge {
private connected = false;
/** Bumped on every connect/disconnect; answers to older requests are dropped. */
private generation = 0;
constructor(private readonly deps: SpotifyLibraryDeps) {}
listBrowsableApps(): MediaBrowserApp[] {
return this.deps.isSignedIn() ? [SPOTIFY_BROWSER_APP] : [];
}
connect(app: MediaBrowserApp): Promise<string> {
this.disconnect();
if (app.packageName !== SPOTIFY_PACKAGE) return Promise.reject(new Error("Not a Spotify library"));
if (!this.deps.isSignedIn()) return Promise.reject(new Error("Sign in under Spotify in the Music app menu first."));
this.connected = true;
return Promise.resolve("root");
}
async browse(parentId: string): Promise<MediaBrowseItem[]> {
if (!this.connected) throw new Error("Not connected");
const generation = this.generation;
const rows = await this.list(parentId);
if (generation !== this.generation) throw new Error("Disconnected");
return rows;
}
playFromMediaId(mediaId: string): void {
if (!this.connected) return;
const request = this.playRequest(mediaId);
if (request) void this.deps.player.startPlayback(request);
}
disconnect(): void {
this.connected = false;
this.generation++;
}
/** What playing a browse row starts; null for rows that don't play. */
playRequest(mediaId: string): SpotifyPlayRequest | null {
if (mediaId === "liked") return { contextUri: this.likedContextUri() };
const [kind, ...rest] = mediaId.split(":");
const id = rest.join(":");
switch (kind) {
case "playlist":
case "album":
case "artist":
return id ? { contextUri: `spotify:${kind}:${id}` } : null;
case "track": {
const separator = id.lastIndexOf(TRACK_CONTEXT_SEPARATOR);
const uri = separator < 0 ? id : id.slice(0, separator);
const context = separator < 0 ? "" : id.slice(separator + 1);
if (!uri) return null;
if (context === "liked") return { contextUri: this.likedContextUri(), offsetUri: uri };
return context ? { contextUri: context, offsetUri: uri } : { uris: [uri] };
}
default:
return null;
}
}
private async list(parentId: string): Promise<MediaBrowseItem[]> {
const client = this.deps.client;
if (parentId === "root") return ROOT_ROWS;
if (parentId === "recent") {
// The history repeats tracks; keep each one's latest play.
const seen = new Set<string>();
return (await client.recentlyPlayed())
.filter((played) => !seen.has(played.item.uri) && seen.add(played.item.uri))
.map((played) => trackRow(played.item, played.contextUri));
}
if (parentId === "playlists") {
const userId = this.deps.userId();
return (await client.playlists()).map((playlist) => {
const listable = playlist.collaborative || playlist.ownerId === userId;
return {
mediaId: `playlist:${playlist.id}`,
title: playlist.name,
subtitle: listable ? "" : playlist.ownerName,
browsable: listable,
playable: true,
};
});
}
if (parentId === "liked") return (await client.savedTracks()).map((item) => trackRow(item, "liked"));
if (parentId === "albums") return (await client.savedAlbums()).map(albumRow);
if (parentId === "artists") {
return (await client.followedArtists()).map((artist) => ({
mediaId: `artist:${artist.id}`,
title: artist.name,
subtitle: "",
browsable: true,
playable: true,
}));
}
const [kind, ...rest] = parentId.split(":");
const id = rest.join(":");
if (kind === "playlist") return (await client.playlistItems(id)).map((item) => trackRow(item, `spotify:playlist:${id}`));
if (kind === "album") return (await client.albumTracks(id)).map((item) => trackRow(item, `spotify:album:${id}`));
if (kind === "artist") return (await client.artistAlbums(id)).map(albumRow);
throw new Error(`Unknown Spotify library item: ${parentId}`);
}
private likedContextUri(): string {
return `spotify:user:${this.deps.userId()}:collection`;
}
}
function trackRow(item: SpotifyItem, contextUri: string): MediaBrowseItem {
return {
mediaId: `track:${item.uri}${contextUri ? `${TRACK_CONTEXT_SEPARATOR}${contextUri}` : ""}`,
title: item.name,
subtitle: item.artists,
browsable: false,
playable: true,
};
}
function albumRow(album: { id: string; name: string; artists: string }): MediaBrowseItem {
return { mediaId: `album:${album.id}`, title: album.name, subtitle: album.artists, browsable: true, playable: true };
}
+570
View File
@@ -0,0 +1,570 @@
import type { GrayImage } from "../graphics/image";
import {
DEFAULT_MEDIA_STATE,
interpolateMediaState,
type MediaControllerBridge,
type MediaControllerState,
type MediaCustomAction,
type MediaQueueItem,
} from "./media-types";
import {
SpotifyApiError,
type SpotifyClient,
type SpotifyDevice,
type SpotifyItem,
type SpotifyPlayback,
type SpotifyPlayRequest,
type SpotifyRepeat,
} from "./spotify-web-api";
export const SPOTIFY_APP_NAME = "Spotify";
/** The iOS app's bundle id; Spotify's Android package is com.spotify.music. */
export const SPOTIFY_PACKAGE = "com.spotify.client";
/**
* Poll intervals while something listens. The Web API has no push channel, so
* a track change shows up within one interval (sooner at a track's end, which
* is polled for directly); requests count against the client ID's quota.
*/
const POLL_PLAYING_MS = 5_000;
const POLL_PAUSED_MS = 10_000;
const POLL_IDLE_MS = 20_000;
const POLL_ERROR_MS = 30_000;
/** Re-read soon after a command: Spotify takes a moment to report its effect. */
const SETTLE_POLL_MS = 600;
const SETTLE_POLLS = 2;
const NOTICE_MS = 8_000;
/** Re-read the queue this often while the Music app shows it, besides on every track change. */
const QUEUE_MAX_AGE_MS = 30_000;
/** At most this often, even on track changes (and after a failed read). */
const QUEUE_MIN_INTERVAL_MS = 5_000;
/** Album art: the smallest of Spotify's sizes (640/300/64) at least this wide. */
const ART_MIN_WIDTH = 128;
const REPEAT_NEXT: Record<SpotifyRepeat, SpotifyRepeat> = { off: "context", context: "track", track: "off" };
const REPEAT_LABEL: Record<SpotifyRepeat, string> = { off: "Repeat: off", context: "Repeat: all", track: "Repeat: one" };
export type SpotifyPlayerDeps = {
client: SpotifyClient;
isSignedIn(): boolean;
/** Fetch an album-art image's encoded bytes; null on failure. */
download(url: string): Promise<Uint8Array | null>;
/** Encoded image bytes to the shared photo tone, fitted within maxSize; null when undecodable. */
decodeArt(bytes: Uint8Array, maxSize: number): GrayImage | null;
/** The phone's output volume, for playback on this phone (Spotify won't set a phone's volume). */
systemVolume: { get(): number; set(percent: number): void };
now?: () => number;
};
/**
* Spotify Connect playback (on this phone or any of the user's devices)
* through the Web API: state from polling GET /me/player while something
* listens, commands as API calls whose failures (no device, no Premium)
* become a short notice in the state.
*/
export class SpotifyPlayer implements MediaControllerBridge {
readonly accessPrompt = "Sign in to Spotify from the Music app menu to show and control Spotify.";
readonly accessLabel = "Spotify sign-in needed";
readonly accessAction = "open the menu";
/** Jumping skips forward through the queue, so the chosen track ends up first. */
readonly skipRebuildsQueue = true;
/** When Spotify was last seen playing (epoch ms); 0 = not this run. */
lastPlayingAtMs = 0;
private readonly now: () => number;
private readonly listeners = new Set<(state: MediaControllerState) => void>();
private playback: SpotifyPlayback | null = null;
private fetchedAtMs = 0;
private pollTimer: ReturnType<typeof setTimeout> | null = null;
private polling: Promise<void> | null = null;
private pollAgain = false;
private settlePolls = 0;
private lastSignature = "";
private notice = "";
private noticeUntilMs = 0;
private noticeTimer: ReturnType<typeof setTimeout> | null = null;
private upcoming: SpotifyItem[] = [];
/** The item the queue was read with; "" = never read. */
private queueCurrentUri = "";
/** When the queue was last read, or a read failed. */
private queueFetchedAtMs = 0;
private queueLoading = false;
private art: { url: string; bytes: Uint8Array | null; decoded: Map<number, GrayImage | null> } | null = null;
private artVersion = 0;
private liked: { uri: string; value: boolean | null } | null = null;
private volumeTarget: number | null = null;
private volumeSending = false;
constructor(private readonly deps: SpotifyPlayerDeps) {
this.now = deps.now ?? Date.now;
}
onStateChange(listener: (state: MediaControllerState) => void): () => void {
this.listeners.add(listener);
listener(this.snapshot());
if (this.listeners.size === 1) this.schedulePoll(0);
return () => {
this.listeners.delete(listener);
if (!this.listeners.size && !this.settlePolls) this.clearPollTimer();
};
}
snapshot(): MediaControllerState {
const notice = this.currentNotice();
if (!this.deps.isSignedIn()) {
return { ...DEFAULT_MEDIA_STATE, status: "Not signed in to Spotify.", notice };
}
const playback = this.playback;
if (!playback) {
return {
...DEFAULT_MEDIA_STATE,
accessEnabled: true,
packageName: SPOTIFY_PACKAGE,
appName: SPOTIFY_APP_NAME,
status: "Nothing is playing on Spotify.",
notice,
};
}
const item = playback.item;
const restricted = playback.device?.restricted === true;
const allowed = (action: string) => !restricted && !playback.disallows.includes(action);
const state: MediaControllerState = {
available: true,
accessEnabled: true,
packageName: SPOTIFY_PACKAGE,
appName: spotifyAppName(playback.device),
playbackState: playback.playing ? "playing" : "paused",
title: item?.name ?? (playback.playingType === "ad" ? "Advertisement" : ""),
artist: item?.artists ?? "",
album: item?.album ?? "",
positionMs: item ? playback.progressMs : -1,
durationMs: item?.durationMs ?? -1,
playbackSpeed: playback.playing ? 1 : 0,
status: "",
canPlayPause: allowed(playback.playing ? "pausing" : "resuming"),
canSkipNext: allowed("skipping_next"),
canSkipPrevious: allowed("skipping_prev"),
artVersion: this.artVersion,
customActions: restricted ? [] : this.customActions(playback),
notice,
};
return interpolateMediaState(state, this.fetchedAtMs, this.now());
}
async start(): Promise<void> {}
async stop(): Promise<void> {}
async playPause(): Promise<void> {
const playback = this.playback;
if (!playback?.playing) {
await this.startPlayback({});
return;
}
await this.command(() => this.deps.client.pause(), () => {
playback.progressMs = this.snapshot().positionMs;
playback.playing = false;
this.fetchedAtMs = this.now();
});
}
async skipNext(): Promise<void> {
await this.command(() => this.deps.client.next());
}
async skipPrevious(): Promise<void> {
await this.command(() => this.deps.client.previous());
}
/** Signed in; whether anything is playing is in the state. */
hasAccess(): boolean {
return this.deps.isSignedIn();
}
/** Sign-in happens from the Music app menu, which shows its progress. */
async requestAccess(): Promise<boolean> {
return this.hasAccess();
}
/**
* Queue ids are positions in getQueue (0 = the current item). The Web API
* has no jump, so this skips forward that many times.
*/
async skipToQueueItem(id: number): Promise<void> {
const steps = Math.round(id);
if (steps <= 0 || steps > this.upcoming.length) return;
await this.command(async () => {
for (let step = 0; step < steps; step++) await this.deps.client.next();
}, () => {
const target = this.upcoming[steps - 1];
if (this.playback && target) {
this.playback.item = target;
this.playback.progressMs = 0;
this.fetchedAtMs = this.now();
this.upcoming = this.upcoming.slice(steps);
this.queueCurrentUri = target.uri;
this.itemChanged(target);
}
});
}
getMediaVolumePercent(): number {
const device = this.playback?.device ?? null;
if (!usesDeviceVolume(device)) return this.deps.systemVolume.get();
return this.volumeTarget ?? device!.volumePercent;
}
setMediaVolumePercent(volumePercent: number): void {
const device = this.playback?.device ?? null;
const volume = Math.max(0, Math.min(100, Math.round(volumePercent)));
if (!usesDeviceVolume(device)) {
this.deps.systemVolume.set(volume);
return;
}
// Scrolling sends a value per step: keep one request in flight and send the latest after it.
device!.volumePercent = volume;
this.volumeTarget = volume;
if (!this.volumeSending) void this.sendVolume(device!.id);
}
getAlbumArt(maxSize: number): GrayImage | null {
const art = this.art;
if (!art?.bytes) return null;
const size = Math.round(maxSize);
if (!art.decoded.has(size)) art.decoded.set(size, this.deps.decodeArt(art.bytes, size));
return art.decoded.get(size) ?? null;
}
/**
* The current item, then what Spotify will play next. Read on demand (the
* Music app asks while it paints), so nothing else pays for the request; a
* stale list stays up, minus the items already played, until the new one
* arrives.
*/
getQueue(): MediaQueueItem[] {
const current = this.playback?.item;
if (!current) return [];
const age = this.now() - this.queueFetchedAtMs;
if (!this.queueLoading && (age > QUEUE_MAX_AGE_MS || (this.queueCurrentUri !== current.uri && age > QUEUE_MIN_INTERVAL_MS))) {
void this.loadQueue();
}
if (!this.queueCurrentUri) return [];
if (this.queueCurrentUri !== current.uri) {
const index = this.upcoming.findIndex((item) => item.uri === current.uri);
if (index >= 0) {
this.upcoming = this.upcoming.slice(index + 1);
this.queueCurrentUri = current.uri;
}
}
return [current, ...this.upcoming].map((item, index) => ({
id: index,
title: item.name,
subtitle: item.artists,
active: index === 0,
}));
}
async sendCustomAction(action: string): Promise<void> {
const playback = this.playback;
if (!playback) return;
const client = this.deps.client;
if (action === "shuffle") {
const shuffle = !playback.shuffle;
await this.command(() => client.setShuffle(shuffle), () => {
playback.shuffle = shuffle;
// Shuffling reorders what comes next.
this.queueFetchedAtMs = 0;
});
} else if (action === "repeat") {
const repeat = REPEAT_NEXT[playback.repeat];
await this.command(() => client.setRepeat(repeat), () => {
playback.repeat = repeat;
});
} else if (action === "like") {
const liked = this.liked;
if (!liked || liked.value === null) return;
const value = !liked.value;
await this.command(() => (value ? client.saveToLibrary([liked.uri]) : client.removeFromLibrary([liked.uri])), () => {
if (this.liked === liked) liked.value = value;
});
}
}
async refresh(): Promise<void> {
await this.poll();
}
/**
* Play something (a browsed item, a search result) or, with an empty
* request, resume. With no active device, starts on one the account has
* open (preferring a phone). Resolves to whether it worked; a failure is
* left as the state's notice.
*/
async startPlayback(request: SpotifyPlayRequest): Promise<boolean> {
const client = this.deps.client;
const playback = this.playback;
const ok = await this.command(async () => {
try {
await client.play(request);
} catch (error) {
if (!(error instanceof SpotifyApiError) || error.reason !== "NO_ACTIVE_DEVICE") throw error;
const device = pickDevice(await client.devices());
if (!device) throw error;
await client.play(request, device.id);
}
}, () => {
this.lastPlayingAtMs = this.now();
if (playback && this.playback === playback && !request.contextUri && !request.uris) {
playback.playing = true;
this.fetchedAtMs = this.now();
}
});
return ok;
}
/** The account changed (signed in, out, or as someone else): forget the old account's state. */
accountChanged(): void {
this.playback = null;
this.upcoming = [];
this.queueCurrentUri = "";
this.art = null;
this.artVersion++;
this.liked = null;
this.lastPlayingAtMs = 0;
this.emit(true);
if (this.listeners.size) this.schedulePoll(0);
}
/** Show a message about a failed command in the state's notice for a few seconds. */
showNotice(message: string): void {
this.notice = message;
this.noticeUntilMs = this.now() + NOTICE_MS;
if (this.noticeTimer !== null) clearTimeout(this.noticeTimer);
this.noticeTimer = setTimeout(() => {
this.noticeTimer = null;
this.emit(true);
}, NOTICE_MS + 50);
this.emit(true);
}
private currentNotice(): string {
return this.notice && this.now() < this.noticeUntilMs ? this.notice : "";
}
private customActions(playback: SpotifyPlayback): MediaCustomAction[] {
if (!playback.item) return [];
const actions: MediaCustomAction[] = [];
if (!playback.disallows.includes("toggling_shuffle")) {
actions.push({ action: "shuffle", name: playback.shuffle ? "Shuffle: on" : "Shuffle: off" });
}
if (!playback.disallows.includes("toggling_repeat_context") || !playback.disallows.includes("toggling_repeat_track")) {
actions.push({ action: "repeat", name: REPEAT_LABEL[playback.repeat] });
}
const liked = this.liked;
if (playback.item.type === "track" && liked?.uri === playback.item.uri && liked.value !== null) {
actions.push({ action: "like", name: liked.value ? "Unlike song" : "Like song" });
}
return actions;
}
/** Run a command; on success apply its expected effect at once, then re-read to confirm. */
private async command(run: () => Promise<void>, applied?: () => void): Promise<boolean> {
let ok = false;
try {
await run();
ok = true;
applied?.();
this.emit(true);
} catch (error) {
this.showNotice(errorMessage(error));
}
this.settlePolls = SETTLE_POLLS;
this.schedulePoll(SETTLE_POLL_MS);
return ok;
}
private async sendVolume(deviceId: string): Promise<void> {
this.volumeSending = true;
try {
while (this.volumeTarget !== null) {
const volume = this.volumeTarget;
try {
await this.deps.client.setVolume(volume, deviceId);
} catch (error) {
this.showNotice(errorMessage(error));
}
if (this.volumeTarget === volume) this.volumeTarget = null;
}
} finally {
this.volumeSending = false;
}
}
private poll(): Promise<void> {
if (this.polling) {
this.pollAgain = true;
return this.polling;
}
this.polling = this.pollOnce().finally(() => {
this.polling = null;
if (this.pollAgain) {
this.pollAgain = false;
void this.poll();
}
});
return this.polling;
}
private async pollOnce(): Promise<void> {
this.clearPollTimer();
if (!this.deps.isSignedIn()) {
if (this.playback) {
this.playback = null;
this.emit(true);
}
return;
}
let delay: number;
try {
const playback = await this.deps.client.playback();
this.fetchedAtMs = this.now();
this.applyPlayback(playback);
delay = this.nextPollDelay(playback);
} catch (error) {
if (!(error instanceof SpotifyApiError) || error.reason !== "signed_out") {
console.warn(`[spotify] playback read failed: ${error}`);
}
// Revoked access signs out (SpotifySession); the account listener resets the state.
delay = POLL_ERROR_MS;
}
if (this.settlePolls > 0) {
this.settlePolls--;
delay = Math.min(delay, 1_500);
}
this.emit(false);
this.schedulePoll(delay);
}
private applyPlayback(playback: SpotifyPlayback | null): void {
const previousUri = this.playback?.item?.uri ?? "";
this.playback = playback;
if (playback?.playing) this.lastPlayingAtMs = this.now();
const item = playback?.item ?? null;
if ((item?.uri ?? "") !== previousUri) this.itemChanged(item);
}
/** A new item: fetch its art and whether it is liked. */
private itemChanged(item: SpotifyItem | null): void {
const url = item ? pickArtUrl(item) : "";
if (url !== (this.art?.url ?? "")) {
this.artVersion++;
this.art = url ? { url, bytes: null, decoded: new Map() } : null;
if (url) void this.loadArt(url);
}
this.liked = item?.type === "track" ? { uri: item.uri, value: null } : null;
if (item?.type === "track") void this.loadLiked(item.uri);
}
private async loadArt(url: string): Promise<void> {
let bytes: Uint8Array | null = null;
try {
bytes = await this.deps.download(url);
} catch (error) {
console.warn(`[spotify] album art download failed: ${error}`);
}
if (!bytes?.length || this.art?.url !== url) return;
this.art.bytes = bytes;
this.artVersion++;
this.emit(true);
}
private async loadLiked(uri: string): Promise<void> {
try {
const [value] = await this.deps.client.libraryContains([uri]);
if (this.liked?.uri !== uri) return;
this.liked.value = Boolean(value);
this.emit(true);
} catch (error) {
console.warn(`[spotify] library check failed: ${error}`);
}
}
private async loadQueue(): Promise<void> {
this.queueLoading = true;
try {
const queue = await this.deps.client.queue();
this.upcoming = queue.upcoming;
this.queueCurrentUri = queue.current?.uri ?? "";
this.queueFetchedAtMs = this.now();
this.emit(true);
} catch (error) {
console.warn(`[spotify] queue read failed: ${error}`);
this.queueFetchedAtMs = this.now();
} finally {
this.queueLoading = false;
}
}
private nextPollDelay(playback: SpotifyPlayback | null): number {
if (!playback) return POLL_IDLE_MS;
if (!playback.playing) return POLL_PAUSED_MS;
const durationMs = playback.item?.durationMs ?? -1;
// Catch the change to the next track as it happens.
const remaining = durationMs > 0 ? durationMs - playback.progressMs + 700 : POLL_PLAYING_MS;
return Math.max(1_000, Math.min(POLL_PLAYING_MS, remaining));
}
private schedulePoll(delayMs: number): void {
if (!this.listeners.size && !this.settlePolls) return;
this.clearPollTimer();
this.pollTimer = setTimeout(() => {
this.pollTimer = null;
void this.poll();
}, delayMs);
}
private clearPollTimer(): void {
if (this.pollTimer !== null) clearTimeout(this.pollTimer);
this.pollTimer = null;
}
/** Tell listeners; unforced, only when something they draw (other than the advancing position) changed. */
private emit(force: boolean): void {
if (!this.listeners.size) return;
const state = this.snapshot();
const signature = JSON.stringify({ ...state, positionMs: 0 });
if (!force && signature === this.lastSignature) return;
this.lastSignature = signature;
for (const listener of this.listeners) listener(state);
}
}
/** "Spotify", or "Spotify · <device>" when it plays elsewhere than a phone. */
export function spotifyAppName(device: SpotifyDevice | null): string {
if (!device?.name || device.type === "Smartphone") return SPOTIFY_APP_NAME;
return `${SPOTIFY_APP_NAME} · ${device.name}`;
}
/** Spotify sets a speaker's or computer's volume; a phone's (this one) goes through the system volume. */
function usesDeviceVolume(device: SpotifyDevice | null): boolean {
return Boolean(device && device.type !== "Smartphone" && device.supportsVolume && device.volumePercent >= 0 && device.id);
}
/** A device to start playback on when none is active: an open one, a phone first. */
export function pickDevice(devices: SpotifyDevice[]): SpotifyDevice | null {
const usable = devices.filter((device) => device.id && !device.restricted);
return usable.find((device) => device.active)
?? usable.find((device) => device.type === "Smartphone")
?? usable[0]
?? null;
}
function pickArtUrl(item: SpotifyItem): string {
const images = [...item.images].sort((a, b) => a.width - b.width);
return (images.find((image) => image.width >= ART_MIN_WIDTH) ?? images[images.length - 1])?.url ?? "";
}
export function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
+159
View File
@@ -0,0 +1,159 @@
import type { GrayImage } from "../graphics/image";
import { onSettingsStoreChanged } from "./settings-store";
import {
readSpotifyAccount,
saveSpotifyAccount,
signInToSpotify,
SPOTIFY_ACCOUNT_KEY,
SPOTIFY_CLIENT_ID_KEY,
SpotifySession,
type SpotifyAccount,
type WebSignIn,
} from "./spotify-auth";
import { SpotifyLibrary } from "./spotify-library";
import { errorMessage, SpotifyPlayer } from "./spotify-player";
import { SpotifyClient, type SpotifyFetch, type SpotifySearchType } from "./spotify-web-api";
/** Give up on a sign-in nobody finished on the phone. */
const SIGN_IN_TIMEOUT_MS = 10 * 60_000;
/** What the platform supplies (spotify.ios.ts). */
export type SpotifyPlatform = {
fetch: SpotifyFetch;
webSignIn: WebSignIn;
download(url: string): Promise<Uint8Array | null>;
decodeArt(bytes: Uint8Array, maxSize: number): GrayImage | null;
systemVolume: { get(): number; set(percent: number): void };
};
export type SpotifySignInState =
| { phase: "idle"; error: string }
/** The sign-in sheet is open on the phone, or waiting for Faceclaw to come to the foreground. */
| { phase: "waiting"; error: "" };
/**
* Spotify for the Music app, the media bridges and the assistant: the
* account and its sign-in, the Web API client, the player and the library.
*/
export class SpotifyService {
readonly client: SpotifyClient;
readonly player: SpotifyPlayer;
readonly library: SpotifyLibrary;
private signInState: SpotifySignInState = { phase: "idle", error: "" };
private readonly listeners = new Set<() => void>();
private accountKey: string;
constructor(private readonly platform: SpotifyPlatform) {
const isSignedIn = () => readSpotifyAccount() !== null;
this.client = new SpotifyClient(platform.fetch, new SpotifySession(platform.fetch));
this.player = new SpotifyPlayer({
client: this.client,
isSignedIn,
download: (url) => platform.download(url),
decodeArt: (bytes, maxSize) => platform.decodeArt(bytes, maxSize),
systemVolume: platform.systemVolume,
});
this.library = new SpotifyLibrary({
client: this.client,
player: this.player,
isSignedIn,
userId: () => readSpotifyAccount()?.userId ?? "",
});
this.accountKey = accountIdentity(readSpotifyAccount());
onSettingsStoreChanged((key) => {
if (key !== SPOTIFY_ACCOUNT_KEY && key !== SPOTIFY_CLIENT_ID_KEY) return;
// Token refreshes rewrite the account too; only a different sign-in resets the player.
const identity = accountIdentity(readSpotifyAccount());
if (identity !== this.accountKey) {
this.accountKey = identity;
this.player.accountChanged();
}
this.emit();
});
}
account(): SpotifyAccount | null {
return readSpotifyAccount();
}
signInStatus(): SpotifySignInState {
return this.signInState;
}
/** Repaint hook for the sign-in menu: account or sign-in progress changed. */
onChange(listener: () => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/**
* Open Spotify's sign-in page on the phone (it waits for Faceclaw to be in
* the foreground); the outcome lands in signInStatus().
*/
async signIn(): Promise<void> {
if (this.signInState.phase === "waiting") return;
this.signInState = { phase: "waiting", error: "" };
this.emit();
const timer = setTimeout(() => this.platform.webSignIn.cancel(), SIGN_IN_TIMEOUT_MS);
try {
await signInToSpotify(this.platform.fetch, this.platform.webSignIn);
this.signInState = { phase: "idle", error: "" };
} catch (error) {
const message = errorMessage(error);
this.signInState = { phase: "idle", error: message === "cancelled" ? "" : message };
} finally {
clearTimeout(timer);
this.emit();
}
}
cancelSignIn(): void {
this.platform.webSignIn.cancel();
}
signOut(): void {
saveSpotifyAccount(null);
this.signInState = { phase: "idle", error: "" };
this.emit();
}
/**
* Search Spotify and play the best match: a track, or the album, artist or
* playlist when the request names that kind. Resolves to what started, or
* rejects with why not.
*/
async playSearch(query: string, kind: SpotifySearchType = "track"): Promise<string> {
if (!readSpotifyAccount()) throw new Error("Not signed in to Spotify. Sign in under Spotify in the Music app menu on the glasses.");
const results = await this.client.search(query, [kind], 3);
let request: { contextUri?: string; uris?: string[] } | null = null;
let description = "";
if (kind === "track" && results.tracks[0]) {
const track = results.tracks[0];
request = { uris: [track.uri] };
description = `${track.name}${track.artists ? ` by ${track.artists}` : ""}`;
} else if (kind === "album" && results.albums[0]) {
const album = results.albums[0];
request = { contextUri: album.uri };
description = `the album ${album.name}${album.artists ? ` by ${album.artists}` : ""}`;
} else if (kind === "artist" && results.artists[0]) {
request = { contextUri: results.artists[0].uri };
description = results.artists[0].name;
} else if (kind === "playlist" && results.playlists[0]) {
request = { contextUri: results.playlists[0].uri };
description = `the playlist ${results.playlists[0].name}`;
}
if (!request) throw new Error(`Spotify found no ${kind} matching "${query}".`);
if (!(await this.player.startPlayback(request))) {
throw new Error(this.player.snapshot().notice || "Spotify didn't start playback.");
}
return description;
}
private emit(): void {
for (const listener of this.listeners) listener();
}
}
function accountIdentity(account: SpotifyAccount | null): string {
return account ? `${account.clientId}/${account.userId}` : "";
}
+474
View File
@@ -0,0 +1,474 @@
/**
* Spotify Web API over HTTPS with the signed-in user's token: the player
* (what is playing on any of the user's Spotify Connect devices, and control
* of it), the user's library, and search, normalized into the small shapes
* the Music app uses. No NativeScript imports, so the Node tests drive it with
* a fake fetch.
*
* Every personal client ID is a development-mode app, which since February
* 2026 means: the client ID's owner needs Premium, playback control needs
* Premium, at most five allowlisted users, only owned or collaborative
* playlists list their items, no batch lookups, and search and artist albums
* return at most 10 results per page.
*/
export const SPOTIFY_API_BASE = "https://api.spotify.com/v1";
const HTTP_TIMEOUT_MS = 12_000;
/** The most a library listing gathers (a page is 50); enough to scroll through on the glasses. */
const MAX_LIST_ITEMS = 500;
/** The subset of fetch this client needs (fetchTextWithUserAgent in the app). */
export type SpotifyFetch = (
url: string,
init: { method: string; headers: Record<string, string>; body?: string },
) => Promise<{ status: number; text(): Promise<string> }>;
/** Hands out a current access token, refreshing it when expired or when forced (after a 401). */
export type SpotifyTokenSource = {
accessToken(forceRefresh: boolean): Promise<string>;
};
/** A failed request; `reason` is Spotify's player error code (NO_ACTIVE_DEVICE, PREMIUM_REQUIRED, ...). */
export class SpotifyApiError extends Error {
constructor(
message: string,
readonly status: number,
readonly reason = "",
) {
super(message);
this.name = "SpotifyApiError";
}
}
export type SpotifyImage = { url: string; width: number; height: number };
export type SpotifyItem = {
uri: string;
type: "track" | "episode";
name: string;
/** Track artists, comma-joined; for an episode, its show. */
artists: string;
/** The track's album; for an episode, its show. "" when the API leaves it out (album track listings). */
album: string;
durationMs: number;
images: SpotifyImage[];
};
export type SpotifyDevice = {
id: string;
name: string;
/** "Smartphone", "Computer", "Speaker", ... */
type: string;
active: boolean;
/** Restricted devices accept no Web API commands. */
restricted: boolean;
/** -1 when the device reports none. */
volumePercent: number;
supportsVolume: boolean;
};
export type SpotifyRepeat = "off" | "context" | "track";
export type SpotifyPlayback = {
device: SpotifyDevice | null;
playing: boolean;
progressMs: number;
shuffle: boolean;
repeat: SpotifyRepeat;
/** The playlist / album / artist playing from; "" for none (a queue of single tracks). */
contextUri: string;
/** null during an ad, between items, or for content the API does not describe. */
item: SpotifyItem | null;
/** "track", "episode", "ad" or "unknown". */
playingType: string;
/** The player actions the context forbids, as Spotify names them: pausing, resuming, skipping_next, ... */
disallows: string[];
};
export type SpotifyQueue = { current: SpotifyItem | null; upcoming: SpotifyItem[] };
export type SpotifyUser = { id: string; displayName: string; product: string };
export type SpotifyPlaylist = {
id: string;
uri: string;
name: string;
ownerId: string;
ownerName: string;
collaborative: boolean;
total: number;
};
export type SpotifyAlbum = { id: string; uri: string; name: string; artists: string };
export type SpotifyArtist = { id: string; uri: string; name: string };
/** A played track and the context it played from ("" when none). */
export type SpotifyPlayed = { item: SpotifyItem; contextUri: string };
export type SpotifySearchResults = {
tracks: SpotifyItem[];
albums: SpotifyAlbum[];
artists: SpotifyArtist[];
playlists: SpotifyPlaylist[];
};
export type SpotifySearchType = "track" | "album" | "artist" | "playlist";
/**
* What to play: a context (playlist, album, artist, show) optionally starting
* at one of its items, or a list of track URIs. Empty resumes the current
* playback.
*/
export type SpotifyPlayRequest = {
contextUri?: string;
uris?: string[];
offsetUri?: string;
offsetPosition?: number;
};
type Query = Record<string, string | number | boolean | undefined>;
export class SpotifyClient {
constructor(
private readonly fetchImpl: SpotifyFetch,
private readonly tokens: SpotifyTokenSource,
) {}
/** The current playback on whichever device is active; null when nothing is. */
async playback(): Promise<SpotifyPlayback | null> {
const raw = await this.request("GET", "/me/player", { query: { additional_types: "episode" } });
return raw ? parsePlayback(raw) : null;
}
async queue(): Promise<SpotifyQueue> {
const raw = await this.request("GET", "/me/player/queue");
return {
current: parseItem(raw?.currently_playing),
upcoming: asArray(raw?.queue).map(parseItem).filter(isPresent),
};
}
async devices(): Promise<SpotifyDevice[]> {
const raw = await this.request("GET", "/me/player/devices");
return asArray(raw?.devices).map(parseDevice).filter(isPresent);
}
async play(request: SpotifyPlayRequest = {}, deviceId = ""): Promise<void> {
const body: Record<string, unknown> = {};
if (request.contextUri) body.context_uri = request.contextUri;
if (request.uris?.length) body.uris = request.uris;
if (request.offsetUri) body.offset = { uri: request.offsetUri };
else if (request.offsetPosition !== undefined) body.offset = { position: request.offsetPosition };
await this.request("PUT", "/me/player/play", { query: { device_id: deviceId || undefined }, body });
}
async pause(): Promise<void> {
await this.request("PUT", "/me/player/pause");
}
async next(): Promise<void> {
await this.request("POST", "/me/player/next");
}
async previous(): Promise<void> {
await this.request("POST", "/me/player/previous");
}
async setShuffle(on: boolean): Promise<void> {
await this.request("PUT", "/me/player/shuffle", { query: { state: on } });
}
async setRepeat(mode: SpotifyRepeat): Promise<void> {
await this.request("PUT", "/me/player/repeat", { query: { state: mode } });
}
async setVolume(percent: number, deviceId = ""): Promise<void> {
const volume = Math.max(0, Math.min(100, Math.round(percent)));
await this.request("PUT", "/me/player/volume", { query: { volume_percent: volume, device_id: deviceId || undefined } });
}
/** Move playback to a device (one that shows in devices() but is not active), optionally playing. */
async transfer(deviceId: string, play: boolean): Promise<void> {
await this.request("PUT", "/me/player", { body: { device_ids: [deviceId], play } });
}
async me(): Promise<SpotifyUser> {
const raw = await this.request("GET", "/me");
return { id: str(raw?.id), displayName: str(raw?.display_name) || str(raw?.id), product: str(raw?.product) };
}
/** Whether each URI is in the user's library (Liked Songs for tracks). */
async libraryContains(uris: string[]): Promise<boolean[]> {
const raw = await this.request("GET", "/me/library/contains", { query: { uris: uris.join(",") } });
return asArray(raw).map(Boolean);
}
async saveToLibrary(uris: string[]): Promise<void> {
await this.request("PUT", "/me/library", { query: { uris: uris.join(",") } });
}
async removeFromLibrary(uris: string[]): Promise<void> {
await this.request("DELETE", "/me/library", { query: { uris: uris.join(",") } });
}
playlists(): Promise<SpotifyPlaylist[]> {
return this.collect("/me/playlists", { limit: 50 }, (raw) => asArray(raw?.items).map(parsePlaylist));
}
/** Only playlists the user owns or collaborates on list their items (403 otherwise). */
playlistItems(playlistId: string): Promise<SpotifyItem[]> {
return this.collect(`/playlists/${encodeURIComponent(playlistId)}/items`, { limit: 50, additional_types: "track,episode" },
(raw) => asArray(raw?.items).map((entry: any) => parseItem(entry?.item ?? entry?.track)));
}
savedTracks(): Promise<SpotifyItem[]> {
return this.collect("/me/tracks", { limit: 50 }, (raw) => asArray(raw?.items).map((entry: any) => parseItem(entry?.track)));
}
savedAlbums(): Promise<SpotifyAlbum[]> {
return this.collect("/me/albums", { limit: 50 }, (raw) => asArray(raw?.items).map((entry: any) => parseAlbum(entry?.album)));
}
albumTracks(albumId: string): Promise<SpotifyItem[]> {
return this.collect(`/albums/${encodeURIComponent(albumId)}/tracks`, { limit: 50 }, (raw) => asArray(raw?.items).map(parseItem));
}
followedArtists(): Promise<SpotifyArtist[]> {
// Cursor-paged, with the page wrapped in an "artists" object.
return this.collect("/me/following", { type: "artist", limit: 50 }, (raw) => asArray(raw?.artists?.items).map(parseArtist),
(raw) => str(raw?.artists?.next));
}
artistAlbums(artistId: string): Promise<SpotifyAlbum[]> {
return this.collect(`/artists/${encodeURIComponent(artistId)}/albums`, { include_groups: "album,single,compilation", limit: 10 },
(raw) => asArray(raw?.items).map(parseAlbum), undefined, 100);
}
/** Recently played tracks, newest first (one page: the API keeps only the last 50). */
async recentlyPlayed(): Promise<SpotifyPlayed[]> {
const raw = await this.request("GET", "/me/player/recently-played", { query: { limit: 50 } });
return asArray(raw?.items)
.map((entry: any) => {
const item = parseItem(entry?.track);
return item ? { item, contextUri: str(entry?.context?.uri) } : null;
})
.filter(isPresent);
}
async search(query: string, types: SpotifySearchType[], limit = 5): Promise<SpotifySearchResults> {
const raw = await this.request("GET", "/search", {
query: { q: query, type: types.join(","), limit: Math.max(1, Math.min(10, Math.round(limit))) },
});
return {
tracks: asArray(raw?.tracks?.items).map(parseItem).filter(isPresent),
albums: asArray(raw?.albums?.items).map(parseAlbum).filter(isPresent),
artists: asArray(raw?.artists?.items).map(parseArtist).filter(isPresent),
// Search results include nulls for playlists the API can no longer return.
playlists: asArray(raw?.playlists?.items).map(parsePlaylist).filter(isPresent),
};
}
/** Gather a paged listing by following its `next` links, up to maxItems. */
private async collect<T>(
path: string,
query: Query,
parse: (raw: any) => Array<T | null>,
nextOf: (raw: any) => string = (raw) => str(raw?.next),
maxItems = MAX_LIST_ITEMS,
): Promise<T[]> {
const items: T[] = [];
let raw = await this.request("GET", path, { query });
for (;;) {
for (const item of parse(raw)) if (item) items.push(item);
const next = nextOf(raw);
if (!next || items.length >= maxItems) return items.slice(0, maxItems);
raw = await this.request("GET", next);
}
}
/**
* One API call. `path` is relative to the API base, or an absolute `next`
* link from a page. Resolves to the parsed JSON body (null when empty);
* a 401 refreshes the token and retries once.
*/
private async request(method: string, path: string, options: { query?: Query; body?: unknown } = {}): Promise<any> {
const url = path.startsWith("https://") ? path : `${SPOTIFY_API_BASE}${path}${buildQuery(options.query)}`;
const headers: Record<string, string> = { Accept: "application/json" };
if (options.body !== undefined) headers["Content-Type"] = "application/json";
// A command without a body still sends an empty one: Spotify answers a
// PUT or POST with no Content-Length with 411.
const body = options.body !== undefined ? JSON.stringify(options.body) : method === "GET" ? undefined : "";
for (let attempt = 0; ; attempt++) {
const authorization = `Bearer ${await this.tokens.accessToken(attempt > 0)}`;
const response = await withTimeout(this.fetchImpl(url, { method, headers: { ...headers, Authorization: authorization }, body }));
const text = await withTimeout(response.text());
if (response.status === 401 && attempt === 0) continue;
if (response.status >= 200 && response.status < 300) {
if (!text.trim()) return null;
try {
return JSON.parse(text);
} catch {
// Commands answer 200 with a snapshot id or plain text; nothing to read.
return null;
}
}
throw apiError(response.status, text);
}
}
}
/** Form / query encoding (not URLSearchParams, which the NativeScript runtime mishandles). */
export function buildQuery(query: Query | undefined): string {
if (!query) return "";
const parts = Object.keys(query)
.filter((key) => query[key] !== undefined && query[key] !== "")
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(query[key]))}`);
return parts.length ? `?${parts.join("&")}` : "";
}
async function withTimeout<T>(promise: Promise<T>): Promise<T> {
let timer: ReturnType<typeof setTimeout> | null = null;
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new SpotifyApiError("Spotify didn't answer. Check the phone's connection.", 0)), HTTP_TIMEOUT_MS);
});
try {
return await Promise.race([promise, timeout]);
} catch (error) {
if (error instanceof SpotifyApiError) throw error;
throw new SpotifyApiError(`Can't reach Spotify: ${(error as Error)?.message ?? error}`, 0);
} finally {
if (timer) clearTimeout(timer);
}
}
/** A message for the glasses from Spotify's error body ({error: {status, message, reason}}). */
function apiError(status: number, body: string): SpotifyApiError {
let message = "";
let reason = "";
try {
const parsed = JSON.parse(body);
message = str(parsed?.error?.message ?? parsed?.error_description);
reason = str(parsed?.error?.reason);
} catch {
// Not JSON (a gateway error page).
}
switch (reason) {
case "NO_ACTIVE_DEVICE":
return new SpotifyApiError("Spotify isn't open on any device. Open Spotify on your phone, then try again.", status, reason);
case "PREMIUM_REQUIRED":
return new SpotifyApiError("Controlling Spotify playback needs Spotify Premium.", status, reason);
}
if (status === 401) return new SpotifyApiError("Spotify no longer accepts this sign-in. Sign in again from the Music app menu.", status, reason);
if (status === 403 && /registered|developer dashboard/i.test(message)) {
return new SpotifyApiError("This Spotify account isn't on the client ID's user list (Developer Dashboard > User Management).", status, reason);
}
if (status === 429) return new SpotifyApiError("Spotify is limiting requests; try again in a minute.", status, reason);
return new SpotifyApiError(message ? `Spotify: ${message}` : `Spotify error (HTTP ${status}).`, status, reason);
}
export function parsePlayback(raw: any): SpotifyPlayback {
const repeat = str(raw?.repeat_state);
const disallows = raw?.actions?.disallows;
return {
device: parseDevice(raw?.device),
playing: raw?.is_playing === true,
progressMs: num(raw?.progress_ms, 0),
shuffle: raw?.shuffle_state === true,
repeat: repeat === "context" || repeat === "track" ? repeat : "off",
contextUri: str(raw?.context?.uri),
item: parseItem(raw?.item),
playingType: str(raw?.currently_playing_type) || "unknown",
disallows: disallows && typeof disallows === "object" ? Object.keys(disallows).filter((key) => disallows[key] === true) : [],
};
}
export function parseItem(raw: any): SpotifyItem | null {
if (!raw || typeof raw !== "object" || typeof raw.uri !== "string" || !raw.uri) return null;
if (raw.type === "episode") {
const show = str(raw.show?.name);
return {
uri: raw.uri,
type: "episode",
name: str(raw.name),
artists: show || str(raw.show?.publisher),
album: show,
durationMs: num(raw.duration_ms, -1),
images: parseImages(raw.images?.length ? raw.images : raw.show?.images),
};
}
return {
uri: raw.uri,
type: "track",
name: str(raw.name),
artists: joinNames(raw.artists),
album: str(raw.album?.name),
durationMs: num(raw.duration_ms, -1),
images: parseImages(raw.album?.images),
};
}
export function parseDevice(raw: any): SpotifyDevice | null {
if (!raw || typeof raw !== "object") return null;
const volume = raw.volume_percent;
return {
id: str(raw.id),
name: str(raw.name),
type: str(raw.type),
active: raw.is_active === true,
restricted: raw.is_restricted === true,
volumePercent: typeof volume === "number" && Number.isFinite(volume) ? volume : -1,
supportsVolume: raw.supports_volume === true,
};
}
function parsePlaylist(raw: any): SpotifyPlaylist | null {
if (!raw || typeof raw !== "object" || !raw.id) return null;
return {
id: str(raw.id),
uri: str(raw.uri) || `spotify:playlist:${raw.id}`,
name: str(raw.name),
ownerId: str(raw.owner?.id),
ownerName: str(raw.owner?.display_name) || str(raw.owner?.id),
collaborative: raw.collaborative === true,
// `items` replaced the deprecated `tracks` summary in 2026.
total: num(raw.items?.total ?? raw.tracks?.total, -1),
};
}
function parseAlbum(raw: any): SpotifyAlbum | null {
if (!raw || typeof raw !== "object" || !raw.id) return null;
return { id: str(raw.id), uri: str(raw.uri) || `spotify:album:${raw.id}`, name: str(raw.name), artists: joinNames(raw.artists) };
}
function parseArtist(raw: any): SpotifyArtist | null {
if (!raw || typeof raw !== "object" || !raw.id) return null;
return { id: str(raw.id), uri: str(raw.uri) || `spotify:artist:${raw.id}`, name: str(raw.name) };
}
function parseImages(raw: any): SpotifyImage[] {
return asArray(raw)
.filter((image: any) => image && typeof image.url === "string" && image.url)
.map((image: any) => ({ url: image.url, width: num(image.width, 0), height: num(image.height, 0) }));
}
function joinNames(raw: any): string {
return asArray(raw).map((entry: any) => str(entry?.name)).filter(Boolean).join(", ");
}
function asArray(value: unknown): any[] {
return Array.isArray(value) ? value : [];
}
function str(value: unknown): string {
return typeof value === "string" ? value : "";
}
function num(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
function isPresent<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
+63
View File
@@ -0,0 +1,63 @@
import { fetchTextWithUserAgent } from "../util/http";
import { downloadBinary } from "./binary-http.ios";
import { grayImageFromPacket, PHOTO_TONE } from "./image-files";
import { fromData, toData } from "./kotlin-data";
import type { WebSignIn } from "./spotify-auth";
import { SpotifyService } from "./spotify-service";
declare const FaceclawAppleMusic: any;
declare const FaceclawCrypto: any;
declare const FaceclawGraphics: any;
declare const FaceclawKitIosProtocol: any;
declare const FaceclawWebSignIn: any;
const ART_DOWNLOAD_TIMEOUT_MS = 10_000;
/** Sign-in in the system browser sheet, which FaceclawWebSignIn closes once the loopback redirect arrives. */
const webSignIn: WebSignIn = {
createPkce: () => {
// 64 URL-safe characters (RFC 7636 allows 43..128).
const verifier = String(FaceclawCrypto.randomBase64Url(48));
return { verifier, challenge: String(FaceclawCrypto.sha256Base64Url(verifier)) };
},
randomState: () => String(FaceclawCrypto.randomBase64Url(16)),
open: (authorizeUrl, port, path) =>
new Promise<string>((resolve, reject) => {
FaceclawWebSignIn.shared().signInPortPathCompletion(authorizeUrl, port, path, (redirectUrl: string | null, error: string | null) => {
if (redirectUrl) resolve(String(redirectUrl));
else reject(new Error(String(error || "Sign-in failed")));
});
}),
cancel: () => FaceclawWebSignIn.shared().cancel(),
};
let protocol: any = null;
let service: SpotifyService | null = null;
/** The Spotify service, created on first use (main thread only: it owns timers and the sign-in sheet). */
export function spotifyService(): SpotifyService | null {
service ??= new SpotifyService({
fetch: (url, init) => fetchTextWithUserAgent(url, init),
webSignIn,
download: async (url) => {
const response = await downloadBinary(url, ART_DOWNLOAD_TIMEOUT_MS);
return response.status === 200 ? response.bytes : null;
},
decodeArt: (bytes, maxSize) => {
const packet = FaceclawGraphics.bgraPacketFromImageDataMaxSize(toData(bytes), Math.round(maxSize));
if (!packet) return null;
// The shared Kotlin tone curve and dither, as for Apple Music's art.
protocol ??= FaceclawKitIosProtocol.new();
return grayImageFromPacket(fromData(protocol.grayPacketBgraGammaDither(packet, PHOTO_TONE.gamma, PHOTO_TONE.dither)));
},
// FaceclawAppleMusic's system output volume needs no media-library access.
systemVolume: {
get: () => {
const volume = Number(FaceclawAppleMusic.shared().volumePercent());
return Number.isFinite(volume) ? Math.max(-1, Math.min(100, Math.round(volume))) : -1;
},
set: (percent) => FaceclawAppleMusic.shared().setVolumePercent(Math.max(0, Math.min(100, Math.round(percent)))),
},
});
return service;
}
+9
View File
@@ -0,0 +1,9 @@
import type { SpotifyService } from "./spotify-service";
/**
* Spotify through its Web API is wired up on iOS only (spotify.ios.ts): on
* Android, Spotify publishes a media session the Music app already controls.
*/
export function spotifyService(): SpotifyService | null {
return null;
}