import { useCallback, useEffect, useMemo, useSyncExternalStore } from 'react'; import { useMatrixClient } from './useMatrixClient'; import { useClientConfig } from './useClientConfig'; import { NowPlayingEntry, NowPlayingMe, nowPlayingBaseUrl } from '../utils/nowPlaying'; import { NowPlayingApi, getNowPlayingServices, getOwnNowPlaying, setOwnNowPlaying, subscribeOwnNowPlaying, } from '../utils/nowPlayingClient'; import type { NowPlayingStore } from '../utils/nowPlayingStore'; /** [Gitea #491] The now-playing service for this homeserver, if config.json has one. */ export function useNowPlayingServices(): | { api: NowPlayingApi; store: NowPlayingStore } | undefined { const mx = useMatrixClient(); const { nowPlaying } = useClientConfig(); const base = nowPlayingBaseUrl(nowPlaying, mx.getDomain() ?? undefined); return useMemo(() => (base ? getNowPlayingServices(mx, base) : undefined), [mx, base]); } const noop = () => () => undefined; /** What `userId` is playing right now, if they share it. */ export function useNowPlaying(userId: string | undefined): NowPlayingEntry | undefined { const services = useNowPlayingServices(); const store = services?.store; const subscribe = useCallback( (cb: () => void) => (store && userId ? store.subscribe(userId, cb) : noop()), [store, userId], ); const get = useCallback(() => (store && userId ? store.get(userId) : undefined), [store, userId]); return useSyncExternalStore(subscribe, get); } /** The signed-in user's own sharing state (kept fresh by NowPlayingMonitor). */ export function useOwnNowPlaying(): NowPlayingMe | undefined { return useSyncExternalStore(subscribeOwnNowPlaying, getOwnNowPlaying); } const OWN_POLL_MS = 20_000; /** * Always mounted (ClientNonUIFeatures): polls the user's own entry so their * status text can follow the music, including while Lotus is in the background. */ export function useNowPlayingMonitor(): void { const services = useNowPlayingServices(); useEffect(() => { if (!services) { setOwnNowPlaying(undefined); return undefined; } let stopped = false; let timer: ReturnType | undefined; let delay = OWN_POLL_MS; const tick = async () => { try { const me = await services.api.me(); if (stopped) return; setOwnNowPlaying(me); delay = OWN_POLL_MS; } catch { // Keep the last state for a while, then drop the music text so a dead // service can't leave an old track in the status. delay = Math.min(delay * 2, 5 * 60_000); if (delay >= 4 * OWN_POLL_MS) setOwnNowPlaying(undefined); } if (!stopped) timer = setTimeout(tick, delay); }; tick(); return () => { stopped = true; clearTimeout(timer); }; }, [services]); }