forked from Blendman974/faceclaw
Merge branch 'main' of https://github.com/jimrandomh/faceclaw
This commit is contained in:
commit
3c3aa31542
19 files changed
+930
-39
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user