Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-15 19:50:44 +03:00
1 parent 1c96d5973b
commit e80dbc2fda
38 files changed
+1352 -6335

No files matched your search

+155 -15
View File
@@ -5,10 +5,9 @@
import { rpc, type RpcMethodName } from './rpc';
import { Store } from './store';
import { t, tf, setLanguage, getLanguage } from '../i18n';
import { setWatchName } from './watch';
import { loadCustomEmojis } from './emoji';
import type {
Identity,
PublicDashboard,
QueueEntry,
ServerInfo,
Status,
@@ -17,13 +16,11 @@ import type {
} from './types';
export type ViewName =
| 'now'
| 'dashboard'
| 'queue'
| 'search'
| 'library'
| 'stats'
| 'rooms'
| 'watch'
| 'server'
| 'rpc';
@@ -42,6 +39,8 @@ export interface AppState {
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.
@@ -51,10 +50,14 @@ export interface AppState {
// 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<AppState>({
view: 'now',
view: 'dashboard',
connection: 'disconnected',
identity: null,
status: null,
@@ -68,10 +71,16 @@ export const appStore = new Store<AppState>({
durationMs: 0,
onlineCount: 0,
listeners: [],
publicDashboard: null,
watchUrl: '',
toast: null,
nowPlayingVideoAllowed: true,
shortcutsOpen: false,
sidebarOpen: false,
capabilities: {
plugins: false,
webExtensions: false,
},
});
// ── toast ────────────────────────────────────────────────────────────────────
@@ -124,9 +133,7 @@ export async function changeLanguage(language: 'en' | 'ru') {
export function applyIdentity(auth: Identity | null) {
appStore.set({ identity: auth });
if (auth) {
setWatchName(auth.nickname || null);
void loadUserPrefs();
void loadCustomEmojis();
}
}
@@ -176,6 +183,7 @@ export async function connectWithToken(tokenInput: string) {
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();
@@ -210,9 +218,6 @@ 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.
// The watch view owns its own #watch/<room> hash (see watch.ts), so a
// re-selection never clobbers an existing room deep link.
if (view === 'watch' && location.hash.startsWith('#watch')) return;
const target = `#${view}`;
if (location.hash !== target) location.hash = target;
}
@@ -275,6 +280,47 @@ export async function loadFavorites() {
// ── 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;
@@ -283,24 +329,29 @@ export function boot() {
// Apply the persisted language before anything renders text.
setLanguage(getLanguage(), false);
// Server config: the Now Playing video preview can be disabled globally.
// Server config: the video preview policy and external VoidWatch link.
fetch('/config.json')
.then((r) => r.json())
.then((cfg) => {
if (cfg && cfg.nowPlayingVideo === false) {
appStore.set({ nowPlayingVideoAllowed: false });
}
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'));
};
@@ -335,6 +386,9 @@ export function boot() {
});
}
});
rpc.on('plugins.updated', () => {
if (appStore.get().capabilities.webExtensions) void loadWebExtensions();
});
// Local 1s ticker keeps the progress bar moving between server updates.
setInterval(() => {
@@ -361,6 +415,92 @@ export function boot() {
// 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<AppState['capabilities']>(
'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<string, LoadedWebExtension>();
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);
}
}
}