import { MatrixClient } from 'matrix-js-sdk'; import { NowPlayingEntry, NowPlayingMe, musicStatusFor } from './nowPlaying'; import { NowPlayingStore } from './nowPlayingStore'; /** * [Gitea #491] Talks to the Lotus now-playing service. Auth is a Matrix OpenID * token (the same kind Element Call uses), cached until shortly before it * expires; no Matrix access token ever leaves the homeserver. */ export class NowPlayingApi { private token?: { value: string; expiresAt: number }; private pendingToken?: Promise; constructor( private readonly mx: MatrixClient, readonly base: string, ) {} private async getToken(force: boolean): Promise { if (!force && this.token && Date.now() < this.token.expiresAt) return this.token.value; if (!this.pendingToken) { this.pendingToken = this.mx .getOpenIdToken() .then((t) => { const lifeMs = Math.max(60, (t.expires_in ?? 3600) - 60) * 1000; this.token = { value: t.access_token, expiresAt: Date.now() + lifeMs }; return t.access_token; }) .finally(() => { this.pendingToken = undefined; }); } return this.pendingToken; } private async request(path: string, init: RequestInit = {}, retried = false): Promise { const token = await this.getToken(retried); const res = await fetch(`${this.base}${path}`, { ...init, credentials: 'omit', headers: { ...(init.body ? { 'Content-Type': 'application/json' } : {}), Authorization: `Bearer ${token}`, }, signal: init.signal ?? AbortSignal.timeout(10_000), }); if (res.status === 401 && !retried) return this.request(path, init, true); if (!res.ok) throw new Error(`now-playing HTTP ${res.status}`); return res.json() as Promise; } me(): Promise { return this.request('/v1/me'); } setShare(share: boolean): Promise { return this.request('/v1/me', { method: 'PUT', body: JSON.stringify({ share }) }); } async users(ids: string[]): Promise> { const q = encodeURIComponent(ids.join(',')); const res = await this.request<{ users?: Record }>( `/v1/users?ids=${q}`, ); return res.users ?? {}; } } type Listener = () => void; // --- the user's own sharing state and music status text ------------------- let ownMe: NowPlayingMe | undefined; let ownMusicStatus = ''; const ownListeners = new Set(); const musicListeners = new Set(); export const getOwnNowPlaying = (): NowPlayingMe | undefined => ownMe; /** The music text the presence heartbeat may publish, or '' (see effectiveStatus). */ export const getMusicStatus = (): string => ownMusicStatus; export function subscribeOwnNowPlaying(listener: Listener): () => void { ownListeners.add(listener); return () => { ownListeners.delete(listener); }; } /** Fires only when the music text changes. */ export function subscribeMusicStatus(listener: Listener): () => void { musicListeners.add(listener); return () => { musicListeners.delete(listener); }; } export function setOwnNowPlaying(me: NowPlayingMe | undefined): void { ownMe = me; ownListeners.forEach((l) => l()); const music = musicStatusFor(me); if (music !== ownMusicStatus) { ownMusicStatus = music; musicListeners.forEach((l) => l()); } } // --- one API + store per (homeserver user, service URL) ------------------- let current: { key: string; api: NowPlayingApi; store: NowPlayingStore } | undefined; export function getNowPlayingServices( mx: MatrixClient, base: string, ): { api: NowPlayingApi; store: NowPlayingStore } { const key = `${mx.getUserId()}|${base}`; if (!current || current.key !== key) { current?.store.dispose(); const api = new NowPlayingApi(mx, base); current = { key, api, store: new NowPlayingStore(api) }; setOwnNowPlaying(undefined); } return current; }