// Bridges playback state to the OS via the Media Session API, so hardware // media keys and the lockscreen/notification controls (phone especially) // drive the bot. Metadata + position follow appStore; the action handlers // map straight onto the RPC calls the UI already uses. import { appStore, safeCall } from './app'; import { thumbFor } from './format'; function skip() { const id = appStore.get().identity; if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 }); else safeCall('VoteSkip'); } export function initMediaSession() { if (!('mediaSession' in navigator)) return; const ms = navigator.mediaSession; ms.setActionHandler('play', () => void safeCall('Resume')); ms.setActionHandler('pause', () => void safeCall('Pause')); ms.setActionHandler('previoustrack', () => void safeCall('Seek', { position: 0 }) ); ms.setActionHandler('nexttrack', () => skip()); ms.setActionHandler('seekto', (d) => { if (typeof d.seekTime === 'number') { safeCall('Seek', { position: Math.round(d.seekTime * 1000) }); } }); ms.setActionHandler('seekbackward', (d) => { const by = (d.seekOffset || 10) * 1000; const s = appStore.get(); safeCall('Seek', { position: Math.max(0, s.positionMs - by) }); }); ms.setActionHandler('seekforward', (d) => { const by = (d.seekOffset || 10) * 1000; const s = appStore.get(); const dur = s.durationMs || s.positionMs + by; safeCall('Seek', { position: Math.min(dur, s.positionMs + by) }); }); let lastKey = ''; appStore.subscribe(() => { const s = appStore.get(); const track = s.current; const st = s.status; ms.playbackState = !track ? 'none' : st && st.isPlaying && !st.isPaused ? 'playing' : 'paused'; // Rebuild metadata only when the track changes. const key = track ? track.url || track.title || '' : ''; if (track && key !== lastKey) { lastKey = key; const artwork = thumbFor(track); ms.metadata = new MediaMetadata({ title: track.title || 'Echoion', artist: track.artist || '', album: 'Echoion', artwork: artwork ? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }] : [], }); } else if (!track) { lastKey = ''; ms.metadata = null; } // Keep the scrubber in sync where supported. if (typeof ms.setPositionState === 'function' && s.durationMs > 0) { try { ms.setPositionState({ duration: s.durationMs / 1000, position: Math.min(s.positionMs, s.durationMs) / 1000, playbackRate: 1, }); } catch { /* invalid position state (e.g. position > duration) — ignore */ } } }); }