1 parent
7a18682b0e
commit
24fecc90f3
107 files changed
+14935
-1919
No files matched your search
@@ -0,0 +1,365 @@
|
||||
// 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 { setWatchName } from './watch';
|
||||
import { loadCustomEmojis } from './emoji';
|
||||
import type {
|
||||
Identity,
|
||||
QueueEntry,
|
||||
ServerInfo,
|
||||
Status,
|
||||
Subscriber,
|
||||
Track,
|
||||
} from './types';
|
||||
|
||||
export type ViewName =
|
||||
| 'now'
|
||||
| 'queue'
|
||||
| 'search'
|
||||
| 'library'
|
||||
| 'stats'
|
||||
| 'watch'
|
||||
| 'server'
|
||||
| '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<string>;
|
||||
searchResults: Track[];
|
||||
searchTab: 'all' | 'youtube' | 'yandex';
|
||||
positionMs: number;
|
||||
durationMs: number;
|
||||
onlineCount: number;
|
||||
listeners: Subscriber[];
|
||||
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;
|
||||
}
|
||||
|
||||
export const appStore = new Store<AppState>({
|
||||
view: 'now',
|
||||
connection: 'disconnected',
|
||||
identity: null,
|
||||
status: null,
|
||||
current: null,
|
||||
queue: [],
|
||||
favorites: [],
|
||||
favUrls: new Set(),
|
||||
searchResults: [],
|
||||
searchTab: 'all',
|
||||
positionMs: 0,
|
||||
durationMs: 0,
|
||||
onlineCount: 0,
|
||||
listeners: [],
|
||||
toast: null,
|
||||
nowPlayingVideoAllowed: true,
|
||||
shortcutsOpen: false,
|
||||
sidebarOpen: false,
|
||||
});
|
||||
|
||||
// ── toast ────────────────────────────────────────────────────────────────────
|
||||
|
||||
let toastTimer: ReturnType<typeof setTimeout> | 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<T = unknown>(
|
||||
method: RpcMethodName,
|
||||
params?: Record<string, unknown>
|
||||
): Promise<T | null> {
|
||||
try {
|
||||
return await rpc.call<T>(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) {
|
||||
setWatchName(auth.nickname || null);
|
||||
void loadUserPrefs();
|
||||
void loadCustomEmojis();
|
||||
}
|
||||
}
|
||||
|
||||
// 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<boolean> {
|
||||
try {
|
||||
const auth = await rpc.call<Identity>('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<void> {
|
||||
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);
|
||||
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.
|
||||
// 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;
|
||||
}
|
||||
|
||||
// ── refresh orchestration ────────────────────────────────────────────────────
|
||||
|
||||
export async function refreshCore() {
|
||||
if (!rpc.connected) return;
|
||||
const [status, current, queue, info] = await Promise.all([
|
||||
safeCall<Status>('GetStatus'),
|
||||
safeCall<{ track?: Track }>('GetCurrentTrack'),
|
||||
safeCall<{ queue?: QueueEntry[] }>('GetQueue'),
|
||||
safeCall<ServerInfo>('GetServerInfo'),
|
||||
]);
|
||||
const state = appStore.get();
|
||||
const next: Partial<AppState> = {
|
||||
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;
|
||||
|
||||
export function boot() {
|
||||
if (booted) return;
|
||||
booted = true;
|
||||
|
||||
// Apply the persisted language before anything renders text.
|
||||
setLanguage(getLanguage(), false);
|
||||
|
||||
// Server config: the Now Playing video preview can be disabled globally.
|
||||
fetch('/config.json')
|
||||
.then((r) => r.json())
|
||||
.then((cfg) => {
|
||||
if (cfg && cfg.nowPlayingVideo === false) {
|
||||
appStore.set({ nowPlayingVideoAllowed: false });
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* keep the default (allowed) */
|
||||
});
|
||||
|
||||
rpc.onState = (s) => appStore.set({ connection: s });
|
||||
|
||||
// After an automatic reconnect, restore the authenticated session from
|
||||
// the stored token (or autologin) and pull fresh state.
|
||||
rpc.onReconnected = async () => {
|
||||
await restoreSession();
|
||||
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<typeof setTimeout> | 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 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();
|
||||
refreshAll();
|
||||
})();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Maps the numeric RpcMethod enum value carried by audit-log entries to a
|
||||
// human name. This mirrors the declaration order of `enum class RpcMethod`
|
||||
// in EchoionApi/include/echoion/api/rpc/RpcTypes.hpp, which is explicitly
|
||||
// append-only ("numeric values are server-internal and only need to stay
|
||||
// self-consistent") — so index == enum value. When you append a method to
|
||||
// that enum, append it here too.
|
||||
const RPC_METHOD_BY_INDEX: readonly string[] = [
|
||||
'Play', // 0
|
||||
'Pause',
|
||||
'Resume',
|
||||
'Stop',
|
||||
'Skip',
|
||||
'Seek',
|
||||
'SetVolume',
|
||||
'QueueTrack',
|
||||
'RemoveFromQueue',
|
||||
'ClearQueue',
|
||||
'GetQueue', // 10
|
||||
'MoveInQueue',
|
||||
'GetCurrentTrack',
|
||||
'GetTrackInfo',
|
||||
'SearchTracks',
|
||||
'LoadPlaylist',
|
||||
'SavePlaylist',
|
||||
'GetPlaylists',
|
||||
'DeletePlaylist',
|
||||
'GetConfig',
|
||||
'SetConfig', // 20
|
||||
'ReloadConfig',
|
||||
'GetStatus',
|
||||
'HotReload',
|
||||
'Shutdown',
|
||||
'Authenticate',
|
||||
'Logout',
|
||||
'GetAuditLog',
|
||||
'ManageUsers',
|
||||
'GetServerInfo',
|
||||
'RequestLoginToken', // 30
|
||||
'ValidateLoginToken',
|
||||
'ToggleShuffle',
|
||||
'ToggleRepeat',
|
||||
'ShuffleQueue',
|
||||
'GetPlaylist',
|
||||
'GetHistory',
|
||||
'GetStats',
|
||||
'GetFavorites',
|
||||
'AddFavorite',
|
||||
'RemoveFavorite', // 40
|
||||
'VoteSkip',
|
||||
'Announce',
|
||||
'GetAggregateStats',
|
||||
'AuthenticateByAddress',
|
||||
'RestartWebInterface',
|
||||
'ToggleAutoplay',
|
||||
'GetUserPrefs',
|
||||
'SetUserPrefs',
|
||||
'GetCustomEmojis',
|
||||
'AddCustomEmoji', // 50
|
||||
'RemoveCustomEmoji',
|
||||
'GetLyrics',
|
||||
];
|
||||
|
||||
export function auditMethodName(method: number): string {
|
||||
return RPC_METHOD_BY_INDEX[method] ?? `Method #${method}`;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// Imperative custom dialogs (item 10) replacing the browser's native
|
||||
// confirm()/prompt(), which can't be styled and look out of place. A single
|
||||
// <DialogHost/> mounted at the app root renders the active request; the
|
||||
// confirmDialog/promptDialog helpers return a promise that resolves when the
|
||||
// user answers, so call sites read like `if (await confirmDialog(...))`.
|
||||
|
||||
import { Store } from './store';
|
||||
|
||||
export interface ConfirmRequest {
|
||||
kind: 'confirm';
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
danger?: boolean;
|
||||
resolve: (ok: boolean) => void;
|
||||
}
|
||||
|
||||
export interface PromptRequest {
|
||||
kind: 'prompt';
|
||||
title: string;
|
||||
message?: string;
|
||||
placeholder?: string;
|
||||
initial?: string;
|
||||
confirmLabel?: string;
|
||||
cancelLabel?: string;
|
||||
resolve: (value: string | null) => void;
|
||||
}
|
||||
|
||||
export type DialogRequest = ConfirmRequest | PromptRequest;
|
||||
|
||||
interface DialogState {
|
||||
current: DialogRequest | null;
|
||||
}
|
||||
|
||||
export const dialogStore = new Store<DialogState>({ current: null });
|
||||
|
||||
// Resolve the active dialog and clear it. Guards against double-resolve (e.g.
|
||||
// clicking confirm and the backdrop in quick succession).
|
||||
function settle(value: boolean | string | null) {
|
||||
const req = dialogStore.get().current;
|
||||
if (!req) return;
|
||||
dialogStore.set({ current: null });
|
||||
if (req.kind === 'confirm') {
|
||||
req.resolve(value === true);
|
||||
} else {
|
||||
req.resolve(typeof value === 'string' ? value : null);
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveConfirm(ok: boolean) {
|
||||
settle(ok);
|
||||
}
|
||||
|
||||
export function resolvePrompt(value: string | null) {
|
||||
settle(value);
|
||||
}
|
||||
|
||||
export function confirmDialog(
|
||||
opts: Omit<ConfirmRequest, 'kind' | 'resolve'>
|
||||
): Promise<boolean> {
|
||||
// A pending dialog is cancelled if a new one opens (shouldn't overlap).
|
||||
const pending = dialogStore.get().current;
|
||||
if (pending) {
|
||||
if (pending.kind === 'confirm') pending.resolve(false);
|
||||
else pending.resolve(null);
|
||||
}
|
||||
return new Promise<boolean>((resolve) => {
|
||||
dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } });
|
||||
});
|
||||
}
|
||||
|
||||
export function promptDialog(
|
||||
opts: Omit<PromptRequest, 'kind' | 'resolve'>
|
||||
): Promise<string | null> {
|
||||
const pending = dialogStore.get().current;
|
||||
if (pending) {
|
||||
if (pending.kind === 'confirm') pending.resolve(false);
|
||||
else pending.resolve(null);
|
||||
}
|
||||
return new Promise<string | null>((resolve) => {
|
||||
dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols';
|
||||
|
||||
const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!;
|
||||
const kodik = byName('kodik');
|
||||
const playerjs = byName('playerjs');
|
||||
const alloha = byName('alloha');
|
||||
const vimeo = byName('vimeo');
|
||||
const playerjsSpec = byName('player.js');
|
||||
const rutube = byName('rutube');
|
||||
const dailymotion = byName('dailymotion');
|
||||
const vk = byName('vk');
|
||||
|
||||
describe('kodik parse', () => {
|
||||
it('parses JSON-string time updates', () => {
|
||||
expect(
|
||||
kodik.parse(
|
||||
JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 })
|
||||
)
|
||||
).toEqual({ kind: 'time', seconds: 42.5 });
|
||||
});
|
||||
|
||||
it('parses duration and play/pause/ended state', () => {
|
||||
expect(
|
||||
kodik.parse({ key: 'kodik_player_duration_update', value: 1440 })
|
||||
).toEqual({ kind: 'duration', seconds: 1440 });
|
||||
expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' });
|
||||
expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({
|
||||
kind: 'pause',
|
||||
});
|
||||
expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({
|
||||
kind: 'ended',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects everything else', () => {
|
||||
expect(kodik.parse('garbage')).toBeNull();
|
||||
expect(kodik.parse('{"broken json')).toBeNull();
|
||||
expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull();
|
||||
expect(kodik.parse(null)).toBeNull();
|
||||
expect(kodik.parse(42)).toBeNull();
|
||||
});
|
||||
|
||||
it('is hostname-pinned and seeks by reloading with start_from', () => {
|
||||
expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe(
|
||||
true
|
||||
);
|
||||
expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true);
|
||||
expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false);
|
||||
// start_from is set (overwritten) while signed params are preserved.
|
||||
const seeked = kodik.reloadSeek!(
|
||||
'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5',
|
||||
42.9
|
||||
);
|
||||
expect(seeked).toContain('start_from=42');
|
||||
expect(seeked).toContain('d_sign=abc');
|
||||
expect(seeked).not.toContain('start_from=5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('playerjs.com parse', () => {
|
||||
it('parses object and JSON-string events', () => {
|
||||
expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({
|
||||
kind: 'time',
|
||||
seconds: 12,
|
||||
});
|
||||
expect(
|
||||
playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 }))
|
||||
).toEqual({ kind: 'duration', seconds: 600 });
|
||||
expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' });
|
||||
});
|
||||
|
||||
it('does not lock on player.js-spec or unknown shapes', () => {
|
||||
expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull();
|
||||
expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull();
|
||||
expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull();
|
||||
});
|
||||
|
||||
it('normalizes quality, voiceover and subtitle capabilities', () => {
|
||||
expect(
|
||||
playerjs.parse({
|
||||
event: 'qualities',
|
||||
answer: [{ id: '720', name: '720p' }, '1080p'],
|
||||
})
|
||||
).toMatchObject({
|
||||
kind: 'extraList',
|
||||
control: { id: 'quality', scope: 'local' },
|
||||
});
|
||||
expect(
|
||||
playerjs.parse({
|
||||
event: 'audiotracks',
|
||||
answer: { ru: 'Russian', en: 'English' },
|
||||
})
|
||||
).toMatchObject({
|
||||
kind: 'extraList',
|
||||
control: { id: 'audiotrack', scope: 'synced' },
|
||||
});
|
||||
expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({
|
||||
kind: 'extraCurrent',
|
||||
id: 'subtitle',
|
||||
value: '1',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('alloha detection', () => {
|
||||
it('pins known Alloha player hosts', () => {
|
||||
expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true);
|
||||
expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true);
|
||||
expect(alloha.matchUrl!('https://example.com/player')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vimeo parse', () => {
|
||||
it('parses timeupdate with bundled duration and the getDuration reply', () => {
|
||||
expect(
|
||||
vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } })
|
||||
).toEqual({ kind: 'time', seconds: 10, duration: 200 });
|
||||
expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({
|
||||
kind: 'duration',
|
||||
seconds: 200,
|
||||
});
|
||||
expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' });
|
||||
});
|
||||
|
||||
it('does not lock on a playerjs.com message (has `answer`) or garbage', () => {
|
||||
expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(vimeo.parse('garbage')).toBeNull();
|
||||
expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull();
|
||||
});
|
||||
|
||||
it('matchUrl selects vimeo hosts only', () => {
|
||||
expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true);
|
||||
expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true);
|
||||
expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false);
|
||||
});
|
||||
|
||||
it('prepareUrl hides native chrome', () => {
|
||||
const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123');
|
||||
expect(p).toContain('controls=0');
|
||||
expect(p).toContain('title=0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('player.js (embedly spec) parse', () => {
|
||||
it('parses context-tagged events', () => {
|
||||
expect(
|
||||
playerjsSpec.parse({
|
||||
context: 'player.js',
|
||||
event: 'timeupdate',
|
||||
value: { seconds: 5, duration: 100 },
|
||||
})
|
||||
).toEqual({ kind: 'time', seconds: 5, duration: 100 });
|
||||
expect(
|
||||
playerjsSpec.parse({ context: 'player.js', event: 'pause' })
|
||||
).toEqual({ kind: 'pause' });
|
||||
expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual(
|
||||
{ kind: 'hello' }
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects messages without the player.js context', () => {
|
||||
expect(playerjsSpec.parse({ event: 'play' })).toBeNull();
|
||||
expect(playerjsSpec.parse('garbage')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rutube parse + matchUrl', () => {
|
||||
it('parses player:* events', () => {
|
||||
expect(
|
||||
rutube.parse(
|
||||
JSON.stringify({ type: 'player:currentTime', data: { time: 30 } })
|
||||
)
|
||||
).toEqual({ kind: 'time', seconds: 30 });
|
||||
expect(
|
||||
rutube.parse({ type: 'player:changeState', data: { state: 'playing' } })
|
||||
).toEqual({ kind: 'play' });
|
||||
expect(
|
||||
rutube.parse({ type: 'player:durationChange', data: { duration: 90 } })
|
||||
).toEqual({ kind: 'duration', seconds: 90 });
|
||||
});
|
||||
|
||||
it('ignores foreign messages', () => {
|
||||
expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull();
|
||||
expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true);
|
||||
expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dailymotion parse + prepareUrl', () => {
|
||||
it('parses classic querystring events', () => {
|
||||
expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual(
|
||||
{ kind: 'time', seconds: 12, duration: 240 }
|
||||
);
|
||||
expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' });
|
||||
expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' });
|
||||
expect(dailymotion.parse({ event: 'play' })).toBeNull();
|
||||
});
|
||||
|
||||
it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => {
|
||||
expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x'))
|
||||
.toBe(true);
|
||||
expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true);
|
||||
const prepared = dailymotion.prepareUrl!(
|
||||
'https://www.dailymotion.com/embed/video/x?foo=1'
|
||||
);
|
||||
expect(prepared).toContain('api=postMessage');
|
||||
expect(prepared).toContain('controls=0');
|
||||
expect(prepared).toContain('foo=1');
|
||||
// idempotent
|
||||
expect(dailymotion.prepareUrl!(prepared)).toBe(prepared);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vk parse + prepareUrl', () => {
|
||||
it('parses player_api events', () => {
|
||||
expect(
|
||||
vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 })
|
||||
).toEqual({ kind: 'time', seconds: 8, duration: 60 });
|
||||
expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({
|
||||
kind: 'play',
|
||||
});
|
||||
expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({
|
||||
kind: 'pause',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores foreign messages and injects js_api=1', () => {
|
||||
expect(vk.parse({ event: 'play', answer: 1 })).toBeNull();
|
||||
expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true);
|
||||
expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true);
|
||||
expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain(
|
||||
'js_api=1'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('registry order + prepareEmbedUrl', () => {
|
||||
it('generic (content-detected) set is player.js then playerjs', () => {
|
||||
expect(
|
||||
EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name)
|
||||
).toEqual(['player.js', 'playerjs']);
|
||||
});
|
||||
|
||||
it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => {
|
||||
expect(
|
||||
prepareEmbedUrl('https://www.dailymotion.com/embed/video/x')
|
||||
).toContain('api=postMessage');
|
||||
expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe(
|
||||
'https://kodik.info/seria/1/hash/720p'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,972 @@
|
||||
// Adapters for postMessage-controllable embed players in the Watch view.
|
||||
//
|
||||
// A generic iframe can only be driven if the player inside exposes a
|
||||
// postMessage API — everything else stays view-only by browser design.
|
||||
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
|
||||
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
|
||||
// commands {key:'kodik_player_api', value:{method}}.
|
||||
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
|
||||
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
|
||||
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
|
||||
// params (prepareUrl) and their command/event shapes are community-
|
||||
// documented — flagged VERIFY, one-line fixes if a live embed differs.
|
||||
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
|
||||
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
|
||||
// {event, answer} events.
|
||||
// Shapes marked VERIFY are community-documented, not official; dev builds
|
||||
// console.debug every unrecognized frame message to reverse-engineer them.
|
||||
//
|
||||
// Detection: for a hostname-matched player only that protocol is probed;
|
||||
// otherwise the generic set is probed until one `parse` recognizes a message
|
||||
// and locks the adapter. On timeout the embed is uncontrollable and the
|
||||
// caller keeps today's host-driven view-only behavior.
|
||||
|
||||
export interface EmbedAdapter {
|
||||
protocol: string;
|
||||
// True for players (Kodik) driven by reloading the iframe rather than
|
||||
// postMessage commands: the caller should avoid drift-reconcile churn and
|
||||
// not expect pause to work.
|
||||
reloadBased: boolean;
|
||||
play(): void;
|
||||
pause(): void;
|
||||
seekMs(ms: number): void;
|
||||
setVolume(v01: number): void; // 0..1
|
||||
positionMs(): number;
|
||||
durationMs(): number;
|
||||
paused(): boolean;
|
||||
extras(): PlayerExtraControl[];
|
||||
setExtra(id: string, value: string): void;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
export interface ExtraControlOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface PlayerExtraControl {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: 'select' | 'button';
|
||||
options: ExtraControlOption[];
|
||||
current: string | null;
|
||||
scope: 'local' | 'synced';
|
||||
}
|
||||
|
||||
// Fired only for events NOT caused by our own commands (see suppression
|
||||
// below) — i.e. gestures made inside the embed UI, which the host must relay
|
||||
// to the room.
|
||||
export interface EmbedCallbacks {
|
||||
onPlay(positionMs: number): void;
|
||||
onPause(positionMs: number): void;
|
||||
onSeek(positionMs: number): void;
|
||||
onDurationChange(durationMs: number): void;
|
||||
onEnded(): void;
|
||||
onExtraControls(controls: PlayerExtraControl[]): void;
|
||||
}
|
||||
|
||||
export type EmbedEvent =
|
||||
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
|
||||
// VK) that bundle it into their timeupdate payload.
|
||||
| { kind: 'time'; seconds: number; duration?: number }
|
||||
| { kind: 'duration'; seconds: number }
|
||||
| { kind: 'play' }
|
||||
| { kind: 'pause' }
|
||||
| { kind: 'ended' }
|
||||
| { kind: 'extraList'; control: PlayerExtraControl }
|
||||
| { kind: 'extraCurrent'; id: string; value: string }
|
||||
// Recognized the protocol but the event carries no state we track; enough
|
||||
// to lock detection.
|
||||
| { kind: 'hello' };
|
||||
|
||||
export interface ProtocolDef {
|
||||
name: string;
|
||||
// Hostname-based selection: when a URL matches, only this protocol is
|
||||
// probed (skips content-based detection). Left undefined for generic
|
||||
// protocols detected purely by the messages they emit (kodik, player.js).
|
||||
matchUrl?(url: string): boolean;
|
||||
// Inject opt-in query params the player needs before the iframe loads
|
||||
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
|
||||
prepareUrl?(url: string): string;
|
||||
// Some players (Kodik) expose no postMessage command API — the only way to
|
||||
// seek is to reload the iframe at a start offset. When present, the adapter
|
||||
// seeks by setting frame.src to this URL instead of posting a command.
|
||||
reloadSeek?(currentSrc: string, seconds: number): string;
|
||||
probe(win: Window): void;
|
||||
parse(data: unknown): EmbedEvent | null;
|
||||
play(win: Window): void;
|
||||
pause(win: Window): void;
|
||||
seek(win: Window, seconds: number): void;
|
||||
volume(win: Window, v01: number): void;
|
||||
probeExtras?(win: Window): void;
|
||||
setExtra?(win: Window, id: string, value: string): void;
|
||||
staticExtras?(url: string): PlayerExtraControl[];
|
||||
}
|
||||
|
||||
// Embeds are served from many mirror domains (esp. Kodik), so the target
|
||||
// origin can't be pinned; we never trust incoming data beyond parsing known
|
||||
// shapes into numbers.
|
||||
function post(win: Window, msg: unknown) {
|
||||
try {
|
||||
win.postMessage(msg, '*');
|
||||
} catch {
|
||||
/* frame navigating/gone */
|
||||
}
|
||||
}
|
||||
|
||||
const asNumber = (v: unknown): number =>
|
||||
typeof v === 'number' ? v : Number(v);
|
||||
|
||||
// Embed URLs are absolute, so no base is needed; guard `location` so the
|
||||
// helpers also work under the node test runner.
|
||||
const baseHref = (): string | undefined =>
|
||||
typeof location !== 'undefined' ? location.href : undefined;
|
||||
|
||||
function hostOf(url: string): string {
|
||||
try {
|
||||
return new URL(url, baseHref()).hostname.toLowerCase();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function isHostOrSubdomain(host: string, domain: string): boolean {
|
||||
return host === domain || host.endsWith(`.${domain}`);
|
||||
}
|
||||
|
||||
function withParams(url: string, params: Record<string, string>): string {
|
||||
try {
|
||||
const u = new URL(url, baseHref());
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
|
||||
}
|
||||
return u.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
|
||||
// d_sign/ref_sign params).
|
||||
function setParam(url: string, key: string, value: string): string {
|
||||
try {
|
||||
const u = new URL(url, baseHref());
|
||||
u.searchParams.set(key, value);
|
||||
return u.toString();
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize an object-or-JSON-string payload into a plain object, or null.
|
||||
function asObj(data: unknown): Record<string, unknown> | null {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
const s = data.trim();
|
||||
if (!s.startsWith('{') && !s.startsWith('[')) return null;
|
||||
try {
|
||||
obj = JSON.parse(s);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return obj && typeof obj === 'object'
|
||||
? (obj as Record<string, unknown>)
|
||||
: null;
|
||||
}
|
||||
|
||||
function toOptions(value: unknown): ExtraControlOption[] {
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((item, index) => [String(index), item] as const)
|
||||
: value && typeof value === 'object'
|
||||
? Object.entries(value as Record<string, unknown>)
|
||||
: [];
|
||||
return entries.flatMap(([fallback, item]) => {
|
||||
if (item && typeof item === 'object') {
|
||||
const option = item as Record<string, unknown>;
|
||||
const raw = option.value ?? option.id ?? option.index ?? fallback;
|
||||
const label = option.label ?? option.name ?? option.title ?? raw;
|
||||
return [{ value: String(raw), label: String(label) }];
|
||||
}
|
||||
return item == null
|
||||
? []
|
||||
: [{ value: fallback, label: String(item) }];
|
||||
});
|
||||
}
|
||||
|
||||
function extraControl(
|
||||
id: string,
|
||||
label: string,
|
||||
scope: PlayerExtraControl['scope'],
|
||||
options: ExtraControlOption[],
|
||||
current: string | null = null
|
||||
): PlayerExtraControl {
|
||||
return { id, label, scope, options, current, kind: 'select' };
|
||||
}
|
||||
|
||||
const kodik: ProtocolDef = {
|
||||
name: 'kodik',
|
||||
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
|
||||
// locks as `kodik` and never falls back to view-only.
|
||||
matchUrl: (url) => {
|
||||
const host = hostOf(url);
|
||||
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
|
||||
.some((domain) => isHostOrSubdomain(host, domain));
|
||||
},
|
||||
// Kodik has NO postMessage command API — the only way to seek is to reload
|
||||
// the iframe at a start offset (preserving its signed params). start_from
|
||||
// auto-resumes playback from that second.
|
||||
reloadSeek: (src, seconds) =>
|
||||
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
|
||||
probe(win) {
|
||||
// Community-documented; harmless if ignored by the player.
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
|
||||
},
|
||||
parse(data) {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
if (!data.includes('kodik_player')) return null;
|
||||
try {
|
||||
obj = JSON.parse(data);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const m = obj as { key?: unknown; value?: unknown } | null;
|
||||
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
|
||||
return null;
|
||||
}
|
||||
const n = asNumber(m.value);
|
||||
switch (m.key) {
|
||||
case 'kodik_player_time_update':
|
||||
case 'kodik_player_current_time':
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
case 'kodik_player_duration_update':
|
||||
case 'kodik_player_duration':
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
case 'kodik_player_play':
|
||||
return { kind: 'play' };
|
||||
case 'kodik_player_pause':
|
||||
return { kind: 'pause' };
|
||||
case 'kodik_player_video_ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
// Unmapped kodik_player_* event — still unambiguously Kodik.
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
},
|
||||
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
|
||||
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
|
||||
seek: (win, seconds) =>
|
||||
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
|
||||
volume: (win, v01) =>
|
||||
post(win, {
|
||||
key: 'kodik_player_api',
|
||||
value: { method: 'change_volume', volume: v01 },
|
||||
}),
|
||||
};
|
||||
|
||||
const playerjs: ProtocolDef = {
|
||||
name: 'playerjs',
|
||||
probe(win) {
|
||||
post(win, { api: 'duration' });
|
||||
post(win, { api: 'time' });
|
||||
},
|
||||
probeExtras(win) {
|
||||
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
|
||||
post(win, { api });
|
||||
}
|
||||
},
|
||||
staticExtras() {
|
||||
return [
|
||||
extraControl(
|
||||
'speed',
|
||||
'Speed',
|
||||
'synced',
|
||||
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
|
||||
value: String(speed),
|
||||
label: `${speed}×`,
|
||||
})),
|
||||
'1'
|
||||
),
|
||||
];
|
||||
},
|
||||
parse(data) {
|
||||
let obj: unknown = data;
|
||||
if (typeof data === 'string') {
|
||||
if (!data.startsWith('{')) return null;
|
||||
try {
|
||||
obj = JSON.parse(data);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const m = obj as
|
||||
| { event?: unknown; answer?: unknown; context?: unknown }
|
||||
| null;
|
||||
if (!m || typeof m.event !== 'string') return null;
|
||||
// A {context:'player.js'} message belongs to the embedly spec adapter,
|
||||
// not this one.
|
||||
if (m.context === 'player.js') return null;
|
||||
const n = asNumber(m.answer);
|
||||
// Only lock on events Playerjs actually emits — a bare {event:...}
|
||||
// could belong to some other player's protocol.
|
||||
switch (m.event) {
|
||||
case 'qualities':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'quality',
|
||||
'Quality',
|
||||
'local',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'audiotracks':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'audiotrack',
|
||||
'Voiceover',
|
||||
'synced',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'subtitles':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'subtitle',
|
||||
'Subtitles',
|
||||
'local',
|
||||
[
|
||||
{ value: '-1', label: 'Off' },
|
||||
...toOptions(m.answer),
|
||||
]
|
||||
),
|
||||
};
|
||||
case 'episodes':
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'episode',
|
||||
'Episode',
|
||||
'synced',
|
||||
toOptions(m.answer)
|
||||
),
|
||||
};
|
||||
case 'quality':
|
||||
case 'audiotrack':
|
||||
case 'subtitle':
|
||||
case 'speed':
|
||||
case 'episode':
|
||||
return {
|
||||
kind: 'extraCurrent',
|
||||
id: m.event,
|
||||
value: String(m.answer ?? ''),
|
||||
};
|
||||
case 'time':
|
||||
case 'updatetime':
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
case 'duration':
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'end':
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
case 'init':
|
||||
case 'inited':
|
||||
case 'ready':
|
||||
case 'volume':
|
||||
return { kind: 'hello' };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
play: (win) => post(win, { api: 'play' }),
|
||||
pause: (win) => post(win, { api: 'pause' }),
|
||||
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
|
||||
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
|
||||
setExtra: (win, id, value) => {
|
||||
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
|
||||
return;
|
||||
}
|
||||
post(win, { api: id, set: value });
|
||||
},
|
||||
};
|
||||
|
||||
const alloha: ProtocolDef = {
|
||||
...playerjs,
|
||||
name: 'alloha',
|
||||
matchUrl: (url) =>
|
||||
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
|
||||
(domain) => isHostOrSubdomain(hostOf(url), domain)
|
||||
),
|
||||
};
|
||||
|
||||
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
|
||||
// from playerjs.com by carrying `data`, not `answer`.
|
||||
const vimeo: ProtocolDef = {
|
||||
name: 'vimeo',
|
||||
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
|
||||
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
|
||||
prepareUrl: (url) =>
|
||||
withParams(url, {
|
||||
controls: '0',
|
||||
title: '0',
|
||||
byline: '0',
|
||||
portrait: '0',
|
||||
}),
|
||||
probe(win) {
|
||||
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
|
||||
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
|
||||
}
|
||||
post(win, JSON.stringify({ method: 'getDuration' }));
|
||||
},
|
||||
probeExtras(win) {
|
||||
post(win, JSON.stringify({ method: 'getQualities' }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m) return null;
|
||||
if (m.method === 'getDuration') {
|
||||
const n = asNumber(m.value);
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
if (m.method === 'getQualities') {
|
||||
return {
|
||||
kind: 'extraList',
|
||||
control: extraControl(
|
||||
'quality',
|
||||
'Quality',
|
||||
'local',
|
||||
toOptions(m.value)
|
||||
),
|
||||
};
|
||||
}
|
||||
if (typeof m.event !== 'string') return null;
|
||||
if ('answer' in m) return null; // that's a playerjs.com message
|
||||
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
|
||||
switch (m.event) {
|
||||
case 'timeupdate': {
|
||||
const sec = asNumber(d.seconds);
|
||||
const dur = asNumber(d.duration);
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
case 'finish':
|
||||
return { kind: 'ended' };
|
||||
case 'ready':
|
||||
case 'loaded':
|
||||
return { kind: 'hello' };
|
||||
default:
|
||||
return null; // bare {event} without vimeo markers → not ours
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ method: 'play' })),
|
||||
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
|
||||
seek: (w, s) =>
|
||||
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
|
||||
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
|
||||
setExtra: (w, id, value) => {
|
||||
if (id === 'quality') {
|
||||
post(w, JSON.stringify({ method: 'setQuality', value }));
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
|
||||
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
|
||||
const PJS = { context: 'player.js', version: '0.0.11' } as const;
|
||||
const playerjsSpec: ProtocolDef = {
|
||||
name: 'player.js',
|
||||
probe(win) {
|
||||
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
|
||||
post(win, {
|
||||
...PJS,
|
||||
method: 'addEventListener',
|
||||
listener: `ec_${ev}`,
|
||||
value: ev,
|
||||
});
|
||||
}
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
|
||||
switch (m.event) {
|
||||
case 'timeupdate': {
|
||||
const sec = asNumber(v.seconds);
|
||||
const dur = asNumber(v.duration);
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'play':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' }; // any context:'player.js' event is ours
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, { ...PJS, method: 'play' }),
|
||||
pause: (w) => post(w, { ...PJS, method: 'pause' }),
|
||||
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
|
||||
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
|
||||
};
|
||||
|
||||
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
|
||||
const rutube: ProtocolDef = {
|
||||
name: 'rutube',
|
||||
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
|
||||
probe(win) {
|
||||
// Rutube emits events only after an explicit subscribe. VERIFY payload.
|
||||
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
|
||||
return null;
|
||||
}
|
||||
const d = (m.data ?? {}) as {
|
||||
time?: unknown;
|
||||
duration?: unknown;
|
||||
state?: unknown;
|
||||
};
|
||||
switch (m.type) {
|
||||
case 'player:currentTime': {
|
||||
const n = asNumber(d.time);
|
||||
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
|
||||
}
|
||||
case 'player:durationChange': {
|
||||
const n = asNumber(d.duration);
|
||||
return isFinite(n) && n > 0
|
||||
? { kind: 'duration', seconds: n }
|
||||
: { kind: 'hello' };
|
||||
}
|
||||
case 'player:changeState': {
|
||||
const st = String(d.state);
|
||||
if (st === 'playing') return { kind: 'play' };
|
||||
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
|
||||
if (st === 'ended') return { kind: 'ended' };
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
default:
|
||||
return { kind: 'hello' }; // player:* is unambiguously Rutube
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
|
||||
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
|
||||
seek: (w, s) =>
|
||||
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
|
||||
volume: (w, v) =>
|
||||
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
|
||||
};
|
||||
|
||||
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
|
||||
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
|
||||
const dailymotion: ProtocolDef = {
|
||||
name: 'dailymotion',
|
||||
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
|
||||
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
|
||||
// (our overlay bar drives playback instead).
|
||||
prepareUrl: (url) =>
|
||||
withParams(url, {
|
||||
api: 'postMessage',
|
||||
controls: '0',
|
||||
'ui-start-screen-info': 'false',
|
||||
'ui-logo': 'false',
|
||||
}),
|
||||
probe() {
|
||||
/* classic embed auto-emits once api=postMessage is set */
|
||||
},
|
||||
parse(data) {
|
||||
if (typeof data !== 'string' || !data.includes('event=')) return null;
|
||||
const p = new URLSearchParams(data);
|
||||
const ev = p.get('event');
|
||||
if (!ev) return null;
|
||||
const sec = Number(p.get('time'));
|
||||
const dur = Number(p.get('duration'));
|
||||
switch (ev) {
|
||||
case 'timeupdate':
|
||||
case 'progress':
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
case 'durationchange':
|
||||
return isFinite(dur) && dur > 0
|
||||
? { kind: 'duration', seconds: dur }
|
||||
: { kind: 'hello' };
|
||||
case 'play':
|
||||
case 'playing':
|
||||
return { kind: 'play' };
|
||||
case 'pause':
|
||||
return { kind: 'pause' };
|
||||
case 'video_end':
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' };
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
|
||||
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
|
||||
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
|
||||
volume: (w, v) =>
|
||||
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
|
||||
};
|
||||
|
||||
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
|
||||
const vk: ProtocolDef = {
|
||||
name: 'vk',
|
||||
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
|
||||
prepareUrl: (url) => withParams(url, { js_api: '1' }),
|
||||
probe(win) {
|
||||
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
|
||||
},
|
||||
parse(data) {
|
||||
const m = asObj(data);
|
||||
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const sec = asNumber(m.time ?? m.position);
|
||||
const dur = asNumber(m.duration);
|
||||
switch (m.event) {
|
||||
case 'timeupdate':
|
||||
return isFinite(sec)
|
||||
? {
|
||||
kind: 'time',
|
||||
seconds: sec,
|
||||
duration: isFinite(dur) && dur > 0 ? dur : undefined,
|
||||
}
|
||||
: { kind: 'hello' };
|
||||
case 'started':
|
||||
case 'resumed':
|
||||
return { kind: 'play' };
|
||||
case 'paused':
|
||||
return { kind: 'pause' };
|
||||
case 'ended':
|
||||
return { kind: 'ended' };
|
||||
default:
|
||||
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
|
||||
}
|
||||
},
|
||||
play: (w) => post(w, JSON.stringify({ method: 'play' })),
|
||||
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
|
||||
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
|
||||
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
|
||||
};
|
||||
|
||||
// Hostname-selected protocols first (they're picked by URL, never by content);
|
||||
// then the generic set probed by the messages they emit — kodik first (its
|
||||
// keys are unambiguous), the embedly spec before the looser playerjs.com.
|
||||
// Exported for the parse unit tests.
|
||||
export const EMBED_PROTOCOLS: ProtocolDef[] = [
|
||||
kodik,
|
||||
alloha,
|
||||
vimeo,
|
||||
rutube,
|
||||
dailymotion,
|
||||
vk,
|
||||
playerjsSpec,
|
||||
playerjs,
|
||||
];
|
||||
|
||||
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
|
||||
export function prepareEmbedUrl(url: string): string {
|
||||
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
|
||||
// Signed players such as Kodik depend on their own origin for scripts,
|
||||
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
|
||||
// Echoion controls them only through their postMessage surface.
|
||||
return p?.prepareUrl ? p.prepareUrl(url) : url;
|
||||
}
|
||||
|
||||
const PROBE_INTERVAL_MS = 750;
|
||||
// Commands are echoed back as events by the player; ignore relay callbacks
|
||||
// for this long after each command we send.
|
||||
const SUPPRESS_MS = 800;
|
||||
// A time event this far off the extrapolated position counts as a user seek.
|
||||
const SEEK_JUMP_SEC = 2.5;
|
||||
// Minimum gap between reload-based (Kodik) iframe reloads.
|
||||
const RELOAD_DEBOUNCE_MS = 4000;
|
||||
|
||||
export function detectEmbedAdapter(
|
||||
frame: HTMLIFrameElement,
|
||||
cb: EmbedCallbacks,
|
||||
timeoutMs = 5000
|
||||
): Promise<EmbedAdapter | null> {
|
||||
return new Promise((resolve) => {
|
||||
let locked: ProtocolDef | null = null;
|
||||
|
||||
// A hostname-matched player is probed alone; otherwise probe the
|
||||
// generic (content-detected) set. frame.src is the prepared URL.
|
||||
const matched =
|
||||
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
|
||||
const probeSet = matched
|
||||
? [matched]
|
||||
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
|
||||
|
||||
// Normalized player state. Embeds push time updates rather than expose
|
||||
// getters, so position is the last event extrapolated by wall clock.
|
||||
let lastTimeSec = 0;
|
||||
let lastTimeAt = performance.now();
|
||||
let durationSec = 0;
|
||||
let playing = false;
|
||||
let suppressUntil = 0;
|
||||
const extraControls = new Map<string, PlayerExtraControl>();
|
||||
|
||||
const positionMs = () =>
|
||||
Math.floor(
|
||||
(lastTimeSec +
|
||||
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
|
||||
1000
|
||||
);
|
||||
const suppressed = () => performance.now() < suppressUntil;
|
||||
|
||||
const applyEvent = (ev: EmbedEvent) => {
|
||||
switch (ev.kind) {
|
||||
case 'time': {
|
||||
const jumped =
|
||||
Math.abs(ev.seconds - positionMs() / 1000) >
|
||||
SEEK_JUMP_SEC;
|
||||
// Advancing time implies playing even when the protocol
|
||||
// never sends an explicit play event.
|
||||
const advancing = ev.seconds > lastTimeSec + 0.05;
|
||||
lastTimeSec = ev.seconds;
|
||||
lastTimeAt = performance.now();
|
||||
// Some protocols bundle duration into the time event.
|
||||
if (
|
||||
ev.duration != null &&
|
||||
Math.abs(ev.duration - durationSec) > 0.5
|
||||
) {
|
||||
durationSec = ev.duration;
|
||||
cb.onDurationChange(Math.floor(ev.duration * 1000));
|
||||
}
|
||||
if (jumped && !suppressed()) {
|
||||
cb.onSeek(Math.floor(ev.seconds * 1000));
|
||||
}
|
||||
if (!playing && advancing) {
|
||||
playing = true;
|
||||
if (!suppressed()) cb.onPlay(positionMs());
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'duration':
|
||||
if (Math.abs(ev.seconds - durationSec) > 0.5) {
|
||||
durationSec = ev.seconds;
|
||||
cb.onDurationChange(Math.floor(ev.seconds * 1000));
|
||||
}
|
||||
break;
|
||||
case 'play':
|
||||
if (!playing) {
|
||||
playing = true;
|
||||
lastTimeAt = performance.now();
|
||||
if (!suppressed()) cb.onPlay(positionMs());
|
||||
}
|
||||
break;
|
||||
case 'pause':
|
||||
if (playing) {
|
||||
lastTimeSec = positionMs() / 1000;
|
||||
playing = false;
|
||||
if (!suppressed()) cb.onPause(positionMs());
|
||||
}
|
||||
break;
|
||||
case 'ended':
|
||||
playing = false;
|
||||
cb.onEnded();
|
||||
break;
|
||||
case 'extraList':
|
||||
if (ev.control.options.length > 0) {
|
||||
extraControls.set(ev.control.id, ev.control);
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
break;
|
||||
case 'extraCurrent': {
|
||||
const control = extraControls.get(ev.id);
|
||||
if (control && control.current !== ev.value) {
|
||||
extraControls.set(ev.id, { ...control, current: ev.value });
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'hello':
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// contentWindow is read live on every use: it changes when the frame
|
||||
// navigates, while ev.source comparison below stays valid because the
|
||||
// browsing context object is stable for the life of the element.
|
||||
const win = () => frame.contentWindow;
|
||||
|
||||
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
|
||||
for (const control of p.staticExtras?.(frame.src) ?? []) {
|
||||
extraControls.set(control.id, control);
|
||||
}
|
||||
if (extraControls.size > 0) {
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
}
|
||||
const probeExtras = () => {
|
||||
const current = win();
|
||||
if (current) p.probeExtras?.(current);
|
||||
};
|
||||
probeExtras();
|
||||
const extraProbeTimers = [1500, 3000].map((delay) =>
|
||||
window.setTimeout(probeExtras, delay)
|
||||
);
|
||||
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
|
||||
// debounced so drift-reconcile can't spam reloads (each reload
|
||||
// re-buffers and may replay an ad).
|
||||
let lastReloadAt = 0;
|
||||
const reloadTo = (sec: number) => {
|
||||
const now = performance.now();
|
||||
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
|
||||
lastReloadAt = now;
|
||||
suppressUntil = now + SUPPRESS_MS;
|
||||
lastTimeSec = Math.max(0, sec);
|
||||
lastTimeAt = now;
|
||||
playing = true; // start_from auto-resumes
|
||||
frame.src = p.reloadSeek!(frame.src, sec);
|
||||
};
|
||||
return {
|
||||
protocol: p.name,
|
||||
reloadBased: !!p.reloadSeek,
|
||||
play() {
|
||||
// Commands update state optimistically so positionMs()/paused()
|
||||
// reflect intent immediately — otherwise the 3s sync heartbeat
|
||||
// would fight the slow embed acknowledgement.
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
playing = true;
|
||||
lastTimeAt = performance.now();
|
||||
if (p.reloadSeek) {
|
||||
// No play command — resume by reloading at the current spot.
|
||||
reloadTo(lastTimeSec);
|
||||
return;
|
||||
}
|
||||
const w = win();
|
||||
if (w) p.play(w);
|
||||
},
|
||||
pause() {
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
lastTimeSec = positionMs() / 1000;
|
||||
playing = false;
|
||||
// Reload-based players (Kodik) have no pause — best-effort no-op.
|
||||
if (p.reloadSeek) return;
|
||||
const w = win();
|
||||
if (w) p.pause(w);
|
||||
},
|
||||
seekMs(ms: number) {
|
||||
if (p.reloadSeek) {
|
||||
reloadTo(ms / 1000);
|
||||
return;
|
||||
}
|
||||
suppressUntil = performance.now() + SUPPRESS_MS;
|
||||
lastTimeSec = ms / 1000;
|
||||
lastTimeAt = performance.now();
|
||||
const w = win();
|
||||
if (w) p.seek(w, ms / 1000);
|
||||
},
|
||||
setVolume(v01: number) {
|
||||
const w = win();
|
||||
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
|
||||
},
|
||||
extras: () => [...extraControls.values()],
|
||||
setExtra(id, value) {
|
||||
const control = extraControls.get(id);
|
||||
if (!control || !p.setExtra) return;
|
||||
suppressUntil = performance.now() + 1500;
|
||||
extraControls.set(id, { ...control, current: value });
|
||||
cb.onExtraControls([...extraControls.values()]);
|
||||
const current = win();
|
||||
if (current) p.setExtra(current, id, value);
|
||||
},
|
||||
positionMs,
|
||||
durationMs: () => Math.floor(durationSec * 1000),
|
||||
paused: () => !playing,
|
||||
destroy() {
|
||||
window.removeEventListener('message', handler);
|
||||
clearInterval(probeTimer);
|
||||
clearTimeout(giveUp);
|
||||
for (const timer of extraProbeTimers) clearTimeout(timer);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const handler = (ev: MessageEvent) => {
|
||||
if (ev.source !== frame.contentWindow) return;
|
||||
if (locked) {
|
||||
const e = locked.parse(ev.data);
|
||||
if (e) applyEvent(e);
|
||||
else if (import.meta.env.DEV) {
|
||||
console.debug('[embed] unrecognized message', ev.data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const p of probeSet) {
|
||||
const e = p.parse(ev.data);
|
||||
if (e) {
|
||||
locked = p;
|
||||
clearInterval(probeTimer);
|
||||
clearTimeout(giveUp);
|
||||
applyEvent(e);
|
||||
resolve(makeAdapter(p));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (import.meta.env.DEV) {
|
||||
console.debug('[embed] unrecognized message', ev.data);
|
||||
}
|
||||
};
|
||||
window.addEventListener('message', handler);
|
||||
|
||||
const sendProbes = () => {
|
||||
const w = win();
|
||||
if (!w || locked) return;
|
||||
for (const p of probeSet) p.probe(w);
|
||||
};
|
||||
// The inner player may boot slowly; keep probing until lock or timeout.
|
||||
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
|
||||
frame.addEventListener('load', sendProbes);
|
||||
sendProbes();
|
||||
|
||||
const giveUp = setTimeout(() => {
|
||||
if (locked) return;
|
||||
window.removeEventListener('message', handler);
|
||||
clearInterval(probeTimer);
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Emoji support for watch chat and reactions (item 16). A curated Unicode set
|
||||
// across categories (dependency-free — no multi-MB emoji-data bundle), plus
|
||||
// admin-managed custom image emojis served at /emoji/<name> and referenced by
|
||||
// :name: shortcodes. Recently-used emoji are remembered locally.
|
||||
|
||||
import { Store } from './store';
|
||||
import { rpc } from './rpc';
|
||||
|
||||
export interface CustomEmoji {
|
||||
name: string;
|
||||
mime: string;
|
||||
}
|
||||
|
||||
export const emojiStore = new Store<{
|
||||
custom: CustomEmoji[];
|
||||
recent: string[]; // unicode chars or :shortcode:
|
||||
}>({
|
||||
custom: [],
|
||||
recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'),
|
||||
});
|
||||
|
||||
export async function loadCustomEmojis() {
|
||||
try {
|
||||
const res = await rpc.call<{ emojis?: CustomEmoji[] }>(
|
||||
'GetCustomEmojis'
|
||||
);
|
||||
emojiStore.set({ custom: (res && res.emojis) || [] });
|
||||
} catch {
|
||||
/* not connected / not authed — leave empty */
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberEmoji(token: string) {
|
||||
const recent = [
|
||||
token,
|
||||
...emojiStore.get().recent.filter((r) => r !== token),
|
||||
].slice(0, 24);
|
||||
emojiStore.set({ recent });
|
||||
localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent));
|
||||
}
|
||||
|
||||
// Curated categories of common Unicode emoji.
|
||||
export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [
|
||||
{
|
||||
label: 'Smileys',
|
||||
emoji: [
|
||||
'😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰',
|
||||
'😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞',
|
||||
'😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶',
|
||||
'😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Gestures',
|
||||
emoji: [
|
||||
'👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌',
|
||||
'👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Hearts',
|
||||
emoji: [
|
||||
'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️',
|
||||
'💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥',
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Fun',
|
||||
emoji: [
|
||||
'🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸',
|
||||
'⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️',
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Render a chat message: plain text with :name: custom-emoji shortcodes
|
||||
// replaced by <img> tags. Returns React nodes (text is auto-escaped by React).
|
||||
export function renderChatText(text: string): (string | EmojiToken)[] {
|
||||
const out: (string | EmojiToken)[] = [];
|
||||
const re = /:([a-z0-9_]{1,32}):/g;
|
||||
const custom = new Set(emojiStore.get().custom.map((c) => c.name));
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (!custom.has(m[1])) continue;
|
||||
if (m.index > last) out.push(text.slice(last, m.index));
|
||||
out.push({ emojiName: m[1] });
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface EmojiToken {
|
||||
emojiName: string;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Presentation helpers shared across views — ported from web/app.js.
|
||||
|
||||
import type { Track } from './types';
|
||||
|
||||
export function fmtMs(ms: number | undefined | null): string {
|
||||
const s = Math.max(0, Math.floor((ms || 0) / 1000));
|
||||
const m = Math.floor(s / 60);
|
||||
return `${m}:${String(s % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
export function cover(seed: number): string {
|
||||
const h = (seed * 47) % 360;
|
||||
const h2 = (h + 40) % 360;
|
||||
return `linear-gradient(135deg, hsl(${h} 55% 42%), hsl(${h2} 60% 26%))`;
|
||||
}
|
||||
|
||||
export function seedOf(t: Track | null | undefined): number {
|
||||
const s = (t && (t.id || t.title)) || '?';
|
||||
let n = 0;
|
||||
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
|
||||
return n;
|
||||
}
|
||||
|
||||
// Prefer source-provided artwork; otherwise derive the YouTube thumbnail from
|
||||
// the video id (covers tracks stored before thumbnails were persisted).
|
||||
export function thumbFor(t: Track | null | undefined): string | null {
|
||||
if (!t) return null;
|
||||
if (t.thumbnailUrl) return t.thumbnailUrl;
|
||||
const m = (t.url || '').match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
|
||||
if (m) return `https://i.ytimg.com/vi/${m[1]}/mqdefault.jpg`;
|
||||
if (t.source === 1 && /^[\w-]{11}$/.test(t.id || '')) {
|
||||
return `https://i.ytimg.com/vi/${t.id}/mqdefault.jpg`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// TrackSource enum: 1 = YouTube, 6 = Yandex (see EchoionApi TrackTypes.hpp).
|
||||
export function sourceInfo(
|
||||
t: Track | null | undefined
|
||||
): { label: string; cls: string } | null {
|
||||
const url = (t && t.url) || '';
|
||||
if ((t && t.source === 6) || url.includes('yandex')) {
|
||||
return { label: 'YANDEX', cls: 'src-badge yandex' };
|
||||
}
|
||||
if ((t && t.source === 1) || url.includes('youtu')) {
|
||||
return { label: 'YOUTUBE', cls: 'src-badge' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function avatarColor(name: string | undefined | null): string {
|
||||
let n = 0;
|
||||
const s = name || '';
|
||||
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
|
||||
const h = n % 360;
|
||||
return `linear-gradient(135deg, hsl(${h} 60% 55%), hsl(${(h + 45) % 360} 55% 40%))`;
|
||||
}
|
||||
|
||||
export function coverStyle(t: Track | null | undefined): string {
|
||||
const thumb = thumbFor(t);
|
||||
if (thumb) return `url("${thumb}") center/cover`;
|
||||
if (t) return cover(seedOf(t));
|
||||
return 'linear-gradient(135deg, #2a1a4a, #0d0d1f)';
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// "Open original link" (item 18): a per-row external-link button that opens
|
||||
// the track's real source page in a new tab. Prefers the canonical original
|
||||
// URL (the long, expanded source page) over the shortened faumaray.ru link,
|
||||
// so users land on the real source rather than a redirector. Never the
|
||||
// CDN/stream URL (the DTO doesn't expose it).
|
||||
|
||||
import type { TrackAction } from '../components/TrackRow';
|
||||
import type { Track } from './types';
|
||||
import { ExternalLinkIcon } from '../components/icons';
|
||||
import { t } from '../i18n';
|
||||
|
||||
export function originalLinkUrl(track: Track): string | null {
|
||||
return track.url || track.shortenedUrl || null;
|
||||
}
|
||||
|
||||
export function openOriginal(track: Track) {
|
||||
const url = originalLinkUrl(track);
|
||||
if (url) window.open(url, '_blank', 'noopener');
|
||||
}
|
||||
|
||||
// A TrackRow action for the link, or null when the track has no openable URL.
|
||||
// Rendered as a dedicated icon button (not a whole-row click, which would
|
||||
// fight drag-and-drop and the other row actions).
|
||||
export function originalLinkAction(track: Track): TrackAction | null {
|
||||
if (!originalLinkUrl(track)) return null;
|
||||
return {
|
||||
icon: <ExternalLinkIcon />,
|
||||
title: t('Open original link'),
|
||||
onClick: () => openOriginal(track),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// 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 */
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
const DRIFT_THRESHOLD_SECONDS = 3;
|
||||
const SEEK_COOLDOWN_MS = 5000;
|
||||
|
||||
export function shouldCorrectVideoDrift(
|
||||
playerState: number,
|
||||
currentSeconds: number,
|
||||
targetSeconds: number,
|
||||
millisSinceSeek: number
|
||||
): boolean {
|
||||
return (
|
||||
playerState === 1 &&
|
||||
millisSinceSeek >= SEEK_COOLDOWN_MS &&
|
||||
Math.abs(currentSeconds - targetSeconds) > DRIFT_THRESHOLD_SECONDS
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Tiny hash router: keeps the active view in the URL so views are
|
||||
// bookmarkable and the browser back/forward buttons work. No dependency —
|
||||
// the app has a single flat set of views. The Watch view owns its own
|
||||
// `#watch/<room>` hash (see watch.ts joinRoom/leaveRoom); this router only
|
||||
// reads the room from it to auto-join a deep-linked room.
|
||||
|
||||
import { appStore, type ViewName } from './app';
|
||||
import { joinRoom, watchStore } from './watch';
|
||||
|
||||
const VIEWS: readonly ViewName[] = [
|
||||
'now',
|
||||
'queue',
|
||||
'search',
|
||||
'library',
|
||||
'stats',
|
||||
'watch',
|
||||
'server',
|
||||
'rpc',
|
||||
];
|
||||
|
||||
// The view named by the current hash, defaulting to `now`. Handles both
|
||||
// `#queue` and the watch form `#watch/<room>`.
|
||||
export function viewFromHash(): ViewName {
|
||||
const raw = location.hash.replace(/^#\/?/, '');
|
||||
const base = raw.split(/[/?]/)[0];
|
||||
return (VIEWS as readonly string[]).includes(base)
|
||||
? (base as ViewName)
|
||||
: 'now';
|
||||
}
|
||||
|
||||
function roomFromHash(): string | null {
|
||||
const m = location.hash.match(/^#watch\/([\w-]{1,48})/);
|
||||
return m ? m[1] : null;
|
||||
}
|
||||
|
||||
export function initRouter() {
|
||||
// Initial view comes from the hash (refresh / shared link).
|
||||
appStore.set({ view: viewFromHash() });
|
||||
|
||||
window.addEventListener('hashchange', () => {
|
||||
const view = viewFromHash();
|
||||
appStore.set({ view });
|
||||
// Auto-join a room that appears in the hash (pasted link, or
|
||||
// back/forward onto a different room). Leaving is always explicit.
|
||||
if (view === 'watch') {
|
||||
const room = roomFromHash();
|
||||
if (room && room !== watchStore.get().room) joinRoom(room);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { RpcClient } from './rpc';
|
||||
|
||||
// A minimal fake WebSocket that records sent frames and lets the test push
|
||||
// server frames back. Installed as the global before each RpcClient is made.
|
||||
class FakeWebSocket {
|
||||
static OPEN = 1;
|
||||
static instances: FakeWebSocket[] = [];
|
||||
readyState = FakeWebSocket.OPEN;
|
||||
sent: string[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
onmessage: ((ev: { data: string }) => void) | null = null;
|
||||
|
||||
constructor(public url: string) {
|
||||
FakeWebSocket.instances.push(this);
|
||||
queueMicrotask(() => this.onopen && this.onopen());
|
||||
}
|
||||
send(data: string) {
|
||||
this.sent.push(data);
|
||||
}
|
||||
close() {
|
||||
this.readyState = 3;
|
||||
this.onclose && this.onclose();
|
||||
}
|
||||
receive(obj: unknown) {
|
||||
this.onmessage && this.onmessage({ data: JSON.stringify(obj) });
|
||||
}
|
||||
}
|
||||
|
||||
function installFakes() {
|
||||
FakeWebSocket.instances = [];
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);
|
||||
// /config.json → same-origin /rpc bridge.
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => ({ json: async () => ({ rpcUrl: '/rpc' }) }))
|
||||
);
|
||||
vi.stubGlobal('location', {
|
||||
protocol: 'http:',
|
||||
host: 'bot.local',
|
||||
hostname: 'bot.local',
|
||||
});
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('RpcClient wire contract', () => {
|
||||
it('encodes method as the enum name and params as a JSON string', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
rpc.call('Seek', { position: 4200 });
|
||||
expect(ws.sent).toHaveLength(1);
|
||||
const frame = JSON.parse(ws.sent[0]);
|
||||
expect(frame.method).toBe('Seek');
|
||||
// params must be a JSON-encoded *string*, not a nested object.
|
||||
expect(typeof frame.params).toBe('string');
|
||||
expect(JSON.parse(frame.params)).toEqual({ position: 4200 });
|
||||
expect(frame.id).toBe(1);
|
||||
});
|
||||
|
||||
it('attaches the auth token once set', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
rpc.token = 'tok-abc';
|
||||
rpc.call('GetStatus');
|
||||
const frame = JSON.parse(ws.sent[0]);
|
||||
expect(frame.authToken).toBe('tok-abc');
|
||||
});
|
||||
|
||||
it('resolves a call by requestId and JSON-decodes the result string', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
const p = rpc.call('GetStatus');
|
||||
const frame = JSON.parse(ws.sent[0]);
|
||||
ws.receive({
|
||||
requestId: frame.id,
|
||||
success: true,
|
||||
result: JSON.stringify({ isPlaying: true, volume: 0.5 }),
|
||||
});
|
||||
await expect(p).resolves.toEqual({ isPlaying: true, volume: 0.5 });
|
||||
});
|
||||
|
||||
it('rejects with the decoded error payload', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
const p = rpc.call('Skip');
|
||||
const frame = JSON.parse(ws.sent[0]);
|
||||
ws.receive({
|
||||
requestId: frame.id,
|
||||
success: false,
|
||||
error: JSON.stringify({ code: 7, message: 'DJ required' }),
|
||||
});
|
||||
await expect(p).rejects.toMatchObject({
|
||||
code: 7,
|
||||
message: 'DJ required',
|
||||
});
|
||||
});
|
||||
|
||||
it('dispatches notifications with the data string decoded', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
const seen: unknown[] = [];
|
||||
rpc.on('playback.position', (d) => seen.push(d));
|
||||
ws.receive({
|
||||
event: 'playback.position',
|
||||
data: JSON.stringify({ position: 1000, duration: 200000 }),
|
||||
});
|
||||
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
|
||||
});
|
||||
|
||||
it('fires the wildcard listener with event name and data', async () => {
|
||||
installFakes();
|
||||
const rpc = new RpcClient();
|
||||
await rpc.connect();
|
||||
const ws = FakeWebSocket.instances[0];
|
||||
|
||||
const seen: Array<[unknown, unknown]> = [];
|
||||
rpc.on('*', (event, data) => seen.push([event, data]));
|
||||
ws.receive({
|
||||
event: 'queue.updated',
|
||||
data: JSON.stringify({ size: 3 }),
|
||||
});
|
||||
expect(seen).toEqual([['queue.updated', { size: 3 }]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
// Browser RPC client for the Echoion RPC server — TypeScript port of the
|
||||
// original web/rpc.js. The web UI is a desktop-style client: it connects
|
||||
// straight to the RPC WebSocket and speaks the exact same JSON protocol the
|
||||
// Qt desktop client uses.
|
||||
//
|
||||
// Wire contract (must match the server — do not "clean up"):
|
||||
// - request.method is the RpcMethod enum *name* (e.g. "Play").
|
||||
// - request.params is a JSON-encoded *string*, not a nested object.
|
||||
// - responses are correlated by requestId; result/error are JSON strings.
|
||||
// - notifications carry { event, data } where data is a JSON string.
|
||||
|
||||
export type RpcConnectionState = 'connected' | 'disconnected' | 'error';
|
||||
|
||||
export interface RpcError {
|
||||
code?: number;
|
||||
message: string;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
// Method names mirroring EchoionApi RpcTypes.hpp; the wire carries the name.
|
||||
export type RpcMethodName =
|
||||
| 'Authenticate'
|
||||
| 'AuthenticateByAddress'
|
||||
| 'Logout'
|
||||
| 'Play'
|
||||
| 'Pause'
|
||||
| 'Resume'
|
||||
| 'Stop'
|
||||
| 'Skip'
|
||||
| 'Seek'
|
||||
| 'SetVolume'
|
||||
| 'ToggleShuffle'
|
||||
| 'ToggleRepeat'
|
||||
| 'ToggleAutoplay'
|
||||
| 'ShuffleQueue'
|
||||
| 'QueueTrack'
|
||||
| 'RemoveFromQueue'
|
||||
| 'ClearQueue'
|
||||
| 'GetQueue'
|
||||
| 'MoveInQueue'
|
||||
| 'SearchTracks'
|
||||
| 'GetCurrentTrack'
|
||||
| 'GetStatus'
|
||||
| 'GetServerInfo'
|
||||
| 'GetPlaylist'
|
||||
| 'GetPlaylists'
|
||||
| 'SavePlaylist'
|
||||
| 'LoadPlaylist'
|
||||
| 'DeletePlaylist'
|
||||
| 'GetHistory'
|
||||
| 'GetStats'
|
||||
| 'GetLyrics'
|
||||
| 'GetFavorites'
|
||||
| 'AddFavorite'
|
||||
| 'RemoveFavorite'
|
||||
| 'VoteSkip'
|
||||
| 'Announce'
|
||||
| 'GetAggregateStats'
|
||||
| 'ReloadConfig'
|
||||
| 'RestartWebInterface'
|
||||
| 'ManageUsers'
|
||||
| 'GetAuditLog'
|
||||
| 'GetUserPrefs'
|
||||
| 'SetUserPrefs'
|
||||
| 'GetCustomEmojis'
|
||||
| 'AddCustomEmoji'
|
||||
| 'RemoveCustomEmoji';
|
||||
|
||||
type Pending = {
|
||||
resolve: (value: unknown) => void;
|
||||
reject: (err: RpcError) => void;
|
||||
};
|
||||
|
||||
export class RpcClient {
|
||||
private ws: WebSocket | null = null;
|
||||
private nextId = 1;
|
||||
private pending = new Map<number, Pending>();
|
||||
private listeners = new Map<string, Array<(...args: unknown[]) => void>>();
|
||||
token: string | null = null;
|
||||
onState: (s: RpcConnectionState) => void = () => {};
|
||||
// Fired after an automatic reconnect succeeds so the app can
|
||||
// re-authenticate and refresh its state.
|
||||
onReconnected: () => void = () => {};
|
||||
private wantReconnect = false;
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private reconnectDelay = 2000;
|
||||
|
||||
async connect(): Promise<void> {
|
||||
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
|
||||
try {
|
||||
cfg = await fetch('/config.json').then((r) => r.json());
|
||||
} catch {
|
||||
/* fall back to derived URL below */
|
||||
}
|
||||
// A path-only rpcUrl (default "/rpc") means the same-origin bridge on
|
||||
// the web server; absolute URLs and the bare-port fallback still work.
|
||||
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
let url: string;
|
||||
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
|
||||
url = `${wsProto}://${location.host}${cfg.rpcUrl}`;
|
||||
} else if (cfg.rpcUrl && cfg.rpcUrl.length) {
|
||||
url = cfg.rpcUrl;
|
||||
} else {
|
||||
url = `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.ws = new WebSocket(url);
|
||||
this.ws.onopen = () => {
|
||||
this.wantReconnect = true;
|
||||
this.reconnectDelay = 2000;
|
||||
this.onState('connected');
|
||||
resolve();
|
||||
};
|
||||
this.ws.onclose = () => {
|
||||
this.onState('disconnected');
|
||||
this.failAll('Connection closed');
|
||||
this.scheduleReconnect();
|
||||
};
|
||||
this.ws.onerror = () => {
|
||||
this.onState('error');
|
||||
reject(new Error('WebSocket error'));
|
||||
};
|
||||
this.ws.onmessage = (ev) => this.onMessage(String(ev.data));
|
||||
});
|
||||
}
|
||||
|
||||
// Reconnect with backoff after an unexpected close. Only armed once a
|
||||
// connection has succeeded; an explicit disconnect() disarms it.
|
||||
private scheduleReconnect() {
|
||||
if (!this.wantReconnect || this.reconnectTimer) return;
|
||||
const delay = this.reconnectDelay;
|
||||
this.reconnectDelay = Math.min(this.reconnectDelay * 2, 15000);
|
||||
this.reconnectTimer = setTimeout(async () => {
|
||||
this.reconnectTimer = null;
|
||||
try {
|
||||
await this.connect();
|
||||
this.onReconnected();
|
||||
} catch {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.wantReconnect = false;
|
||||
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
get connected(): boolean {
|
||||
return !!this.ws && this.ws.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
private decode(s: unknown): unknown {
|
||||
if (s == null) return null;
|
||||
if (typeof s !== 'string') return s;
|
||||
try {
|
||||
return JSON.parse(s);
|
||||
} catch {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
private onMessage(raw: string) {
|
||||
let msg: Record<string, unknown>;
|
||||
try {
|
||||
msg = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if ('requestId' in msg) {
|
||||
const p = this.pending.get(msg.requestId as number);
|
||||
if (!p) return;
|
||||
this.pending.delete(msg.requestId as number);
|
||||
if (msg.success) {
|
||||
p.resolve(this.decode(msg.result));
|
||||
} else {
|
||||
p.reject(
|
||||
(this.decode(msg.error) as RpcError) || {
|
||||
message: 'RPC error',
|
||||
}
|
||||
);
|
||||
}
|
||||
} else if ('event' in msg) {
|
||||
const data = this.decode(msg.data);
|
||||
const event = msg.event as string;
|
||||
(this.listeners.get(event) || []).forEach((cb) => cb(data));
|
||||
(this.listeners.get('*') || []).forEach((cb) => cb(event, data));
|
||||
}
|
||||
}
|
||||
|
||||
private failAll(message: string) {
|
||||
for (const [, p] of this.pending) p.reject({ message });
|
||||
this.pending.clear();
|
||||
}
|
||||
|
||||
call<T = unknown>(
|
||||
method: RpcMethodName,
|
||||
params: Record<string, unknown> = {}
|
||||
): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.connected || !this.ws) {
|
||||
reject({ message: 'Not connected' });
|
||||
return;
|
||||
}
|
||||
const id = this.nextId++;
|
||||
const req: Record<string, unknown> = {
|
||||
id,
|
||||
method,
|
||||
params: JSON.stringify(params),
|
||||
};
|
||||
if (this.token) req.authToken = this.token;
|
||||
this.pending.set(id, {
|
||||
resolve: resolve as (v: unknown) => void,
|
||||
reject,
|
||||
});
|
||||
this.ws.send(JSON.stringify(req));
|
||||
});
|
||||
}
|
||||
|
||||
on(event: string, cb: (...args: unknown[]) => void) {
|
||||
if (!this.listeners.has(event)) this.listeners.set(event, []);
|
||||
this.listeners.get(event)!.push(cb);
|
||||
}
|
||||
|
||||
authenticate(token: string) {
|
||||
this.token = token;
|
||||
return this.call('Authenticate', { token });
|
||||
}
|
||||
|
||||
requestToken(nickname: string) {
|
||||
return this.call('Authenticate', { nickname });
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton shared by the whole app (mirrors the vanilla `const rpc`).
|
||||
export const rpc = new RpcClient();
|
||||
@@ -0,0 +1,111 @@
|
||||
// Global keyboard shortcuts for desktop control. Ignored while typing in a
|
||||
// field, and while any modifier is held (so browser/OS chords still work).
|
||||
|
||||
import { appStore, safeCall, showView } from './app';
|
||||
|
||||
// List shown in the "?" cheat-sheet overlay. English source strings; the
|
||||
// overlay translates the labels.
|
||||
export const SHORTCUTS: Array<{ keys: string; label: string }> = [
|
||||
{ keys: 'Space', label: 'Play / pause' },
|
||||
{ keys: '← / →', label: 'Seek 5s' },
|
||||
{ keys: '↑ / ↓', label: 'Volume' },
|
||||
{ keys: 'N', label: 'Skip / vote skip' },
|
||||
{ keys: '/', label: 'Focus search' },
|
||||
{ keys: '?', label: 'This help' },
|
||||
];
|
||||
|
||||
function isTyping(): boolean {
|
||||
const el = document.activeElement as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
const tag = el.tagName;
|
||||
return (
|
||||
tag === 'INPUT' ||
|
||||
tag === 'TEXTAREA' ||
|
||||
tag === 'SELECT' ||
|
||||
el.isContentEditable
|
||||
);
|
||||
}
|
||||
|
||||
async function togglePlay() {
|
||||
const st = appStore.get().status || {};
|
||||
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
|
||||
else await safeCall('Resume');
|
||||
}
|
||||
|
||||
function seekBy(deltaSec: number) {
|
||||
const s = appStore.get();
|
||||
const dur = s.durationMs || 0;
|
||||
if (!dur) return;
|
||||
const pos = Math.max(0, Math.min(dur, s.positionMs + deltaSec * 1000));
|
||||
safeCall('Seek', { position: Math.round(pos) });
|
||||
}
|
||||
|
||||
function volumeBy(deltaPct: number) {
|
||||
const st = appStore.get().status || {};
|
||||
const cur = Math.round((st.volume ?? 0.5) * 100);
|
||||
const next = Math.max(0, Math.min(100, cur + deltaPct));
|
||||
safeCall('SetVolume', { volume: next / 100 });
|
||||
}
|
||||
|
||||
function skip() {
|
||||
const id = appStore.get().identity;
|
||||
// Mirror the Now view: DJ/admin force-skip, everyone else votes.
|
||||
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
|
||||
else safeCall('VoteSkip');
|
||||
}
|
||||
|
||||
export function initShortcuts() {
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
if (isTyping()) {
|
||||
if (e.key === 'Escape') {
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch (e.key) {
|
||||
case ' ':
|
||||
e.preventDefault();
|
||||
void togglePlay();
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
seekBy(-5);
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
seekBy(5);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
volumeBy(5);
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
volumeBy(-5);
|
||||
break;
|
||||
case 'n':
|
||||
case 'N':
|
||||
skip();
|
||||
break;
|
||||
case '/':
|
||||
e.preventDefault();
|
||||
showView('search');
|
||||
setTimeout(() => {
|
||||
document
|
||||
.querySelector<HTMLInputElement>('#view-search input')
|
||||
?.focus();
|
||||
}, 50);
|
||||
break;
|
||||
case '?':
|
||||
appStore.set({ shortcutsOpen: !appStore.get().shortcutsOpen });
|
||||
break;
|
||||
case 'Escape': {
|
||||
const s = appStore.get();
|
||||
if (s.shortcutsOpen) appStore.set({ shortcutsOpen: false });
|
||||
else if (s.sidebarOpen) appStore.set({ sidebarOpen: false });
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Minimal external store + useSyncExternalStore hook. One immutable snapshot
|
||||
// for the whole app state (the vanilla UI re-rendered everything on any
|
||||
// refresh anyway, so per-field granularity buys nothing at this scale).
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
export class Store<T> {
|
||||
private state: T;
|
||||
private listeners = new Set<() => void>();
|
||||
|
||||
constructor(initial: T) {
|
||||
this.state = initial;
|
||||
}
|
||||
|
||||
get(): T {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
set(partial: Partial<T>) {
|
||||
this.state = { ...this.state, ...partial };
|
||||
this.listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
subscribe = (listener: () => void): (() => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function useStore<T>(store: Store<T>): T {
|
||||
return useSyncExternalStore(store.subscribe, () => store.get());
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { renderTsMarkup } from './tsMarkup';
|
||||
|
||||
const html = (src: string) => renderToStaticMarkup(<>{renderTsMarkup(src)}</>);
|
||||
|
||||
describe('renderTsMarkup', () => {
|
||||
it('renders markdown bold/italic/code', () => {
|
||||
expect(html('**bold** and *italic* and `code`')).toBe(
|
||||
'<p><strong>bold</strong> and <em>italic</em> and <code>code</code></p>'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders BBCode bold/underline/color', () => {
|
||||
expect(html('[b]x[/b] [u]y[/u] [color=#f00]z[/color]')).toBe(
|
||||
'<p><strong>x</strong> <u>y</u> <span style="color:#f00">z</span></p>'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders markdown and BBCode links with safe attributes', () => {
|
||||
expect(html('[site](https://example.com)')).toBe(
|
||||
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">site</a></p>'
|
||||
);
|
||||
expect(html('[url]https://example.com[/url]')).toBe(
|
||||
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">https://example.com</a></p>'
|
||||
);
|
||||
});
|
||||
|
||||
it('escapes raw HTML (no injection)', () => {
|
||||
// React escapes text nodes; the <img> is rendered as literal text.
|
||||
const out = html('<img src=x onerror=alert(1)>');
|
||||
expect(out).not.toContain('<img');
|
||||
expect(out).toContain('<img');
|
||||
});
|
||||
|
||||
it('renders headers and blockquotes', () => {
|
||||
expect(html('# Title')).toBe('<h3>Title</h3>');
|
||||
expect(html('> quoted')).toBe(
|
||||
'<blockquote><p>quoted</p></blockquote>'
|
||||
);
|
||||
});
|
||||
|
||||
it('renders the TS6 collapsible details container', () => {
|
||||
const out = html(':::details Info\nbody\n:::');
|
||||
expect(out).toContain('<details open="">');
|
||||
expect(out).toContain('<summary>Info</summary>');
|
||||
expect(out).toContain('<p>body</p>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
// Renders the TeamSpeak-6 markdown + BBCode subset the bot's replies use so
|
||||
// the announce composer (item 14) can preview exactly what subscribers see.
|
||||
// Security: text is escaped first (React escapes by default since we return
|
||||
// elements, never dangerouslySetInnerHTML), so untrusted markup can't inject
|
||||
// HTML — only the recognized tags below produce formatting.
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
// Inline pass: **bold**, *italic* / _italic_, ~~strike~~, `code`, [text](url),
|
||||
// and the BBCode equivalents [b] [i] [u] [s] [url] [color=…]. Applied to one
|
||||
// line's worth of text.
|
||||
function renderInline(text: string, keyBase: string): ReactNode[] {
|
||||
// Ordered so the first matching rule wins at each position.
|
||||
const rules: Array<{
|
||||
re: RegExp;
|
||||
render: (m: RegExpExecArray, key: string) => ReactNode;
|
||||
}> = [
|
||||
{
|
||||
re: /\*\*([^*]+)\*\*/,
|
||||
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
|
||||
},
|
||||
{
|
||||
re: /\[b\]([\s\S]*?)\[\/b\]/i,
|
||||
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
|
||||
},
|
||||
{
|
||||
re: /(?:\*([^*]+)\*|_([^_]+)_)/,
|
||||
render: (m, k) => (
|
||||
<em key={k}>{renderInline(m[1] ?? m[2], k)}</em>
|
||||
),
|
||||
},
|
||||
{
|
||||
re: /\[i\]([\s\S]*?)\[\/i\]/i,
|
||||
render: (m, k) => <em key={k}>{renderInline(m[1], k)}</em>,
|
||||
},
|
||||
{
|
||||
re: /\[u\]([\s\S]*?)\[\/u\]/i,
|
||||
render: (m, k) => <u key={k}>{renderInline(m[1], k)}</u>,
|
||||
},
|
||||
{
|
||||
re: /(?:~~([^~]+)~~|\[s\]([\s\S]*?)\[\/s\])/i,
|
||||
render: (m, k) => <s key={k}>{renderInline(m[1] ?? m[2], k)}</s>,
|
||||
},
|
||||
{
|
||||
re: /`([^`]+)`/,
|
||||
render: (m, k) => <code key={k}>{m[1]}</code>,
|
||||
},
|
||||
{
|
||||
re: /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/,
|
||||
render: (m, k) => (
|
||||
<a key={k} href={m[2]} target="_blank" rel="noopener noreferrer">
|
||||
{m[1]}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
re: /\[url\]([\s\S]*?)\[\/url\]/i,
|
||||
render: (m, k) => (
|
||||
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
|
||||
{m[1]}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
re: /\[url=([^\]]+)\]([\s\S]*?)\[\/url\]/i,
|
||||
render: (m, k) => (
|
||||
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
|
||||
{renderInline(m[2], k)}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
re: /\[color=([#\w]+)\]([\s\S]*?)\[\/color\]/i,
|
||||
render: (m, k) => (
|
||||
<span key={k} style={{ color: m[1] }}>
|
||||
{renderInline(m[2], k)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
// Find the earliest match across all rules, emit the text before it, the
|
||||
// rendered node, then recurse on the remainder.
|
||||
let best: { index: number; length: number; node: ReactNode } | null = null;
|
||||
let counter = 0;
|
||||
for (const rule of rules) {
|
||||
const m = rule.re.exec(text);
|
||||
if (m && (best === null || m.index < best.index)) {
|
||||
best = {
|
||||
index: m.index,
|
||||
length: m[0].length,
|
||||
node: rule.render(m, `${keyBase}-${counter++}`),
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!best) return [text];
|
||||
const before = text.slice(0, best.index);
|
||||
const after = text.slice(best.index + best.length);
|
||||
return [
|
||||
...(before ? [before] : []),
|
||||
best.node,
|
||||
...renderInline(after, `${keyBase}-r`),
|
||||
];
|
||||
}
|
||||
|
||||
// Block pass: headers (#, ##, ###), blockquotes (>), and the TS6 collapsible
|
||||
// container (:::details Title … :::). Everything else is a paragraph line.
|
||||
export function renderTsMarkup(source: string): ReactNode {
|
||||
const lines = source.split('\n');
|
||||
const blocks: ReactNode[] = [];
|
||||
let i = 0;
|
||||
let key = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
const details = /^:::details\s+(.*)$/.exec(line.trim());
|
||||
if (details) {
|
||||
const inner: string[] = [];
|
||||
i++;
|
||||
while (i < lines.length && lines[i].trim() !== ':::') {
|
||||
inner.push(lines[i]);
|
||||
i++;
|
||||
}
|
||||
i++; // skip closing :::
|
||||
blocks.push(
|
||||
<details key={key++} open>
|
||||
<summary>{renderInline(details[1], `s${key}`)}</summary>
|
||||
{renderTsMarkup(inner.join('\n'))}
|
||||
</details>
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const header = /^(#{1,3})\s+(.*)$/.exec(line);
|
||||
if (header) {
|
||||
const level = header[1].length;
|
||||
const content = renderInline(header[2], `h${key}`);
|
||||
blocks.push(
|
||||
level === 1 ? (
|
||||
<h3 key={key++}>{content}</h3>
|
||||
) : level === 2 ? (
|
||||
<h4 key={key++}>{content}</h4>
|
||||
) : (
|
||||
<h5 key={key++}>{content}</h5>
|
||||
)
|
||||
);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^>\s?/.test(line)) {
|
||||
const quote: string[] = [];
|
||||
while (i < lines.length && /^>\s?/.test(lines[i])) {
|
||||
quote.push(lines[i].replace(/^>\s?/, ''));
|
||||
i++;
|
||||
}
|
||||
blocks.push(
|
||||
<blockquote key={key++}>
|
||||
{renderTsMarkup(quote.join('\n'))}
|
||||
</blockquote>
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
blocks.push(<p key={key++}>{renderInline(line, `p${key}`)}</p>);
|
||||
i++;
|
||||
}
|
||||
|
||||
return <>{blocks}</>;
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// Shapes of the RPC payloads the UI consumes (subset of the server DTOs;
|
||||
// fields the UI does not read are omitted).
|
||||
|
||||
export interface Track {
|
||||
id?: string;
|
||||
title?: string;
|
||||
artist?: string;
|
||||
url?: string; // originalUrl (play-by-url)
|
||||
shortenedUrl?: string; // faumaray.ru short link, preferred for opening
|
||||
thumbnailUrl?: string;
|
||||
duration?: number; // ms
|
||||
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
|
||||
}
|
||||
|
||||
export interface QueueEntry {
|
||||
queueId: number;
|
||||
track: Track;
|
||||
isPlaying?: boolean;
|
||||
addedBy?: string;
|
||||
}
|
||||
|
||||
export interface Status {
|
||||
isPlaying?: boolean;
|
||||
isPaused?: boolean;
|
||||
shuffle?: boolean;
|
||||
repeat?: boolean;
|
||||
autoplay?: boolean;
|
||||
volume?: number;
|
||||
skipVotes?: number;
|
||||
skipVotesNeeded?: number;
|
||||
skipVoted?: boolean;
|
||||
}
|
||||
|
||||
export interface Identity {
|
||||
uid?: string;
|
||||
nickname?: string;
|
||||
isAdmin?: boolean;
|
||||
isDj?: boolean;
|
||||
token?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ServerInfo {
|
||||
version?: string;
|
||||
uptimeSeconds?: number;
|
||||
onlineSubscribers?: number;
|
||||
onlineSubscriberNames?: string[];
|
||||
// Parallel to onlineSubscriberNames (same order): TeamSpeak uids so the
|
||||
// "Listening now" card can fetch each listener's avatar.
|
||||
onlineSubscriberUids?: string[];
|
||||
}
|
||||
|
||||
export interface AggregateStats {
|
||||
tracksToday: number;
|
||||
playsTotal: number;
|
||||
listeningMsToday: number;
|
||||
queueAdditionsToday: number;
|
||||
skipsToday: number;
|
||||
skipsTotal: number;
|
||||
topRequesters: Array<{ uid?: string; nickname: string; count: number }>;
|
||||
youtubeCount: number;
|
||||
yandexCount: number;
|
||||
otherCount: number;
|
||||
}
|
||||
|
||||
export interface Subscriber {
|
||||
uid: string;
|
||||
nickname?: string;
|
||||
online?: boolean;
|
||||
}
|
||||
|
||||
export interface Playlist {
|
||||
id: string;
|
||||
name: string;
|
||||
trackCount: number;
|
||||
}
|
||||
|
||||
// GetPlaylist response — a playlist's full track list (Dto::PlaylistContents).
|
||||
export interface PlaylistContents {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
tracks: Track[];
|
||||
}
|
||||
|
||||
// GetAuditLog response entry (Dto::AuditEntryDto). `method` is the numeric
|
||||
// RpcMethod enum value; map it to a name with lib/auditMethods.
|
||||
export interface AuditEntry {
|
||||
clientId: number;
|
||||
method: number;
|
||||
timestamp: number; // unix seconds
|
||||
}
|
||||
|
||||
// GetLyrics response (Dto::LyricsResponse).
|
||||
export interface LyricsLine {
|
||||
ms: number; // offset from track start
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface LyricsResult {
|
||||
found: boolean;
|
||||
plain: string;
|
||||
synced: LyricsLine[];
|
||||
source?: string;
|
||||
title?: string;
|
||||
artist?: string;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState, type RefObject } from 'react';
|
||||
|
||||
// Auto-hides the Watch player's overlay controls (and the mouse cursor) after
|
||||
// `idleMs` of no input while a video is PLAYING, and reveals them instantly on
|
||||
// any input — like a regular video player, in both windowed and fullscreen.
|
||||
// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is
|
||||
// open) is left to CSS (:hover / :focus-within); this hook only owns the idle
|
||||
// timeout and the "always visible while paused" rule. Returns the hidden flag.
|
||||
export function useControlsAutoHide(
|
||||
shellRef: RefObject<HTMLElement | null>,
|
||||
opts: { playing: boolean; enabled?: boolean; idleMs?: number }
|
||||
): boolean {
|
||||
const { playing, enabled = true, idleMs = 3000 } = opts;
|
||||
const [hidden, setHidden] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const shell = shellRef.current;
|
||||
// Paused, disabled, or no element: always show, no timer.
|
||||
if (!shell || !enabled || !playing) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
let timer: number | undefined;
|
||||
const arm = () => {
|
||||
if (timer) window.clearTimeout(timer);
|
||||
timer = window.setTimeout(() => setHidden(true), idleMs);
|
||||
};
|
||||
const reveal = () => {
|
||||
setHidden(false); // React bails when already false → no churn
|
||||
arm();
|
||||
};
|
||||
const events = [
|
||||
'mousemove',
|
||||
'pointerdown',
|
||||
'touchstart',
|
||||
'keydown',
|
||||
'focusin',
|
||||
] as const;
|
||||
for (const e of events) {
|
||||
shell.addEventListener(e, reveal, { passive: true });
|
||||
}
|
||||
// Entering/leaving fullscreen counts as activity.
|
||||
document.addEventListener('fullscreenchange', reveal);
|
||||
arm();
|
||||
return () => {
|
||||
if (timer) window.clearTimeout(timer);
|
||||
for (const e of events) shell.removeEventListener(e, reveal);
|
||||
document.removeEventListener('fullscreenchange', reveal);
|
||||
};
|
||||
}, [shellRef, playing, enabled, idleMs]);
|
||||
|
||||
return hidden;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,75 @@
|
||||
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
|
||||
// Playing video preview use it; the script is injected once and callers await
|
||||
// the same readiness promise.
|
||||
//
|
||||
// Console-error triage for the YouTube embeds (as seen in production behind
|
||||
// the reverse proxy):
|
||||
// - "Failed to execute 'postMessage' … target origin ('https://www.youtube.com')
|
||||
// does not match the recipient window's origin" — the IFrame API guesses the
|
||||
// embedder when no explicit origin is passed; fixed by youtubeEmbedVars().
|
||||
// - "__Secure-YEC has been rejected … SameSite" — YouTube setting its own
|
||||
// third-party cookie inside the iframe; the youtube-nocookie.com host
|
||||
// reduces this noise but cannot eliminate it.
|
||||
// - "Attempt to postMessage on disconnected port" — fires when an iframe is
|
||||
// torn down mid-message (source switch, room leave); harmless.
|
||||
|
||||
// Privacy-enhanced embed host (see cookie note above). Pass as the
|
||||
// (undeclared in @types/youtube) top-level `host` option of YT.Player.
|
||||
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
|
||||
|
||||
// playerVars every embed must pass: native controls stay hidden (the custom
|
||||
// bar / sync logic owns playback), and enablejsapi + origin keep the API's
|
||||
// postMessage channel bound to this page's real origin.
|
||||
export function youtubeEmbedVars(
|
||||
extra?: Record<string, string | number>
|
||||
): YT.PlayerVars {
|
||||
return {
|
||||
rel: 0,
|
||||
modestbranding: 1,
|
||||
controls: 0,
|
||||
disablekb: 1,
|
||||
iv_load_policy: 3,
|
||||
enablejsapi: 1,
|
||||
origin: location.origin,
|
||||
widget_referrer: location.origin,
|
||||
...extra,
|
||||
} as YT.PlayerVars;
|
||||
}
|
||||
|
||||
let promise: Promise<void> | null = null;
|
||||
|
||||
export function loadYouTubeApi(): Promise<void> {
|
||||
if (promise) return promise;
|
||||
promise = new Promise((resolve) => {
|
||||
const w = window as unknown as {
|
||||
YT?: typeof YT;
|
||||
onYouTubeIframeAPIReady?: () => void;
|
||||
};
|
||||
if (w.YT && w.YT.Player) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const prev = w.onYouTubeIframeAPIReady;
|
||||
w.onYouTubeIframeAPIReady = () => {
|
||||
prev?.();
|
||||
resolve();
|
||||
};
|
||||
if (!document.querySelector('script[data-yt-iframe-api]')) {
|
||||
const tag = document.createElement('script');
|
||||
tag.src = 'https://www.youtube.com/iframe_api';
|
||||
tag.dataset.ytIframeApi = '1';
|
||||
document.head.appendChild(tag);
|
||||
}
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
|
||||
// Extract an 11-char YouTube video id from a watch/share/embed URL or a bare
|
||||
// id, or null when the URL is not YouTube.
|
||||
export function youtubeIdFromUrl(url: string | undefined | null): string | null {
|
||||
if (!url) return null;
|
||||
const m = url.match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
|
||||
if (m) return m[1];
|
||||
if (/^[\w-]{11}$/.test(url)) return url;
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user