mirror of
https://git.undefined-dev.fr/Blendman974/faceclaw.git
synced 2026-11-19 21:03:09 +00:00
Use Spotify API if an API key is provided
This commit is contained in:
1 parent
f47d82b871
commit
49ea8a7d74
18 files changed
+736
-39
No files matched your search
@@ -6,8 +6,9 @@
|
||||
* Make BLE benchmark work on iOS
|
||||
* Ensure connection is re-set to 2M on reconnect
|
||||
* Add support for embedded icons and custom layouts in Android notifications
|
||||
* iOS: Notifications are selectable via the task switcher
|
||||
* Port the Developer app's resource-usage monitor and various test pages to iOS
|
||||
* iOS: Notifications are selectable via the task switcher
|
||||
* Android: Optionally sign in to Spotify's Web API for library browsing and other features
|
||||
|
||||
## 0.8.5 - 2026-10-25
|
||||
|
||||
|
||||
@@ -53,7 +53,9 @@ type FocusColumn = "actions" | "playlist";
|
||||
/**
|
||||
* Music controller app: metadata + album art + transport controls for the
|
||||
* active Android media session (any player that publishes one) or, on iOS,
|
||||
* the Apple Music system player or Spotify (signed in from the window menu),
|
||||
* the Apple Music system player; on both, Spotify through its Web API once
|
||||
* signed in from the window menu (optional on Android, where it adds
|
||||
* library browsing, shuffle / repeat / like and Spotify on other devices),
|
||||
* plus the player's queue when it exposes one
|
||||
* (scroll to a track, click to jump). With no session, the front page lists
|
||||
* the apps whose library can be browsed (click one to open its
|
||||
@@ -525,19 +527,21 @@ export function createMusicAppWindow(options: InProcessAppOptions): InProcessWin
|
||||
iconLetter: "M",
|
||||
icon: "music",
|
||||
closeable: true,
|
||||
// Music settings choose among Android media apps; iOS has Apple Music, plus Spotify's sign-in here.
|
||||
// Music settings choose among Android media apps (iOS has Apple Music
|
||||
// alone); Spotify's sign-in is optional on Android, where its media
|
||||
// session works without it.
|
||||
menuItems: () => {
|
||||
if (!global.isIOS) {
|
||||
return [{
|
||||
const spotify = spotifyService();
|
||||
return [
|
||||
...(global.isIOS ? [] : [{
|
||||
label: "Music settings",
|
||||
onSelect: (ctx) => {
|
||||
onSelect: (ctx: LayerContext) => {
|
||||
ctx.stack.pop();
|
||||
ctx.stack.push(new MusicSettingsLayer());
|
||||
},
|
||||
}];
|
||||
}
|
||||
const spotify = spotifyService();
|
||||
return spotify ? [spotifyMenuItem(spotify)] : [];
|
||||
}]),
|
||||
...(spotify ? [spotifyMenuItem(spotify)] : []),
|
||||
];
|
||||
},
|
||||
actions: options.actions,
|
||||
baseLayer: new MusicRootLayer(musicLayer),
|
||||
|
||||
@@ -8,25 +8,31 @@ import { submenuItem, TextPageLayer, type MenuItem } from "../../ui/menu";
|
||||
import { WindowMenuLayer } from "../../ui/window-menu";
|
||||
import { TextViewerLayer } from "../files/text-viewer";
|
||||
|
||||
const SETUP_INTRO = global.isIOS
|
||||
? "Faceclaw controls Spotify through Spotify's Web API, which needs a Spotify developer app of your own. Creating one is free; Spotify requires its owner to have Premium, and controlling playback needs Premium too."
|
||||
: "Faceclaw already shows and controls Spotify on this phone, like any music app. Signing in to Spotify's Web API is optional and adds browsing your Spotify library, playing from Spotify by voice, shuffle / repeat / like, and Spotify playing on your other devices. It needs a Spotify developer app of your own: creating one is free, Spotify requires its owner to have Premium, and controlling playback through it needs Premium too.";
|
||||
|
||||
const SETUP_HELP = [
|
||||
"Faceclaw controls Spotify through Spotify's Web API, which needs a Spotify developer app of your own. Creating one is free; Spotify requires its owner to have Premium, and controlling playback needs Premium too.",
|
||||
SETUP_INTRO,
|
||||
"",
|
||||
`1. On a computer, open ${SPOTIFY_DASHBOARD_URL.replace("https://", "")} and sign in with your Spotify account.`,
|
||||
"2. Create an app. Any name and description will do.",
|
||||
`3. Add this Redirect URI exactly: ${SPOTIFY_REDIRECT_URI}`,
|
||||
"4. Under \"Which API/SDKs are you planning to use?\", tick Web API, then save.",
|
||||
"5. Open the app's settings, copy its Client ID, and enter it as Client ID here.",
|
||||
"6. Choose Sign in, then finish on your phone: Faceclaw opens Spotify's sign-in page there.",
|
||||
"6. Choose Sign in, then finish on your phone: Faceclaw opens Spotify's sign-in page there (once Faceclaw is open on the phone, if it was in the background).",
|
||||
"",
|
||||
"Spotify plays on whichever of your devices is open (this phone, a computer, a speaker). To start music when nothing is playing, Spotify must be open on one of them.",
|
||||
"",
|
||||
"Others can sign in with your client ID once you add their Spotify email under User Management in the dashboard (up to five people).",
|
||||
].join("\n");
|
||||
|
||||
/** The Music app menu's Spotify row (iOS): sign in, sign out, client ID, setup help. */
|
||||
/** The Music app menu's Spotify row: sign in, sign out, client ID, setup help. */
|
||||
export function spotifyMenuItem(service: SpotifyService): MenuItem {
|
||||
return submenuItem("Spotify", (ctx) => ctx.stack.push(new SpotifyMenuLayer(service)), {
|
||||
description: "Sign in to Spotify to show and control it from the glasses.",
|
||||
description: global.isIOS
|
||||
? "Sign in to Spotify to show and control it from the glasses."
|
||||
: "Optional: sign in to Spotify to browse its library and play from it by voice.",
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "./media-types";
|
||||
import { spotifyService } from "./spotify.ios";
|
||||
import type { SpotifyLibrary } from "./spotify-library";
|
||||
import { SPOTIFY_PACKAGE } from "./spotify-player";
|
||||
import { SPOTIFY_IOS_BUNDLE_ID } from "./spotify-player";
|
||||
|
||||
export type { MediaBrowseItem, MediaBrowserApp } from "./media-types";
|
||||
|
||||
@@ -85,7 +85,7 @@ export class IosMediaBrowserBridge implements MediaBrowserBridge {
|
||||
|
||||
connect(app: MediaBrowserApp): Promise<string> {
|
||||
this.disconnect();
|
||||
const library = app.packageName === SPOTIFY_PACKAGE ? this.spotify() : this.appleMusic;
|
||||
const library = app.packageName === SPOTIFY_IOS_BUNDLE_ID ? this.spotify() : this.appleMusic;
|
||||
if (!library) return Promise.reject(new Error(`${app.appName} can't be browsed`));
|
||||
this.current = library;
|
||||
return library.connect(app);
|
||||
|
||||
@@ -2,6 +2,9 @@ import { Utils } from "@nativescript/core";
|
||||
import { ignoredMediaPackages, isMediaAppEnabled, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
|
||||
import { onSettingsStoreChanged } from "./settings-store";
|
||||
import { parseMediaBrowseItems, type MediaBrowseItem, type MediaBrowserApp, type MediaBrowserBridge } from "./media-types";
|
||||
import { spotifyService } from "./spotify";
|
||||
import type { SpotifyLibrary } from "./spotify-library";
|
||||
import { SPOTIFY_ANDROID_PACKAGE } from "./spotify-player";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
@@ -157,4 +160,54 @@ export class FaceclawMediaBrowserBridge implements MediaBrowserBridge {
|
||||
}
|
||||
}
|
||||
|
||||
export const mediaBrowserBridge: MediaBrowserBridge = new FaceclawMediaBrowserBridge();
|
||||
/**
|
||||
* The Android libraries: apps' media browser services, with Spotify's
|
||||
* library from its Web API instead. Spotify's own browser service admits
|
||||
* only allowlisted callers (Android Auto, Wear, Assistant), so connecting to
|
||||
* it always fails; signed in, its row opens the Web API library, and signed
|
||||
* out, opening it says how to sign in. Signed in with Spotify not installed,
|
||||
* the library is still offered (it plays on the user's other devices).
|
||||
*/
|
||||
export class AndroidMediaBrowserBridge implements MediaBrowserBridge {
|
||||
private current: MediaBrowserBridge | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly services: MediaBrowserBridge,
|
||||
private readonly spotify: () => SpotifyLibrary | null,
|
||||
private readonly isEnabled: (packageName: string) => boolean = isMediaAppEnabled,
|
||||
) {}
|
||||
|
||||
listBrowsableApps(refresh = false): MediaBrowserApp[] {
|
||||
const apps = this.services.listBrowsableApps(refresh);
|
||||
const library = this.spotify();
|
||||
if (!library || apps.some((app) => app.packageName === SPOTIFY_ANDROID_PACKAGE) || !this.isEnabled(SPOTIFY_ANDROID_PACKAGE)) {
|
||||
return apps;
|
||||
}
|
||||
return [...apps, ...library.listBrowsableApps()];
|
||||
}
|
||||
|
||||
connect(app: MediaBrowserApp): Promise<string> {
|
||||
this.disconnect();
|
||||
const library = app.packageName === SPOTIFY_ANDROID_PACKAGE ? this.spotify() : null;
|
||||
this.current = library ?? this.services;
|
||||
return this.current.connect(library ? library.app : 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 AndroidMediaBrowserBridge(
|
||||
new FaceclawMediaBrowserBridge(),
|
||||
() => spotifyService()?.library ?? null,
|
||||
);
|
||||
@@ -12,11 +12,14 @@ import {
|
||||
type MediaPlaybackState,
|
||||
type MediaQueueItem,
|
||||
} from "./media-types";
|
||||
import { spotifyService } from "./spotify";
|
||||
import { SPOTIFY_ANDROID_PACKAGE, type SpotifyPlayer } from "./spotify-player";
|
||||
|
||||
declare const com: any;
|
||||
|
||||
export type { MediaControllerState, MediaPlaybackState, MediaQueueItem } from "./media-types";
|
||||
|
||||
/** Android media sessions (any player that publishes one), through FaceclawMediaController. */
|
||||
export class FaceclawMediaControllerBridge implements MediaControllerBridge {
|
||||
readonly accessPrompt = "Notification access is required to control Android media sessions. Tap to open settings.";
|
||||
readonly accessLabel = "Notification access needed";
|
||||
@@ -215,4 +218,251 @@ function normalizePlaybackState(value: string): MediaPlaybackState {
|
||||
}
|
||||
}
|
||||
|
||||
export const mediaControllerBridge: MediaControllerBridge = new FaceclawMediaControllerBridge();
|
||||
export type AndroidMediaSource = "session" | "spotify";
|
||||
|
||||
/**
|
||||
* Which to follow: the media session (any player, Spotify included when it
|
||||
* runs on this phone) or Spotify's Web API player (signed in; it also sees
|
||||
* Spotify playing on a computer or speaker). The one playing; with both
|
||||
* playing, the session when it is Spotify's own (the same playback), else the
|
||||
* current choice (no flapping); with neither, a Spotify session, then the one
|
||||
* that played last, then whichever has something. Without notification
|
||||
* access the session shows its access prompt unless Spotify has something.
|
||||
*/
|
||||
export function chooseAndroidMediaSource(
|
||||
current: AndroidMediaSource,
|
||||
session: MediaControllerState,
|
||||
spotify: MediaControllerState | null,
|
||||
sessionLastPlayingAtMs: number,
|
||||
spotifyLastPlayingAtMs: number,
|
||||
): AndroidMediaSource {
|
||||
if (!spotify?.accessEnabled) return "session";
|
||||
if (!session.accessEnabled) return spotify.available ? "spotify" : "session";
|
||||
const sessionIsSpotify = session.packageName === SPOTIFY_ANDROID_PACKAGE;
|
||||
const sessionPlaying = session.playbackState === "playing";
|
||||
const spotifyPlaying = spotify.playbackState === "playing";
|
||||
if (sessionPlaying && spotifyPlaying) return sessionIsSpotify ? "session" : current;
|
||||
if (sessionPlaying) return "session";
|
||||
if (spotifyPlaying) return "spotify";
|
||||
if (sessionIsSpotify && session.available) return "session";
|
||||
if (sessionLastPlayingAtMs !== spotifyLastPlayingAtMs) {
|
||||
return spotifyLastPlayingAtMs > sessionLastPlayingAtMs ? "spotify" : "session";
|
||||
}
|
||||
return session.available || !spotify.available ? "session" : "spotify";
|
||||
}
|
||||
|
||||
/**
|
||||
* The Android Music bridge: media sessions, plus Spotify's Web API once
|
||||
* signed in (optional). Spotify playing on this phone stays the session's:
|
||||
* its state, art, queue and transport come from the session (instant, no
|
||||
* quota), and the Web API adds what the session lacks: shuffle / repeat /
|
||||
* like rows and the volume of a Spotify Connect speaker or computer. Spotify
|
||||
* playing on another device, with no session here, follows the Web API player.
|
||||
*/
|
||||
export class AndroidMediaControllerBridge implements MediaControllerBridge {
|
||||
readonly accessPrompt: string;
|
||||
readonly accessLabel: string;
|
||||
readonly accessAction: string;
|
||||
private source: AndroidMediaSource = "session";
|
||||
private sessionLastPlayingAtMs = 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;
|
||||
/** The player the last getQueue listed, so a jump goes to the same one. */
|
||||
private queueSource: MediaControllerBridge | null = null;
|
||||
/** A Spotify session's item and play state, to re-read the Web API when they change. */
|
||||
private spotifySessionKey = "";
|
||||
|
||||
constructor(
|
||||
private readonly session: MediaControllerBridge,
|
||||
private readonly spotify: () => SpotifyPlayer | null,
|
||||
private readonly now: () => number = Date.now,
|
||||
) {
|
||||
this.accessPrompt = session.accessPrompt;
|
||||
this.accessLabel = session.accessLabel;
|
||||
this.accessAction = session.accessAction;
|
||||
}
|
||||
|
||||
get skipRebuildsQueue(): boolean {
|
||||
return (this.queueSource ?? this.active()).skipRebuildsQueue;
|
||||
}
|
||||
|
||||
onStateChange(listener: (state: MediaControllerState) => void): () => void {
|
||||
if (!this.listeners.size) {
|
||||
const spotify = this.spotify();
|
||||
this.unsubscribeSources = [
|
||||
this.session.onStateChange((state) => this.sessionChanged(state)),
|
||||
...(spotify ? [spotify.onStateChange(() => this.emit())] : []),
|
||||
];
|
||||
}
|
||||
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 session = this.session.snapshot();
|
||||
const spotify = this.spotify()?.snapshot() ?? null;
|
||||
this.select(session, spotify);
|
||||
const state = this.source === "spotify" && spotify ? spotify : withSpotifyExtras(session, spotify);
|
||||
// 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,
|
||||
artVersion: this.artVersion,
|
||||
// A Spotify command can fail while the session is the one shown (playing from the Spotify library).
|
||||
notice: spotify?.notice || state.notice || "",
|
||||
};
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
await this.session.start();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.session.stop();
|
||||
}
|
||||
|
||||
playPause(): Promise<void> {
|
||||
return this.active().playPause();
|
||||
}
|
||||
|
||||
skipNext(): Promise<void> {
|
||||
return this.active().skipNext();
|
||||
}
|
||||
|
||||
skipPrevious(): Promise<void> {
|
||||
return this.active().skipPrevious();
|
||||
}
|
||||
|
||||
/** Notification access (what requestAccess opens); Spotify signs in from the Music menu. */
|
||||
hasAccess(): boolean {
|
||||
return this.session.hasAccess();
|
||||
}
|
||||
|
||||
requestAccess(): Promise<boolean> {
|
||||
return this.session.requestAccess();
|
||||
}
|
||||
|
||||
skipToQueueItem(id: number): Promise<void> {
|
||||
return (this.queueSource ?? this.active()).skipToQueueItem(id);
|
||||
}
|
||||
|
||||
/** Spotify's own volume logic (a Connect device's volume, else this phone's) whenever Spotify is shown. */
|
||||
getMediaVolumePercent(): number {
|
||||
return this.volumeSource().getMediaVolumePercent();
|
||||
}
|
||||
|
||||
setMediaVolumePercent(volumePercent: number): void {
|
||||
this.volumeSource().setMediaVolumePercent(volumePercent);
|
||||
}
|
||||
|
||||
getAlbumArt(maxSize: number): GrayImage | null {
|
||||
return this.active().getAlbumArt(maxSize);
|
||||
}
|
||||
|
||||
/** The session's queue; for a Spotify session that lists none, the Web API's. */
|
||||
getQueue(): MediaQueueItem[] {
|
||||
const active = this.active();
|
||||
const queue = active.getQueue();
|
||||
const spotify = this.spotifyExtras();
|
||||
if (queue.length || active !== this.session || !spotify) {
|
||||
this.queueSource = active;
|
||||
return queue;
|
||||
}
|
||||
this.queueSource = spotify;
|
||||
return spotify.getQueue();
|
||||
}
|
||||
|
||||
/** Spotify's actions (shown with a Spotify session too) go to the Web API player; any others to the session. */
|
||||
async sendCustomAction(action: string): Promise<void> {
|
||||
const spotify = this.spotify();
|
||||
if (spotify && spotify.snapshot().customActions?.some((custom) => custom.action === action)) {
|
||||
await spotify.sendCustomAction(action);
|
||||
} else {
|
||||
await this.session.sendCustomAction?.(action);
|
||||
}
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
await this.spotify()?.refresh();
|
||||
}
|
||||
|
||||
private active(): MediaControllerBridge {
|
||||
const spotify = this.spotify();
|
||||
this.select(this.session.snapshot(), spotify?.snapshot() ?? null);
|
||||
return this.source === "spotify" && spotify ? spotify : this.session;
|
||||
}
|
||||
|
||||
/** The signed-in Web API player when it describes what the session shows (Spotify's own session); else null. */
|
||||
private spotifyExtras(): SpotifyPlayer | null {
|
||||
const spotify = this.spotify();
|
||||
if (!spotify || this.session.snapshot().packageName !== SPOTIFY_ANDROID_PACKAGE) return null;
|
||||
return spotify.snapshot().available ? spotify : null;
|
||||
}
|
||||
|
||||
private volumeSource(): MediaControllerBridge {
|
||||
const active = this.active();
|
||||
return active === this.session ? this.spotifyExtras() ?? this.session : active;
|
||||
}
|
||||
|
||||
private select(session: MediaControllerState, spotify: MediaControllerState | null): void {
|
||||
if (session.playbackState === "playing") this.sessionLastPlayingAtMs = this.now();
|
||||
this.source = chooseAndroidMediaSource(this.source, session, spotify, this.sessionLastPlayingAtMs,
|
||||
this.spotify()?.lastPlayingAtMs ?? 0);
|
||||
}
|
||||
|
||||
private sessionChanged(state: MediaControllerState): void {
|
||||
// Spotify's session changed track or started / stopped: re-read the Web
|
||||
// API now, so its rows (like this song, shuffle) follow at once rather
|
||||
// than at the next poll. Signed out, the player skips the request.
|
||||
const key = state.packageName === SPOTIFY_ANDROID_PACKAGE ? `${state.title}\n${state.playbackState}` : "";
|
||||
if (key !== this.spotifySessionKey) {
|
||||
this.spotifySessionKey = key;
|
||||
if (key) void this.spotify()?.refresh();
|
||||
}
|
||||
this.emit();
|
||||
}
|
||||
|
||||
/** Forward every source update: each drops its own repeats, and Spotify also signals queue changes. */
|
||||
private emit(): void {
|
||||
if (!this.listeners.size) return;
|
||||
const state = this.snapshot();
|
||||
for (const listener of this.listeners) listener(state);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spotify's session state plus what only the Web API knows: its custom rows
|
||||
* and, when it plays elsewhere, the device ("Spotify · Kitchen"). "Like
|
||||
* song" names the Web API's current item, so it is left out until both agree
|
||||
* on the track (the API lags a skip by up to a poll).
|
||||
*/
|
||||
export function withSpotifyExtras(session: MediaControllerState, spotify: MediaControllerState | null): MediaControllerState {
|
||||
if (!spotify?.available || session.packageName !== SPOTIFY_ANDROID_PACKAGE) return session;
|
||||
const sameItem = spotify.title === session.title;
|
||||
const actions = (spotify.customActions ?? []).filter((custom) => sameItem || custom.action !== "like");
|
||||
return {
|
||||
...session,
|
||||
appName: sameItem ? spotify.appName : session.appName,
|
||||
customActions: [...(session.customActions ?? []), ...actions],
|
||||
};
|
||||
}
|
||||
|
||||
const sessionBridge = new FaceclawMediaControllerBridge();
|
||||
|
||||
export const mediaControllerBridge: MediaControllerBridge = new AndroidMediaControllerBridge(
|
||||
sessionBridge,
|
||||
() => spotifyService()?.player ?? null,
|
||||
);
|
||||
@@ -3,8 +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 and
|
||||
* Spotify through its Web API.
|
||||
* counterparts drive Apple Music through the MediaPlayer framework. Both
|
||||
* add Spotify through its Web API once signed in (spotify-*.ts).
|
||||
*/
|
||||
|
||||
/** The player behind the iOS bridges: the system Music app. */
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import type { MediaBrowseItem, MediaBrowserApp, MediaBrowserBridge } from "./media-types";
|
||||
import { SPOTIFY_APP_NAME, SPOTIFY_PACKAGE, type SpotifyPlayer } from "./spotify-player";
|
||||
import { SPOTIFY_APP_NAME, 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 },
|
||||
@@ -17,6 +15,8 @@ const TRACK_CONTEXT_SEPARATOR = "|";
|
||||
|
||||
export type SpotifyLibraryDeps = {
|
||||
client: SpotifyClient;
|
||||
/** Spotify's app id on this platform, which names the library in the browse picker. */
|
||||
packageName: string;
|
||||
player: SpotifyPlayer;
|
||||
isSignedIn(): boolean;
|
||||
/** The signed-in user's id (Liked Songs' context URI names it). */
|
||||
@@ -39,15 +39,20 @@ export class SpotifyLibrary implements MediaBrowserBridge {
|
||||
/** Bumped on every connect/disconnect; answers to older requests are dropped. */
|
||||
private generation = 0;
|
||||
|
||||
constructor(private readonly deps: SpotifyLibraryDeps) {}
|
||||
/** This library's row in the browse picker. */
|
||||
readonly app: MediaBrowserApp;
|
||||
|
||||
constructor(private readonly deps: SpotifyLibraryDeps) {
|
||||
this.app = { packageName: deps.packageName, serviceClass: "", appName: SPOTIFY_APP_NAME };
|
||||
}
|
||||
|
||||
listBrowsableApps(): MediaBrowserApp[] {
|
||||
return this.deps.isSignedIn() ? [SPOTIFY_BROWSER_APP] : [];
|
||||
return this.deps.isSignedIn() ? [this.app] : [];
|
||||
}
|
||||
|
||||
connect(app: MediaBrowserApp): Promise<string> {
|
||||
this.disconnect();
|
||||
if (app.packageName !== SPOTIFY_PACKAGE) return Promise.reject(new Error("Not a Spotify library"));
|
||||
if (app.packageName !== this.app.packageName) 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");
|
||||
|
||||
@@ -18,8 +18,10 @@ import {
|
||||
} 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";
|
||||
/** Spotify's iOS bundle id: the player's packageName in the media state on iOS. */
|
||||
export const SPOTIFY_IOS_BUNDLE_ID = "com.spotify.client";
|
||||
/** Spotify's Android package: its media session's owner, which the Web API player reports too. */
|
||||
export const SPOTIFY_ANDROID_PACKAGE = "com.spotify.music";
|
||||
|
||||
/**
|
||||
* Poll intervals while something listens. The Web API has no push channel, so
|
||||
@@ -46,6 +48,8 @@ const REPEAT_LABEL: Record<SpotifyRepeat, string> = { off: "Repeat: off", contex
|
||||
|
||||
export type SpotifyPlayerDeps = {
|
||||
client: SpotifyClient;
|
||||
/** The state's packageName: Spotify's app id on this platform. */
|
||||
packageName: string;
|
||||
isSignedIn(): boolean;
|
||||
/** Fetch an album-art image's encoded bytes; null on failure. */
|
||||
download(url: string): Promise<Uint8Array | null>;
|
||||
@@ -119,7 +123,7 @@ export class SpotifyPlayer implements MediaControllerBridge {
|
||||
return {
|
||||
...DEFAULT_MEDIA_STATE,
|
||||
accessEnabled: true,
|
||||
packageName: SPOTIFY_PACKAGE,
|
||||
packageName: this.deps.packageName,
|
||||
appName: SPOTIFY_APP_NAME,
|
||||
status: "Nothing is playing on Spotify.",
|
||||
notice,
|
||||
@@ -131,7 +135,7 @@ export class SpotifyPlayer implements MediaControllerBridge {
|
||||
const state: MediaControllerState = {
|
||||
available: true,
|
||||
accessEnabled: true,
|
||||
packageName: SPOTIFY_PACKAGE,
|
||||
packageName: this.deps.packageName,
|
||||
appName: spotifyAppName(playback.device),
|
||||
playbackState: playback.playing ? "playing" : "paused",
|
||||
title: item?.name ?? (playback.playingType === "ad" ? "Advertisement" : ""),
|
||||
|
||||
@@ -17,8 +17,10 @@ import { SpotifyClient, type SpotifyFetch, type SpotifySearchType } from "./spot
|
||||
/** 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). */
|
||||
/** What the platform supplies (spotify.ios.ts, spotify.ts). */
|
||||
export type SpotifyPlatform = {
|
||||
/** Spotify's app id on this platform (SPOTIFY_IOS_BUNDLE_ID / SPOTIFY_ANDROID_PACKAGE). */
|
||||
packageName: string;
|
||||
fetch: SpotifyFetch;
|
||||
webSignIn: WebSignIn;
|
||||
download(url: string): Promise<Uint8Array | null>;
|
||||
@@ -48,6 +50,7 @@ export class SpotifyService {
|
||||
this.client = new SpotifyClient(platform.fetch, new SpotifySession(platform.fetch));
|
||||
this.player = new SpotifyPlayer({
|
||||
client: this.client,
|
||||
packageName: platform.packageName,
|
||||
isSignedIn,
|
||||
download: (url) => platform.download(url),
|
||||
decodeArt: (bytes, maxSize) => platform.decodeArt(bytes, maxSize),
|
||||
@@ -55,6 +58,7 @@ export class SpotifyService {
|
||||
});
|
||||
this.library = new SpotifyLibrary({
|
||||
client: this.client,
|
||||
packageName: platform.packageName,
|
||||
player: this.player,
|
||||
isSignedIn,
|
||||
userId: () => readSpotifyAccount()?.userId ?? "",
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { SPOTIFY_IOS_BUNDLE_ID } from "./spotify-player";
|
||||
import { SpotifyService } from "./spotify-service";
|
||||
|
||||
declare const FaceclawAppleMusic: any;
|
||||
@@ -37,6 +38,7 @@ 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({
|
||||
packageName: SPOTIFY_IOS_BUNDLE_ID,
|
||||
fetch: (url, init) => fetchTextWithUserAgent(url, init),
|
||||
webSignIn,
|
||||
download: async (url) => {
|
||||
|
||||
+119
-4
@@ -1,9 +1,124 @@
|
||||
import type { SpotifyService } from "./spotify-service";
|
||||
import { Application, Utils } from "@nativescript/core";
|
||||
import { fetchTextWithUserAgent } from "../util/http";
|
||||
import { downloadBinary } from "./binary-http";
|
||||
import { grayImageFromPacket, PHOTO_TONE } from "./image-files";
|
||||
import { copyToJavaByteBuffer } from "./java-direct-buffer";
|
||||
import type { WebSignIn } from "./spotify-auth";
|
||||
import { SPOTIFY_ANDROID_PACKAGE } from "./spotify-player";
|
||||
import { SpotifyService } from "./spotify-service";
|
||||
|
||||
declare const android: any;
|
||||
declare const com: any;
|
||||
|
||||
const ART_DOWNLOAD_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** The sign-in's listener proxy, held while Java may still call it. */
|
||||
let signInListener: unknown = null;
|
||||
|
||||
/** Faceclaw's activity is in front, so it may open the browser (Android blocks background activity starts). */
|
||||
function foregroundActivity(): any {
|
||||
return Application.suspended ? null : Application.android?.foregroundActivity ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Sign-in in the phone's browser, with FaceclawWebSignIn catching the
|
||||
* loopback redirect. A sign-in started from the glasses while Faceclaw is in
|
||||
* the background opens the page when Faceclaw next comes to the front, as on
|
||||
* iOS.
|
||||
*/
|
||||
const webSignIn: WebSignIn = {
|
||||
createPkce: () => {
|
||||
// 64 URL-safe characters (RFC 7636 allows 43..128).
|
||||
const verifier = String(com.faceclaw.app.FaceclawWebSignIn.randomBase64Url(48));
|
||||
return { verifier, challenge: String(com.faceclaw.app.FaceclawWebSignIn.sha256Base64Url(verifier)) };
|
||||
},
|
||||
randomState: () => String(com.faceclaw.app.FaceclawWebSignIn.randomBase64Url(16)),
|
||||
open: (authorizeUrl, port, path) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const native = com.faceclaw.app.FaceclawWebSignIn.shared();
|
||||
let onResume: ((args: any) => void) | null = null;
|
||||
const stopWaiting = () => {
|
||||
if (onResume) Application.off(Application.resumeEvent, onResume);
|
||||
onResume = null;
|
||||
};
|
||||
const listener = new com.faceclaw.app.FaceclawWebSignInListener({
|
||||
onFinished: (redirectUrl: string | null, error: string | null) => {
|
||||
if (signInListener === listener) signInListener = null;
|
||||
stopWaiting();
|
||||
if (redirectUrl) resolve(String(redirectUrl));
|
||||
else reject(new Error(String(error || "Sign-in failed")));
|
||||
},
|
||||
});
|
||||
const startError = native.start(port, path, listener);
|
||||
if (startError) {
|
||||
reject(new Error(String(startError)));
|
||||
return;
|
||||
}
|
||||
signInListener = listener;
|
||||
const present = (activity: any) => {
|
||||
stopWaiting();
|
||||
const openError = native.openBrowser(activity, authorizeUrl);
|
||||
if (openError) native.fail(String(openError));
|
||||
};
|
||||
const activity = foregroundActivity();
|
||||
if (activity) {
|
||||
present(activity);
|
||||
return;
|
||||
}
|
||||
onResume = (args: any) => present(args?.activity ?? args?.android ?? Utils.android.getApplicationContext());
|
||||
Application.on(Application.resumeEvent, onResume);
|
||||
}),
|
||||
cancel: () => com.faceclaw.app.FaceclawWebSignIn.shared().cancel(),
|
||||
};
|
||||
|
||||
/** The phone's media-stream volume, for Spotify playing on this phone (as the session bridge reports it). */
|
||||
function audioManager(): any {
|
||||
return Utils.android.getApplicationContext()?.getSystemService(android.content.Context.AUDIO_SERVICE) ?? null;
|
||||
}
|
||||
|
||||
const systemVolume = {
|
||||
get: (): number => {
|
||||
const audio = audioManager();
|
||||
if (!audio) return -1;
|
||||
const max = Number(audio.getStreamMaxVolume(android.media.AudioManager.STREAM_MUSIC));
|
||||
if (max <= 0) return 0;
|
||||
return Math.max(0, Math.min(100, Math.round((Number(audio.getStreamVolume(android.media.AudioManager.STREAM_MUSIC)) * 100) / max)));
|
||||
},
|
||||
set: (percent: number): void => {
|
||||
const audio = audioManager();
|
||||
if (!audio) return;
|
||||
const max = Number(audio.getStreamMaxVolume(android.media.AudioManager.STREAM_MUSIC));
|
||||
const volume = Math.round((Math.max(0, Math.min(100, percent)) * max) / 100);
|
||||
audio.setStreamVolume(android.media.AudioManager.STREAM_MUSIC, volume, 0);
|
||||
},
|
||||
};
|
||||
|
||||
let service: SpotifyService | null = null;
|
||||
|
||||
/**
|
||||
* The Spotify Web API service, created on first use (main thread only: it
|
||||
* owns timers and the sign-in). Signing in is optional on Android: Spotify's
|
||||
* media session already gives now-playing and transport control, and the
|
||||
* media bridges add the Web API's extras once signed in (library browsing,
|
||||
* search, shuffle / repeat / like, playback on other Spotify devices).
|
||||
*/
|
||||
export function spotifyService(): SpotifyService | null {
|
||||
return null;
|
||||
service ??= new SpotifyService({
|
||||
packageName: SPOTIFY_ANDROID_PACKAGE,
|
||||
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 size = Math.round(maxSize);
|
||||
// The shared photo tone (gamma + dither), as for media-session art.
|
||||
return grayImageFromPacket(
|
||||
com.faceclaw.app.ImageFileLoader.loadGrayFromBytes(copyToJavaByteBuffer(bytes), size, size, PHOTO_TONE.gamma, PHOTO_TONE.dither),
|
||||
);
|
||||
},
|
||||
systemVolume,
|
||||
});
|
||||
return service;
|
||||
}
|
||||
@@ -1130,7 +1130,7 @@ export const mapboxApiKeySetting = new ConfigSettingString({
|
||||
description: "Mapbox public token (pk. prefix), used by the Navigate app for maps, geocoding, and directions.",
|
||||
});
|
||||
|
||||
/** Edited from the Music app's Spotify menu (iOS); a sign-in is tied to the client ID it was made with. */
|
||||
/** Edited from the Music app's Spotify menu; a sign-in is tied to the client ID it was made with. */
|
||||
export const spotifyClientIdSetting = new ConfigSettingString({
|
||||
id: "spotify-client-id",
|
||||
label: "Client ID",
|
||||
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
interface FaceclawWebSignInListener {
|
||||
/**
|
||||
* The sign-in ended: the redirect URL (query included), or null with why
|
||||
* not ("cancelled" when it was cancelled or replaced by another sign-in).
|
||||
*/
|
||||
fun onFinished(redirectUrl: String?, error: String?): Unit
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function load(file, modules = {}, globals = {}) {
|
||||
const sandbox = { exports: {}, console, JSON, Promise, Date, Math, setTimeout, clearTimeout, require: id => {
|
||||
if (!(id in modules)) throw new Error(`Unstubbed import: ${id}`);
|
||||
return modules[id];
|
||||
}, ...globals };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, sandbox);
|
||||
return sandbox.exports;
|
||||
}
|
||||
|
||||
/** Values from the sandbox carry its own Array/Object prototypes; compare their plain JSON form. */
|
||||
const plain = value => JSON.parse(JSON.stringify(value));
|
||||
|
||||
const SPOTIFY = 'com.spotify.music';
|
||||
const types = load('app/native/media-types.ts');
|
||||
const base = { ...types.DEFAULT_MEDIA_STATE, accessEnabled: true };
|
||||
const playing = (extra = {}) => ({ ...base, available: true, playbackState: 'playing', title: 'Song', ...extra });
|
||||
const paused = (extra = {}) => ({ ...base, available: true, playbackState: 'paused', title: 'Song', ...extra });
|
||||
|
||||
function controllerApi() {
|
||||
return load('app/native/media-controller.ts', {
|
||||
'@nativescript/core': { Utils: {} },
|
||||
'./image-files': {}, './media-apps': {}, './settings-store': {}, './notification-access': {},
|
||||
'./media-types': types,
|
||||
'./spotify': { spotifyService: () => null },
|
||||
'./spotify-player': { SPOTIFY_ANDROID_PACKAGE: SPOTIFY },
|
||||
});
|
||||
}
|
||||
|
||||
/** A media-session bridge and a Web API player stand-in, each recording the commands it gets. */
|
||||
function composite(sessionState, spotifyState) {
|
||||
const api = controllerApi();
|
||||
const calls = [];
|
||||
const fake = (name, state, extra = {}) => ({
|
||||
accessPrompt: `${name} prompt`, accessLabel: `${name} label`, accessAction: `${name} action`, skipRebuildsQueue: true,
|
||||
state, queue: [], volume: name === 'session' ? 30 : 70, lastPlayingAtMs: 0, listeners: [],
|
||||
onStateChange(listener) { this.listeners.push(listener); listener(this.state); return () => calls.push(`${name}:unsubscribe`); },
|
||||
snapshot() { return this.state; },
|
||||
start: async () => calls.push(`${name}:start`), stop: async () => calls.push(`${name}:stop`),
|
||||
playPause: async () => calls.push(`${name}:playPause`), skipNext: async () => calls.push(`${name}:next`),
|
||||
skipPrevious: async () => calls.push(`${name}:previous`),
|
||||
skipToQueueItem: async id => calls.push(`${name}:skipTo:${id}`),
|
||||
getQueue() { calls.push(`${name}:queue`); return this.queue; },
|
||||
getMediaVolumePercent() { return this.volume; }, setMediaVolumePercent: value => calls.push(`${name}:volume:${value}`),
|
||||
getAlbumArt: () => name,
|
||||
hasAccess: () => name === 'session', requestAccess: async () => calls.push(`${name}:access`),
|
||||
sendCustomAction: async action => calls.push(`${name}:custom:${action}`),
|
||||
refresh: async () => calls.push(`${name}:refresh`),
|
||||
...extra,
|
||||
});
|
||||
const session = fake('session', sessionState);
|
||||
const spotify = fake('spotify', spotifyState);
|
||||
let now = 100;
|
||||
const bridge = new api.AndroidMediaControllerBridge(session, () => (spotifyState ? spotify : null), () => now);
|
||||
return { api, bridge, calls, session, spotify, tick: ms => { now += ms; } };
|
||||
}
|
||||
|
||||
test('the Android bridge chooses between the media session and Spotify\'s Web API player', () => {
|
||||
const { chooseAndroidMediaSource: choose } = controllerApi();
|
||||
const spotifySession = (extra) => ({ ...extra, packageName: SPOTIFY });
|
||||
// Signed out (or no Web API player): always the session.
|
||||
assert.equal(choose('spotify', paused(), null, 0, 0), 'session');
|
||||
assert.equal(choose('spotify', paused(), { ...playing(), accessEnabled: false }, 0, 0), 'session');
|
||||
// Without notification access, Spotify when it has something, else the session's access prompt.
|
||||
assert.equal(choose('session', { ...base, accessEnabled: false }, paused(), 0, 0), 'spotify');
|
||||
assert.equal(choose('session', { ...base, accessEnabled: false }, base, 0, 0), 'session');
|
||||
// Playing wins.
|
||||
assert.equal(choose('session', paused({ packageName: 'org.videolan.vlc' }), playing(), 0, 0), 'spotify');
|
||||
assert.equal(choose('spotify', playing({ packageName: 'org.videolan.vlc' }), paused(), 0, 0), 'session');
|
||||
// Both playing: Spotify's own session is the same playback; another player keeps the current choice.
|
||||
assert.equal(choose('spotify', spotifySession(playing()), playing(), 0, 0), 'session');
|
||||
assert.equal(choose('spotify', playing({ packageName: 'org.videolan.vlc' }), playing(), 0, 0), 'spotify');
|
||||
assert.equal(choose('session', playing({ packageName: 'org.videolan.vlc' }), playing(), 0, 0), 'session');
|
||||
// Neither playing: Spotify's session, then the one that played last, then whichever has something.
|
||||
assert.equal(choose('spotify', spotifySession(paused()), paused(), 0, 50), 'session');
|
||||
assert.equal(choose('session', paused({ packageName: 'org.videolan.vlc' }), paused(), 10, 50), 'spotify');
|
||||
assert.equal(choose('spotify', paused({ packageName: 'org.videolan.vlc' }), paused(), 50, 10), 'session');
|
||||
assert.equal(choose('spotify', paused({ packageName: 'org.videolan.vlc' }), paused(), 0, 0), 'session');
|
||||
assert.equal(choose('session', base, paused(), 0, 0), 'spotify');
|
||||
assert.equal(choose('session', base, base, 0, 0), 'session');
|
||||
});
|
||||
|
||||
test('a Spotify session keeps its transport and art and gains the Web API\'s rows and device volume', async () => {
|
||||
const actions = [{ action: 'shuffle', name: 'Shuffle: off' }, { action: 'repeat', name: 'Repeat: off' }, { action: 'like', name: 'Like song' }];
|
||||
const c = composite(playing({ packageName: SPOTIFY, appName: 'Spotify', title: 'Song a', artVersion: 4 }),
|
||||
playing({ packageName: SPOTIFY, appName: 'Spotify · Kitchen', title: 'Song a', customActions: actions }));
|
||||
let state = c.bridge.snapshot();
|
||||
assert.equal(state.title, 'Song a');
|
||||
assert.equal(state.appName, 'Spotify · Kitchen');
|
||||
assert.deepEqual(plain(state.customActions.map(action => action.action)), ['shuffle', 'repeat', 'like']);
|
||||
assert.equal(c.bridge.accessPrompt, 'session prompt');
|
||||
|
||||
await c.bridge.playPause(); await c.bridge.skipNext();
|
||||
await c.bridge.sendCustomAction('like');
|
||||
assert.equal(c.bridge.getAlbumArt(112), 'session');
|
||||
// Volume follows Spotify (a Connect speaker's own volume, or this phone's).
|
||||
assert.equal(c.bridge.getMediaVolumePercent(), 70);
|
||||
c.bridge.setMediaVolumePercent(55);
|
||||
assert.deepEqual(c.calls, ['session:playPause', 'session:next', 'spotify:custom:like', 'spotify:volume:55']);
|
||||
|
||||
// After a skip the API still describes the previous track: "Like song" waits until it catches up.
|
||||
c.session.state = { ...c.session.state, title: 'Song b' };
|
||||
state = c.bridge.snapshot();
|
||||
assert.deepEqual(plain(state.customActions.map(action => action.action)), ['shuffle', 'repeat']);
|
||||
assert.equal(state.appName, 'Spotify');
|
||||
|
||||
// Another player's session gets no Spotify rows, and its own volume.
|
||||
c.session.state = playing({ packageName: 'org.videolan.vlc', appName: 'VLC' });
|
||||
state = c.bridge.snapshot();
|
||||
assert.equal(state.customActions, undefined);
|
||||
assert.equal(c.bridge.getMediaVolumePercent(), 30);
|
||||
});
|
||||
|
||||
test('Spotify playing on another device, with no session here, follows the Web API player', async () => {
|
||||
const c = composite({ ...base, status: 'No session' }, playing({ packageName: SPOTIFY, appName: 'Spotify · MacBook', title: 'Remote', artVersion: 1 }));
|
||||
const first = c.bridge.snapshot();
|
||||
assert.equal(first.title, 'Remote');
|
||||
await c.bridge.playPause(); await c.bridge.skipPrevious(); c.bridge.setMediaVolumePercent(20);
|
||||
assert.equal(c.bridge.getAlbumArt(64), 'spotify');
|
||||
assert.deepEqual(c.calls, ['spotify:playPause', 'spotify:previous', 'spotify:volume:20']);
|
||||
|
||||
// Switching sources changes the art version even when the sources' versions match.
|
||||
c.spotify.state = paused({ packageName: SPOTIFY, artVersion: 1, notice: 'Controlling Spotify playback needs Spotify Premium.' });
|
||||
c.session.state = playing({ packageName: 'org.videolan.vlc', title: 'Local', artVersion: 1 });
|
||||
const second = c.bridge.snapshot();
|
||||
assert.equal(second.title, 'Local');
|
||||
assert.notEqual(second.artVersion, first.artVersion);
|
||||
// A Spotify failure still shows while the session is the one shown.
|
||||
assert.equal(second.notice, 'Controlling Spotify playback needs Spotify Premium.');
|
||||
});
|
||||
|
||||
test('the queue comes from the session, or the Web API when a Spotify session lists none, and jumps go to its source', async () => {
|
||||
const c = composite(playing({ packageName: SPOTIFY }), playing({ packageName: SPOTIFY }));
|
||||
c.session.queue = [{ id: 7, title: 'Next', active: false }];
|
||||
assert.equal(c.bridge.getQueue()[0].id, 7);
|
||||
await c.bridge.skipToQueueItem(7);
|
||||
c.session.queue = [];
|
||||
c.spotify.queue = [{ id: 1, title: 'Up next', subtitle: 'Band', active: false }];
|
||||
assert.equal(c.bridge.getQueue()[0].title, 'Up next');
|
||||
await c.bridge.skipToQueueItem(1);
|
||||
assert.deepEqual(c.calls.filter(call => call.includes('skipTo')), ['session:skipTo:7', 'spotify:skipTo:1']);
|
||||
|
||||
// Not Spotify's session: its (empty) queue stands.
|
||||
c.session.state = playing({ packageName: 'org.videolan.vlc' });
|
||||
assert.deepEqual(plain(c.bridge.getQueue()), []);
|
||||
});
|
||||
|
||||
test('a Spotify session changing track re-reads the Web API at once; listeners hear both sources', () => {
|
||||
const c = composite(playing({ packageName: SPOTIFY, title: 'Song a' }), playing({ packageName: SPOTIFY, title: 'Song a' }));
|
||||
const heard = [];
|
||||
const unsubscribe = c.bridge.onStateChange(state => heard.push(state.title));
|
||||
assert.deepEqual(c.calls, ['spotify:refresh']);
|
||||
c.session.listeners[0]({ ...c.session.state, positionMs: 5 });
|
||||
assert.deepEqual(c.calls, ['spotify:refresh']); // same track and play state
|
||||
c.session.state = playing({ packageName: SPOTIFY, title: 'Song b' });
|
||||
c.session.listeners[0](c.session.state);
|
||||
c.spotify.listeners[0](c.spotify.state);
|
||||
assert.deepEqual(c.calls, ['spotify:refresh', 'spotify:refresh']);
|
||||
assert.ok(heard.length >= 4);
|
||||
unsubscribe();
|
||||
assert.deepEqual(c.calls.slice(2), ['session:unsubscribe', 'spotify:unsubscribe']);
|
||||
});
|
||||
|
||||
test('signed out of Spotify, the Android bridge is the media session', async () => {
|
||||
const c = composite(playing({ packageName: SPOTIFY, title: 'Song' }), { ...base, accessEnabled: false, status: 'Not signed in to Spotify.' });
|
||||
const state = c.bridge.snapshot();
|
||||
assert.equal(state.title, 'Song');
|
||||
assert.equal(state.customActions, undefined);
|
||||
await c.bridge.playPause(); await c.bridge.start(); await c.bridge.requestAccess();
|
||||
assert.equal(c.bridge.hasAccess(), true);
|
||||
assert.equal(c.bridge.getMediaVolumePercent(), 30);
|
||||
assert.deepEqual(c.calls, ['session:playPause', 'session:start', 'session:access']);
|
||||
});
|
||||
|
||||
function browser({ installed = true, signedIn = true, enabled = true } = {}) {
|
||||
const api = load('app/native/media-browser.ts', {
|
||||
'@nativescript/core': { Utils: {} }, './media-apps': {}, './settings-store': {},
|
||||
'./media-types': types,
|
||||
'./spotify': { spotifyService: () => null },
|
||||
'./spotify-player': { SPOTIFY_ANDROID_PACKAGE: SPOTIFY },
|
||||
});
|
||||
const calls = [];
|
||||
const vlc = { packageName: 'org.videolan.vlc', serviceClass: 'VlcBrowser', appName: 'VLC' };
|
||||
const spotifyService = { packageName: SPOTIFY, serviceClass: 'SpotifyMediaBrowserService', appName: 'Spotify' };
|
||||
const services = {
|
||||
listBrowsableApps: refresh => { calls.push(`services:list:${Boolean(refresh)}`); return installed ? [spotifyService, vlc] : [vlc]; },
|
||||
connect: async app => { calls.push(`services:connect:${app.packageName}`); return 'vlc-root'; },
|
||||
browse: async parentId => { calls.push(`services:browse:${parentId}`); return []; },
|
||||
playFromMediaId: mediaId => calls.push(`services:play:${mediaId}`),
|
||||
disconnect: () => calls.push('services:disconnect'),
|
||||
};
|
||||
const libraryApp = { packageName: SPOTIFY, serviceClass: '', appName: 'Spotify' };
|
||||
const library = {
|
||||
app: libraryApp,
|
||||
listBrowsableApps: () => (signedIn ? [libraryApp] : []),
|
||||
connect: async app => {
|
||||
calls.push(`library:connect:${app.serviceClass}`);
|
||||
if (!signedIn) throw new Error('Sign in under Spotify in the Music app menu first.');
|
||||
return 'root';
|
||||
},
|
||||
browse: async parentId => { calls.push(`library:browse:${parentId}`); return []; },
|
||||
playFromMediaId: mediaId => calls.push(`library:play:${mediaId}`),
|
||||
disconnect: () => calls.push('library:disconnect'),
|
||||
};
|
||||
const bridge = new api.AndroidMediaBrowserBridge(services, () => library, () => enabled);
|
||||
return { bridge, calls, vlc, spotifyService };
|
||||
}
|
||||
|
||||
test('Spotify\'s library row opens the Web API library, or explains how to sign in', async () => {
|
||||
const b = browser();
|
||||
const apps = b.bridge.listBrowsableApps(true);
|
||||
assert.deepEqual(plain(apps.map(app => app.appName)), ['Spotify', 'VLC']);
|
||||
assert.equal(await b.bridge.connect(apps[0]), 'root');
|
||||
await b.bridge.browse('playlists');
|
||||
b.bridge.playFromMediaId('playlist:mine');
|
||||
assert.equal(await b.bridge.connect(b.vlc), 'vlc-root');
|
||||
await b.bridge.browse('vlc-root');
|
||||
b.bridge.disconnect();
|
||||
await assert.rejects(b.bridge.browse('root'), /Not connected/);
|
||||
assert.deepEqual(b.calls, ['services:list:true', 'library:connect:', 'library:browse:playlists', 'library:play:playlist:mine',
|
||||
'library:disconnect', 'services:connect:org.videolan.vlc', 'services:browse:vlc-root', 'services:disconnect']);
|
||||
|
||||
const signedOut = browser({ signedIn: false });
|
||||
const [spotify] = signedOut.bridge.listBrowsableApps();
|
||||
await assert.rejects(signedOut.bridge.connect(spotify), /Sign in under Spotify/);
|
||||
|
||||
// Not installed: the library is offered once signed in (it plays on other devices), unless Spotify is ignored.
|
||||
assert.deepEqual(plain(browser({ installed: false }).bridge.listBrowsableApps().map(app => app.appName)), ['VLC', 'Spotify']);
|
||||
assert.deepEqual(plain(browser({ installed: false, signedIn: false }).bridge.listBrowsableApps().map(app => app.appName)), ['VLC']);
|
||||
assert.deepEqual(plain(browser({ installed: false, enabled: false }).bridge.listBrowsableApps().map(app => app.appName)), ['VLC']);
|
||||
});
|
||||
@@ -160,7 +160,7 @@ function browser(music = fakeMusic()) {
|
||||
const api = load('app/native/media-browser.ios.ts', {
|
||||
'./media-types': types,
|
||||
'./spotify.ios': { spotifyService: () => null },
|
||||
'./spotify-player': { SPOTIFY_PACKAGE: 'com.spotify.client' },
|
||||
'./spotify-player': { SPOTIFY_IOS_BUNDLE_ID: 'com.spotify.client' },
|
||||
}, {
|
||||
FaceclawAppleMusic: { shared: () => music },
|
||||
});
|
||||
|
||||
@@ -235,6 +235,7 @@ function playerFixture({ routes = {}, settings = signedIn() } = {}) {
|
||||
...routes });
|
||||
const downloads = []; const decodes = []; const system = { volume: 40, set: [] };
|
||||
const service = new s.service.SpotifyService({
|
||||
packageName: 'com.spotify.client',
|
||||
fetch: f.fetch,
|
||||
webSignIn: { createPkce: () => ({}), randomState: () => '', open: async () => '', cancel: () => {} },
|
||||
download: async url => { downloads.push(url); return new Uint8Array([1, 2, 3]); },
|
||||
@@ -242,7 +243,8 @@ function playerFixture({ routes = {}, settings = signedIn() } = {}) {
|
||||
systemVolume: { get: () => system.volume, set: value => system.set.push(value) },
|
||||
});
|
||||
// The player reads time from Date.now by default; give it the fake clock.
|
||||
const player = new s.player.SpotifyPlayer({ client: service.client, isSignedIn: () => s.auth.readSpotifyAccount() !== null,
|
||||
const player = new s.player.SpotifyPlayer({ client: service.client, packageName: 'com.spotify.client',
|
||||
isSignedIn: () => s.auth.readSpotifyAccount() !== null,
|
||||
download: async url => { downloads.push(url); return new Uint8Array([1, 2, 3]); },
|
||||
decodeArt: (_bytes, size) => { decodes.push(size); return { size }; },
|
||||
systemVolume: { get: () => system.volume, set: value => system.set.push(value) }, now: timers.now });
|
||||
@@ -381,7 +383,7 @@ test('the library tree lists owned playlists as browsable and plays tracks withi
|
||||
{ track: track('a'), context: { uri: 'spotify:album:al' } }, { track: track('a'), context: null }, { track: track('b'), context: null }] } },
|
||||
});
|
||||
const plays = [];
|
||||
const library = new s.library.SpotifyLibrary({ client: new s.api.SpotifyClient(f.fetch, tokens),
|
||||
const library = new s.library.SpotifyLibrary({ client: new s.api.SpotifyClient(f.fetch, tokens), packageName: 'com.spotify.client',
|
||||
player: { startPlayback: async request => { plays.push(request); return true; } },
|
||||
isSignedIn: () => true, userId: () => 'jim' });
|
||||
const [app] = library.listBrowsableApps();
|
||||
|
||||
@@ -91,6 +91,9 @@ function bridges() {
|
||||
'./image-files': {},
|
||||
'./notification-access': { isNotificationListenerEnabled: () => true },
|
||||
'./media-types': load('app/native/media-types.ts', () => { throw new Error('media-types has no imports'); }),
|
||||
// Signed out of Spotify's Web API: the bridges are the native session and browser services alone.
|
||||
'./spotify': { spotifyService: () => null },
|
||||
'./spotify-player': { SPOTIFY_ANDROID_PACKAGE: 'com.spotify.music' },
|
||||
};
|
||||
const globals = { global: { isAndroid: true }, com: { faceclaw: { app: {
|
||||
FaceclawMediaBrowser: NativeBrowser,
|
||||
|
||||
Reference in new issue
Block a user