forked from Blendman974/faceclaw
219 lines
7.3 KiB
TypeScript
219 lines
7.3 KiB
TypeScript
import { Utils } from "@nativescript/core";
|
|
import { GrayImage } from "../graphics/image";
|
|
import { grayImageFromPacket, PHOTO_TONE } from "./image-files";
|
|
import { ignoredMediaPackages, MEDIA_APPS_KEY, rememberMediaApps } from "./media-apps";
|
|
import { onSettingsStoreChanged } from "./settings-store";
|
|
import { isNotificationListenerEnabled } from "./notification-access";
|
|
import {
|
|
DEFAULT_MEDIA_STATE,
|
|
interpolateMediaState,
|
|
type MediaControllerBridge,
|
|
type MediaControllerState,
|
|
type MediaPlaybackState,
|
|
type MediaQueueItem,
|
|
} from "./media-types";
|
|
|
|
declare const com: any;
|
|
|
|
export type { MediaControllerState, MediaPlaybackState, MediaQueueItem } from "./media-types";
|
|
|
|
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";
|
|
readonly accessAction = "open settings";
|
|
readonly skipRebuildsQueue = true;
|
|
private readonly stateListeners = new Set<(state: MediaControllerState) => void>();
|
|
private controller: any = null;
|
|
private listenerProxy: any = null;
|
|
private state: MediaControllerState = { ...DEFAULT_MEDIA_STATE };
|
|
private stateUpdatedAtMs = Date.now();
|
|
private started = false;
|
|
|
|
onStateChange(listener: (state: MediaControllerState) => void): () => void {
|
|
this.stateListeners.add(listener);
|
|
listener(this.snapshot());
|
|
return () => this.stateListeners.delete(listener);
|
|
}
|
|
|
|
snapshot(): MediaControllerState {
|
|
return interpolateMediaState(this.state, this.stateUpdatedAtMs, Date.now());
|
|
}
|
|
|
|
async start(): Promise<void> {
|
|
if (this.started || !global.isAndroid) return;
|
|
this.ensureController();
|
|
this.started = true;
|
|
this.controller?.start();
|
|
}
|
|
|
|
async stop(): Promise<void> {
|
|
if (!this.started || !global.isAndroid) return;
|
|
this.started = false;
|
|
this.controller?.stop();
|
|
}
|
|
|
|
async playPause(): Promise<void> {
|
|
this.ensureController();
|
|
this.controller?.playPause();
|
|
}
|
|
|
|
async skipNext(): Promise<void> {
|
|
this.ensureController();
|
|
this.controller?.skipNext();
|
|
}
|
|
|
|
async skipPrevious(): Promise<void> {
|
|
this.ensureController();
|
|
this.controller?.skipPrevious();
|
|
}
|
|
|
|
hasAccess(): boolean {
|
|
return isNotificationListenerEnabled();
|
|
}
|
|
|
|
/** Opens the notification-access settings screen; the grant is only visible once the app resumes. */
|
|
async requestAccess(): Promise<boolean> {
|
|
this.ensureController();
|
|
this.controller?.openNotificationAccessSettings();
|
|
return false;
|
|
}
|
|
|
|
/** Jump playback to a queue item (see getQueue). */
|
|
async skipToQueueItem(id: number): Promise<void> {
|
|
this.ensureController();
|
|
this.controller?.skipToQueueItem(id);
|
|
}
|
|
|
|
/** Current Android music-stream volume normalized to 0..100. */
|
|
getMediaVolumePercent(): number {
|
|
if (!global.isAndroid) return -1;
|
|
this.ensureController();
|
|
if (!this.controller) return -1;
|
|
return Math.max(-1, Math.min(100, Math.round(Number(this.controller.getMediaVolumePercent()))));
|
|
}
|
|
|
|
/** Set Android's music-stream volume from a normalized 0..100 value. */
|
|
setMediaVolumePercent(volumePercent: number): void {
|
|
if (!global.isAndroid) return;
|
|
this.ensureController();
|
|
this.controller?.setMediaVolumePercent(Math.max(0, Math.min(100, Math.round(volumePercent))));
|
|
}
|
|
|
|
/**
|
|
* Album art for the current item, grayscale with the shared photo tone
|
|
* (gamma-corrected and dithered onto the display's 16 levels), scaled to
|
|
* fit maxSize; null when the player provides none.
|
|
*/
|
|
getAlbumArt(maxSize: number): GrayImage | null {
|
|
if (!global.isAndroid) return null;
|
|
this.ensureController();
|
|
if (!this.controller) return null;
|
|
return grayImageFromPacket(
|
|
this.controller.getAlbumArtGray(Math.round(maxSize), PHOTO_TONE.gamma, PHOTO_TONE.dither),
|
|
);
|
|
}
|
|
|
|
/** The player's queue (playlist), empty when the player exposes none. */
|
|
getQueue(): MediaQueueItem[] {
|
|
if (!global.isAndroid) return [];
|
|
this.ensureController();
|
|
if (!this.controller) return [];
|
|
const json = String(this.controller.getQueueJson() ?? "");
|
|
if (!json) return [];
|
|
try {
|
|
const raw = JSON.parse(json) as Array<{ id?: number; title?: string; active?: boolean }>;
|
|
return raw.map((item) => ({
|
|
id: Number(item.id ?? -1),
|
|
title: String(item.title ?? ""),
|
|
active: Boolean(item.active),
|
|
}));
|
|
} catch (error) {
|
|
console.warn(`media queue parse failed: ${error}`);
|
|
return [];
|
|
}
|
|
}
|
|
|
|
private ensureController(): void {
|
|
if (!global.isAndroid || this.controller) return;
|
|
const context = Utils.android.getApplicationContext();
|
|
if (!context) {
|
|
throw new Error("Android application context unavailable");
|
|
}
|
|
this.controller = new com.faceclaw.app.FaceclawMediaController(context);
|
|
// Install defaults and saved overrides before starting session discovery.
|
|
this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
|
|
onSettingsStoreChanged((key) => {
|
|
if (key === MEDIA_APPS_KEY) {
|
|
this.controller.setIgnoredPackagesJson(JSON.stringify(ignoredMediaPackages()));
|
|
}
|
|
});
|
|
this.listenerProxy = new com.faceclaw.app.FaceclawMediaControllerListener({
|
|
onSessionAppsChanged: (appsJson: string) => {
|
|
try {
|
|
const apps = JSON.parse(String(appsJson));
|
|
rememberMediaApps(apps);
|
|
} catch (error) {
|
|
console.warn(`media session apps parse failed: ${error}`);
|
|
}
|
|
},
|
|
onStateChange: (
|
|
playbackState: string,
|
|
packageName: string,
|
|
appName: string,
|
|
title: string,
|
|
artist: string,
|
|
album: string,
|
|
positionMs: number,
|
|
durationMs: number,
|
|
playbackSpeed: number,
|
|
canPlayPause: boolean,
|
|
canSkipNext: boolean,
|
|
canSkipPrevious: boolean,
|
|
accessEnabled: boolean,
|
|
status: string,
|
|
artVersion: number,
|
|
) => {
|
|
this.state = {
|
|
available: Boolean(title || artist || album || packageName) || String(playbackState) !== "idle",
|
|
accessEnabled: Boolean(accessEnabled),
|
|
packageName: String(packageName),
|
|
appName: String(appName),
|
|
playbackState: normalizePlaybackState(String(playbackState)),
|
|
title: String(title),
|
|
artist: String(artist),
|
|
album: String(album),
|
|
positionMs: Number(positionMs),
|
|
durationMs: Number(durationMs),
|
|
playbackSpeed: Number(playbackSpeed),
|
|
status: String(status),
|
|
canPlayPause: Boolean(canPlayPause),
|
|
canSkipNext: Boolean(canSkipNext),
|
|
canSkipPrevious: Boolean(canSkipPrevious),
|
|
artVersion: Number(artVersion),
|
|
};
|
|
this.stateUpdatedAtMs = Date.now();
|
|
for (const listener of this.stateListeners) {
|
|
listener(this.snapshot());
|
|
}
|
|
},
|
|
});
|
|
this.controller.setListener(this.listenerProxy);
|
|
}
|
|
}
|
|
|
|
function normalizePlaybackState(value: string): MediaPlaybackState {
|
|
switch (value) {
|
|
case "notification-access-required":
|
|
case "idle":
|
|
case "playing":
|
|
case "paused":
|
|
case "buffering":
|
|
case "stopped":
|
|
return value;
|
|
default:
|
|
return "unknown";
|
|
}
|
|
}
|
|
|
|
export const mediaControllerBridge: MediaControllerBridge = new FaceclawMediaControllerBridge();
|