// App-level state + orchestration — the controller half of the old app.js. // Views render from `appStore`; server push and the refresh helpers below // mutate it. import { rpc, type RpcMethodName } from './rpc'; import { Store } from './store'; import { t, tf, setLanguage, getLanguage } from '../i18n'; import type { Identity, PublicDashboard, QueueEntry, ServerInfo, Status, Subscriber, Track, } from './types'; export type ViewName = | 'dashboard' | 'queue' | 'search' | 'library' | 'stats' | 'server' | 'updates' | 'rpc'; export interface AppState { view: ViewName; connection: 'connected' | 'disconnected' | 'error'; identity: Identity | null; status: Status | null; current: Track | null; queue: QueueEntry[]; favorites: Track[]; favUrls: Set; searchResults: Track[]; searchTab: 'all' | 'youtube' | 'yandex'; positionMs: number; durationMs: number; onlineCount: number; listeners: Subscriber[]; publicDashboard: PublicDashboard | null; watchUrl: string; toast: string | null; // Server-wide switch for the Now Playing video preview (item 11), from // /config.json; users can still disable it locally. nowPlayingVideoAllowed: boolean; // Keyboard-shortcut cheat-sheet overlay (toggled with "?"). shortcutsOpen: boolean; // Sidebar drawer on small screens (hamburger in the header); ignored by // CSS on desktop widths where the sidebar is always visible. sidebarOpen: boolean; capabilities: { plugins: boolean; webExtensions: boolean; }; } export const appStore = new Store({ view: 'dashboard', connection: 'disconnected', identity: null, status: null, current: null, queue: [], favorites: [], favUrls: new Set(), searchResults: [], searchTab: 'all', positionMs: 0, durationMs: 0, onlineCount: 0, listeners: [], publicDashboard: null, watchUrl: '', toast: null, nowPlayingVideoAllowed: true, shortcutsOpen: false, sidebarOpen: false, capabilities: { plugins: false, webExtensions: false, }, }); // ── toast ──────────────────────────────────────────────────────────────────── let toastTimer: ReturnType | null = null; export function toast(msg: string) { appStore.set({ toast: msg }); if (toastTimer) clearTimeout(toastTimer); toastTimer = setTimeout(() => appStore.set({ toast: null }), 2400); } export async function safeCall( method: RpcMethodName, params?: Record ): Promise { try { return await rpc.call(method, params); } catch (e) { const err = e as { message?: string }; if (err && err.message) toast(err.message); console.warn(method, 'failed', e); return null; } } // ── auth ───────────────────────────────────────────────────────────────────── export function getStoredToken(): string | null { return localStorage.getItem('echoion.token'); } async function loadUserPrefs() { const prefs = await safeCall<{ language?: string }>('GetUserPrefs'); if (prefs && (prefs.language === 'en' || prefs.language === 'ru')) { // Server-side preference (set here or via !lang) wins over the // browser default but is not written to the local override. if (!localStorage.getItem('echoion.lang')) { setLanguage(prefs.language, false); } } } export async function changeLanguage(language: 'en' | 'ru') { setLanguage(language); if (appStore.get().identity) { await safeCall('SetUserPrefs', { language }); } } export function applyIdentity(auth: Identity | null) { appStore.set({ identity: auth }); if (auth) { void loadUserPrefs(); } } // Autologin: the bot matches this browser's IP against online subscribers' // TeamSpeak addresses and hands back the user's persistent token, so people // on their usual machine never type anything. export async function tryAutologin(): Promise { try { const auth = await rpc.call('AuthenticateByAddress'); if (auth && auth.token) { localStorage.setItem('echoion.token', auth.token); rpc.token = auth.token; applyIdentity(auth); toast(tf('Signed in as {0}', auth.nickname || t('subscriber'))); return true; } } catch { /* no address match — the manual auth box stays available */ } return false; } // Restore the authenticated session: use the stored token, and if it's // missing or rejected (expired/revoked), clear it and fall back to address // autologin. Never throws — a failure just leaves the user as a guest with the // auth box available, so callers can always proceed to refresh state. async function restoreSession(): Promise { const token = getStoredToken(); if (token) { try { applyIdentity((await rpc.authenticate(token)) as Identity); return; } catch { // Stale token — drop it so it doesn't wedge every reconnect. localStorage.removeItem('echoion.token'); rpc.token = null; } } await tryAutologin(); } export async function connectWithToken(tokenInput: string) { const token = tokenInput.trim() || getStoredToken() || ''; try { if (!rpc.connected) await rpc.connect(); if (token) { const auth = (await rpc.authenticate(token)) as Identity; localStorage.setItem('echoion.token', token); applyIdentity(auth); await loadCapabilities(); toast(tf('Welcome, {0}!', auth.nickname || t('friend'))); } refreshAll(); } catch (e) { const err = e as { message?: string }; toast((err && err.message) || t('Connection failed')); } } export async function requestToken(nickname: string) { try { if (!rpc.connected) await rpc.connect(); const res = (await rpc.requestToken(nickname.trim())) as Identity; toast((res && res.message) || t('Token sent via TeamSpeak PM')); } catch (e) { const err = e as { message?: string }; toast((err && err.message) || t('Request failed')); } } export async function logout() { await safeCall('Logout'); localStorage.removeItem('echoion.token'); rpc.token = null; applyIdentity(null); toast(t('Logged out')); } // ── view routing ───────────────────────────────────────────────────────────── export function showView(view: ViewName) { // Navigation closes the mobile drawer. appStore.set({ view, sidebarOpen: false }); // Reflect the selection in the URL for back/forward + shareable links. const target = `#${view}`; if (location.hash !== target) location.hash = target; } // ── refresh orchestration ──────────────────────────────────────────────────── export async function refreshCore() { if (!rpc.connected) return; const [status, current, queue, info] = await Promise.all([ safeCall('GetStatus'), safeCall<{ track?: Track }>('GetCurrentTrack'), safeCall<{ queue?: QueueEntry[] }>('GetQueue'), safeCall('GetServerInfo'), ]); const state = appStore.get(); const next: Partial = { status, current: (current && current.track) || null, queue: (queue && queue.queue) || [], }; if (info && typeof info.onlineSubscribers === 'number') { next.onlineCount = info.onlineSubscribers; } // The nicknames + uids on GetServerInfo feed the "Listening now" card for // everyone. Admins get a richer list from the server view's loadSubscribers, // but that only runs once they open that view — so populate here // unconditionally (previously admins saw an empty card on the Now tab). if (info) { const names = info.onlineSubscriberNames || []; const uids = info.onlineSubscriberUids || []; next.listeners = names.map((n, i) => ({ uid: uids[i] || n, nickname: n, online: true, })); } const track = next.current; if (track && track.duration && !state.durationMs) { next.durationMs = track.duration; } appStore.set(next); } export async function refreshAll() { await refreshCore(); } export async function loadFavorites() { if (!appStore.get().identity) return; const res = await safeCall<{ tracks?: Track[] }>('GetFavorites'); const favorites = (res && res.tracks) || []; appStore.set({ favorites, favUrls: new Set( favorites.map((tr) => tr.url).filter(Boolean) as string[] ), }); } // ── boot ───────────────────────────────────────────────────────────────────── let booted = false; let dashboardEtag = ''; export async function refreshPublicDashboard() { try { const response = await fetch('/api/public/dashboard', { headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {}, cache: 'no-cache', }); if (response.status === 304) return; if (!response.ok) return; const dashboard = (await response.json()) as PublicDashboard; dashboardEtag = response.headers.get('ETag') || ''; const state = appStore.get(); const publicTrack = dashboard.playback.track; const sameTrack = publicTrack && state.current && publicTrack.id === state.current.id; const current = publicTrack ? { ...(sameTrack ? state.current! : {}), ...publicTrack, duration: publicTrack.durationMs ?? publicTrack.duration ?? 0, } : null; appStore.set({ publicDashboard: dashboard, current, status: { ...(state.status || {}), isPlaying: dashboard.playback.isPlaying, isPaused: dashboard.playback.isPaused, volume: dashboard.playback.volume, }, positionMs: dashboard.playback.positionMs, durationMs: current?.duration || 0, onlineCount: dashboard.server.clientCount, }); } catch { /* The RPC login remains usable if the public snapshot is unavailable. */ } } export function boot() { if (booted) return; booted = true; // Apply the persisted language before anything renders text. setLanguage(getLanguage(), false); // Server config: the video preview policy and external VoidWatch link. fetch('/config.json') .then((r) => r.json()) .then((cfg) => { appStore.set({ nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false, watchUrl: typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '', }); }) .catch(() => { /* keep the default (allowed) */ }); rpc.onState = (s) => appStore.set({ connection: s }); void refreshPublicDashboard(); setInterval(() => void refreshPublicDashboard(), 5000); // After an automatic reconnect, restore the authenticated session from // the stored token (or autologin) and pull fresh state. rpc.onReconnected = async () => { await restoreSession(); await loadCapabilities(); refreshAll(); toast(t('Reconnected')); }; // Server push: any event nudges a debounced refresh; position updates // are applied directly so the progress bar stays smooth. let refreshTimer: ReturnType | null = null; rpc.on('*', (event) => { if (event === 'playback.position') return; if (refreshTimer) clearTimeout(refreshTimer); refreshTimer = setTimeout(refreshAll, 150); }); rpc.on('playback.position', (d) => { const data = d as { position?: number; duration?: number } | null; if (!data) return; appStore.set({ positionMs: data.position || 0, durationMs: data.duration || 0, }); }); rpc.on('voteskip.updated', (d) => { const data = d as { votes?: number; needed?: number } | null; if (!data) return; const status = appStore.get().status; if (status) { appStore.set({ status: { ...status, skipVotes: data.votes, skipVotesNeeded: data.needed, }, }); } }); rpc.on('plugins.updated', () => { if (appStore.get().capabilities.webExtensions) void loadWebExtensions(); }); // Local 1s ticker keeps the progress bar moving between server updates. setInterval(() => { const s = appStore.get(); if ( s.status && s.status.isPlaying && !s.status.isPaused && s.durationMs > 0 ) { appStore.set({ positionMs: Math.min(s.durationMs, s.positionMs + 1000), }); } }, 1000); (async () => { try { await rpc.connect(); } catch { /* connection failed — stay on the auth box */ return; } // Session restore is independent of the connection: even if auth fails // we still refresh so guests see live state instead of a blank app. await restoreSession(); await loadCapabilities(); refreshAll(); })(); } async function loadCapabilities() { const capabilities = await safeCall( 'GetCapabilities' ); if (capabilities) { appStore.set({ capabilities }); if (capabilities.webExtensions) await loadWebExtensions(); } } interface PluginWebAsset { id: string; javascript: string; css: string; } interface LoadedWebExtension { signature: string; cleanup?: () => void; } const loadedWebExtensions = new Map(); function unloadWebExtension(id: string) { const loaded = loadedWebExtensions.get(id); if (!loaded) return; try { loaded.cleanup?.(); } catch (error) { console.error(`Echoion plugin web asset ${id} cleanup failed`, error); } document .querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`) .forEach((style) => style.remove()); loadedWebExtensions.delete(id); } async function loadWebExtensions() { const response = await safeCall<{ assets?: PluginWebAsset[] }>( 'GetPluginExtensions' ); if (!response) return; const assets = response.assets || []; const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean)); for (const id of loadedWebExtensions.keys()) { if (!currentIds.has(id)) unloadWebExtension(id); } for (const asset of assets) { if (!asset.id) continue; const signature = `${asset.javascript}\0${asset.css}`; if (loadedWebExtensions.get(asset.id)?.signature === signature) continue; unloadWebExtension(asset.id); let style: HTMLStyleElement | undefined; if (asset.css) { style = document.createElement('style'); style.dataset.echoionPlugin = asset.id; style.textContent = asset.css; document.head.appendChild(style); } try { const host = { call: async (plugin: string, method: string, params: unknown = {}) => rpc.call('PluginCall', { plugin, method, params: JSON.stringify(params), }), store: appStore, toast, }; const cleanup = new Function( 'Echoion', `'use strict';\n${asset.javascript}` )(host); loadedWebExtensions.set(asset.id, { signature, cleanup: typeof cleanup === 'function' ? cleanup : undefined, }); } catch (error) { style?.remove(); console.error(`Echoion plugin web asset ${asset.id} failed`, error); } } }