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

No files matched your search

+1 -2
View File
@@ -37,7 +37,6 @@ target_link_libraries(EchoionWeb
Void::Data Void::Data
Void::Log Void::Log
Void::Async Void::Async
Void::Net
PRIVATE PRIVATE
Threads::Threads Threads::Threads
Boost::beast Boost::beast
@@ -56,7 +55,7 @@ endif()
# That build output is what ships next to the runtime binary (default webRoot # That build output is what ships next to the runtime binary (default webRoot
# "./web", relative to the working directory) and is installed. Opt out with # "./web", relative to the working directory) and is installed. Opt out with
# -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job). # -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job).
option(ECHOION_BUILD_WEB "Build the React web frontend with npm/vite" ON) option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend") set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist") set(_web_dist "${_web_frontend}/web-dist")
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "Echoion Music Bot", "name": "Echoion Music Bot",
"short_name": "Echoion", "short_name": "Echoion",
"description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.", "description": "Control the Echoion TeamSpeak music bot and view live server activity.",
"start_url": "/", "start_url": "/",
"scope": "/", "scope": "/",
"display": "standalone", "display": "standalone",
+6 -7
View File
@@ -1,12 +1,12 @@
// Minimal, dependency-free service worker: makes the panel installable and // Minimal, dependency-free service worker: makes the panel installable and
// keeps the app shell available offline. It deliberately does NOT touch the // keeps the app shell available offline. It deliberately does NOT touch the
// live surfaces — /rpc and /ws (WebSockets aren't interceptable anyway), // live surfaces — /rpc (WebSockets aren't interceptable anyway),
// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI // /config.json, /api/* and /avatar/* all fall through to the network so the
// never shows stale identity/config. // UI never shows stale identity/config.
// Bump when the player shell changes materially so installed/PWA clients do // Bump when the player shell changes materially so installed/PWA clients do
// not retain an index that references a removed hashed bundle. // not retain an index that references a removed hashed bundle.
const CACHE = 'echoion-shell-v2'; const CACHE = 'echoion-shell-v4';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg']; const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
@@ -48,10 +48,9 @@ self.addEventListener('fetch', (event) => {
// Never intercept the live control/config/media surfaces. // Never intercept the live control/config/media surfaces.
if ( if (
url.pathname === '/config.json' || url.pathname === '/config.json' ||
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/rpc') || url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/ws') || url.pathname.startsWith('/avatar')
url.pathname.startsWith('/avatar') ||
url.pathname.startsWith('/emoji')
) { ) {
return; return;
} }
+2 -18
View File
@@ -5,11 +5,8 @@
// - orphaned: present in ru.ts but never used as a literal key // - orphaned: present in ru.ts but never used as a literal key
// //
// Dynamic keys can't be found by this scan and must be checked by hand: // Dynamic keys can't be found by this scan and must be checked by hand:
// - watch.ts state strings rendered via t(w.playerEmpty)
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label) // - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
// - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub) // - HEADS view titles/subtitles (App.tsx) rendered via t(title)/t(sub)
// - server-sent watch.denied reasons (grep sendDenied in
// EchoionWeb/src/WatchSession.cpp) rendered via t(msg.reason)
// Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC // Orphans reported here may be one of those dynamic keys — the KNOWN_DYNAMIC
// list below suppresses the ones we know about. // list below suppresses the ones we know about.
// //
@@ -25,17 +22,6 @@ const ruFile = join(srcDir, 'i18n', 'ru.ts');
// Keys reached through variables (see header); keep in sync by hand. // Keys reached through variables (see header); keep in sync by hand.
const KNOWN_DYNAMIC = new Set([ const KNOWN_DYNAMIC = new Set([
// watch.ts playerEmpty / state strings
'Nothing loaded — paste a URL above',
'Twitch embeds require HTTPS — open the site via its https:// domain',
// server-sent watch.denied reasons (grep sendDenied in WatchSession.cpp)
'Sign in to control playback',
'Only the host controls playback',
'Watch queue is full',
'Watch queue is empty',
'Live stream — cannot seek',
'That viewer is no longer here',
'Only signed-in viewers can host',
// connection state rendered via t(s.connection) in Sidebar.tsx // connection state rendered via t(s.connection) in Sidebar.tsx
'connected', 'connected',
'disconnected', 'disconnected',
@@ -48,8 +34,8 @@ const KNOWN_DYNAMIC = new Set([
'Focus search', 'Focus search',
'This help', 'This help',
// HEADS view titles/subtitles (App.tsx) // HEADS view titles/subtitles (App.tsx)
'Now Playing', 'Dashboard',
'What Echoion is streaming to the channel', 'Live playback and TeamSpeak server activity',
'Queue', 'Queue',
'Reorder and manage upcoming tracks', 'Reorder and manage upcoming tracks',
'Search', 'Search',
@@ -58,8 +44,6 @@ const KNOWN_DYNAMIC = new Set([
'Your favorites and saved playlists', 'Your favorites and saved playlists',
'History & Stats', 'History & Stats',
'Playback history and server insights', 'Playback history and server insights',
'Watch Together',
'Synced viewing room — everyone in step',
'Server & Admin', 'Server & Admin',
'Manage subscribers and broadcast', 'Manage subscribers and broadcast',
'RPC / API', 'RPC / API',
+6 -26
View File
@@ -1,6 +1,5 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import { appStore, boot, getStoredToken, toast } from './lib/app'; import { appStore, boot } from './lib/app';
import { initWatch } from './lib/watch';
import { initRouter } from './lib/router'; import { initRouter } from './lib/router';
import { initShortcuts } from './lib/shortcuts'; import { initShortcuts } from './lib/shortcuts';
import { initMediaSession } from './lib/mediaSession'; import { initMediaSession } from './lib/mediaSession';
@@ -11,24 +10,20 @@ import { Sidebar } from './components/Sidebar';
import { MiniPlayer } from './components/MiniPlayer'; import { MiniPlayer } from './components/MiniPlayer';
import { DialogHost } from './components/DialogHost'; import { DialogHost } from './components/DialogHost';
import { ShortcutsHelp } from './components/ShortcutsHelp'; import { ShortcutsHelp } from './components/ShortcutsHelp';
import { NowView } from './views/NowView'; import { DashboardView } from './views/DashboardView';
import { QueueView } from './views/QueueView'; import { QueueView } from './views/QueueView';
import { SearchView } from './views/SearchView'; import { SearchView } from './views/SearchView';
import { LibraryView } from './views/LibraryView'; import { LibraryView } from './views/LibraryView';
import { StatsView } from './views/StatsView'; import { StatsView } from './views/StatsView';
import { WatchView } from './views/WatchView';
import { ServerView } from './views/ServerView'; import { ServerView } from './views/ServerView';
import { RpcView } from './views/RpcView'; import { RpcView } from './views/RpcView';
import { RoomsView } from './views/RoomsView';
const HEADS: Record<string, [string, string]> = { const HEADS: Record<string, [string, string]> = {
now: ['Now Playing', 'What Echoion is streaming to the channel'], dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'],
queue: ['Queue', 'Reorder and manage upcoming tracks'], queue: ['Queue', 'Reorder and manage upcoming tracks'],
search: ['Search', 'Find tracks across YouTube and Yandex Music'], search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'], library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'], stats: ['History & Stats', 'Playback history and server insights'],
rooms: ['Listening Rooms', 'Independent music streams for different groups'],
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
server: ['Server & Admin', 'Manage subscribers and broadcast'], server: ['Server & Admin', 'Manage subscribers and broadcast'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'], rpc: ['RPC / API', 'Connect to Echoion programmatically'],
}; };
@@ -39,20 +34,12 @@ export function App() {
useEffect(() => { useEffect(() => {
boot(); boot();
initWatch({
getName: () =>
(appStore.get().identity &&
appStore.get().identity!.nickname) ||
null,
getToken: getStoredToken,
toast,
});
initRouter(); initRouter();
initShortcuts(); initShortcuts();
initMediaSession(); initMediaSession();
}, []); }, []);
const [title, sub] = HEADS[s.view] || HEADS.now; const [title, sub] = HEADS[s.view] || HEADS.dashboard;
return ( return (
<div id="app"> <div id="app">
@@ -84,7 +71,7 @@ export function App() {
<div className="header-right"> <div className="header-right">
<span className="pill"> <span className="pill">
<span className="dot dot-green" /> <span className="dot dot-green" />
{s.onlineCount}&nbsp;{t('listening')} {s.onlineCount}&nbsp;{t('online')}
</span> </span>
<button <button
className="icon-btn" className="icon-btn"
@@ -99,18 +86,11 @@ export function App() {
</div> </div>
</header> </header>
{s.view === 'now' && <NowView />} {s.view === 'dashboard' && <DashboardView />}
{s.view === 'queue' && <QueueView />} {s.view === 'queue' && <QueueView />}
{s.view === 'search' && <SearchView />} {s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />} {s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />} {s.view === 'stats' && <StatsView />}
{s.view === 'rooms' && <RoomsView />}
{/* The watch view stays mounted so the embedded player and
room connection survive view switches (the old UI only
toggled `hidden`). */}
<div hidden={s.view !== 'watch'}>
<WatchView />
</div>
{s.view === 'server' && <ServerView />} {s.view === 'server' && <ServerView />}
{s.view === 'rpc' && <RpcView />} {s.view === 'rpc' && <RpcView />}
-112
View File
@@ -1,112 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { useStore } from '../lib/store';
import { emojiStore, loadCustomEmojis } from '../lib/emoji';
import { safeCall, toast } from '../lib/app';
import { CloseIcon } from './icons';
import { t } from '../i18n';
// Admin custom-emoji manager (item 16): upload an image (≤64KB) under a
// shortcode name, list existing ones, and remove them. The image is sent as
// base64 to AddCustomEmoji and served back at /emoji/<name>.
export function EmojiManager() {
const { custom } = useStore(emojiStore);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
loadCustomEmojis();
}, []);
const upload = async () => {
const file = fileRef.current?.files?.[0];
const clean = name.trim().toLowerCase();
if (!/^[a-z0-9_]{1,32}$/.test(clean)) {
toast(t('Emoji name must be 1-32 chars of a-z, 0-9, _'));
return;
}
if (!file) {
toast(t('Choose an image file'));
return;
}
if (file.size > 64 * 1024) {
toast(t('Emoji image too large (max ~64KB)'));
return;
}
setBusy(true);
const dataBase64 = await new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const res = String(reader.result);
resolve(res.slice(res.indexOf(',') + 1)); // strip data: prefix
};
reader.readAsDataURL(file);
});
const res = await safeCall('AddCustomEmoji', {
name: clean,
mime: file.type,
dataBase64,
});
setBusy(false);
if (res) {
toast(t('Emoji added'));
setName('');
if (fileRef.current) fileRef.current.value = '';
loadCustomEmojis();
}
};
return (
<div className="card">
<div className="card-head">
<h2>
{t('Custom emojis')}{' '}
<span className="muted">
{custom.length ? `· ${custom.length}` : ''}
</span>
</h2>
</div>
<div className="emoji-manage-row">
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('shortcode (a-z0-9_)')}
maxLength={32}
/>
<input ref={fileRef} type="file" accept="image/*" />
<button
className="btn btn-accent"
disabled={busy}
onClick={upload}
>
{t('Add emoji')}
</button>
</div>
<div className="emoji-manage-grid">
{custom.map((c) => (
<div key={c.name} className="emoji-manage-item">
<img
className="emoji-img-lg"
src={`/emoji/${c.name}`}
alt={c.name}
/>
<span className="mono">:{c.name}:</span>
<button
className="icon-btn danger"
title={t('Remove')}
onClick={async () => {
await safeCall('RemoveCustomEmoji', {
name: c.name,
});
toast(t('Emoji removed'));
loadCustomEmojis();
}}
>
<CloseIcon />
</button>
</div>
))}
</div>
</div>
);
}
-113
View File
@@ -1,113 +0,0 @@
import { useEffect, useRef } from 'react';
import { useStore } from '../lib/store';
import {
EMOJI_CATEGORIES,
emojiStore,
rememberEmoji,
} from '../lib/emoji';
import { t } from '../i18n';
// A popover emoji picker: recently-used, curated Unicode categories, and the
// server's custom image emojis. `onPick` receives either a unicode char or a
// :shortcode: for a custom emoji.
export function EmojiPicker(props: {
onPick: (token: string) => void;
onClose: () => void;
}) {
const { custom, recent } = useStore(emojiStore);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
props.onClose();
}
};
// Defer so the opening click doesn't immediately close it.
const id = setTimeout(
() => document.addEventListener('mousedown', onDoc),
0
);
return () => {
clearTimeout(id);
document.removeEventListener('mousedown', onDoc);
};
}, [props]);
const pick = (token: string) => {
rememberEmoji(token);
props.onPick(token);
};
return (
<div className="emoji-picker" ref={ref}>
{recent.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Recent')}</div>
<div className="emoji-grid">
{recent.map((token, i) =>
token.startsWith(':') ? (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
<img
src={`/emoji/${token.slice(1, -1)}`}
alt={token}
className="emoji-img"
/>
</button>
) : (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
{token}
</button>
)
)}
</div>
</div>
)}
{custom.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Custom')}</div>
<div className="emoji-grid">
{custom.map((c) => (
<button
key={c.name}
className="emoji-btn"
title={`:${c.name}:`}
onClick={() => pick(`:${c.name}:`)}
>
<img
src={`/emoji/${c.name}`}
alt={c.name}
className="emoji-img"
/>
</button>
))}
</div>
</div>
)}
{EMOJI_CATEGORIES.map((cat) => (
<div key={cat.label} className="emoji-section">
<div className="emoji-section-label">{cat.label}</div>
<div className="emoji-grid">
{cat.emoji.map((e) => (
<button
key={e}
className="emoji-btn"
onClick={() => pick(e)}
>
{e}
</button>
))}
</div>
</div>
))}
</div>
);
}
+1 -1
View File
@@ -14,7 +14,7 @@ async function togglePlay() {
// Mini player mirrors the current track on views other than Now Playing. // Mini player mirrors the current track on views other than Now Playing.
export function MiniPlayer() { export function MiniPlayer() {
const s = useStore(appStore); const s = useStore(appStore);
if (s.view === 'now' || !s.current) return null; if (s.view === 'dashboard' || !s.current) return null;
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused); const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
const canForceSkip = !!( const canForceSkip = !!(
s.identity && s.identity &&
+5 -7
View File
@@ -11,11 +11,9 @@ import {
} from './icons'; } from './icons';
import { t } from '../i18n'; import { t } from '../i18n';
// The one custom player control bar, shared by Watch Together (room /ws // Dashboard playback controls. This component is presentational; authenticated
// protocol) and Now Playing (bot RPC). Purely presentational: the two sync // RPC callbacks are supplied by the dashboard while visitors receive a
// channels differ only in the callbacks the views pass in. Embedded players // disabled, read-only transport surface.
// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is
// the only playback UI.
export function PlayerControls(props: { export function PlayerControls(props: {
playing: boolean; playing: boolean;
positionMs: number; positionMs: number;
@@ -45,7 +43,7 @@ export function PlayerControls(props: {
: 0; : 0;
return ( return (
<div className="player-controls"> <div className="player-controls">
<div className="watch-controls"> <div className="player-control-row">
<button <button
className="ctrl ctrl-main" className="ctrl ctrl-main"
title={t('Play/Pause')} title={t('Play/Pause')}
@@ -102,7 +100,7 @@ export function PlayerControls(props: {
{props.extra} {props.extra}
</div> </div>
{(props.showLocal ?? true) && ( {(props.showLocal ?? true) && (
<div className="watch-controls watch-local"> <div className="player-control-row player-local-row">
<span className="muted">{t('Vol')}</span> <span className="muted">{t('Vol')}</span>
<Bar <Bar
slim slim
@@ -1,99 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import type { PlayerExtraControl } from '../lib/embedProtocols';
import { t } from '../i18n';
import { GearIcon } from './icons';
export function PlayerSettingsMenu(props: {
extras: PlayerExtraControl[];
rate: number;
rateOptions?: number[];
canControl: boolean;
onExtra: (id: string, value: string) => void;
onRate: (rate: number) => void;
}) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const local = props.extras.filter((control) => control.scope === 'local');
const room = props.extras.filter(
(control) => control.scope === 'synced' && control.id !== 'speed'
);
const hasRoom = room.length > 0 || !!props.rateOptions?.length;
useEffect(() => {
if (!open) return;
const close = (event: MouseEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', close);
return () => document.removeEventListener('mousedown', close);
}, [open]);
if (local.length === 0 && !hasRoom) return null;
const renderControl = (control: PlayerExtraControl) => (
<label className="player-setting" key={control.id}>
<span>{t(control.label)}</span>
<select
value={control.current ?? ''}
disabled={control.scope === 'synced' && !props.canControl}
title={
control.scope === 'synced' && !props.canControl
? t('Only the host can change this')
: undefined
}
onChange={(event) => props.onExtra(control.id, event.target.value)}
>
{control.current == null && <option value="">{t('Choose')}</option>}
{control.options.map((option) => (
<option key={option.value} value={option.value}>
{t(option.label)}
</option>
))}
</select>
</label>
);
return (
<div className="player-settings" ref={rootRef}>
<button
className="ctrl"
title={t('Settings')}
aria-expanded={open}
onClick={() => setOpen((value) => !value)}
>
<GearIcon />
</button>
{open && (
<div className="player-settings-popover">
{local.length > 0 && (
<section>
<div className="player-settings-heading">{t('Local')}</div>
{local.map(renderControl)}
</section>
)}
{hasRoom && (
<section>
<div className="player-settings-heading">{t('Room')}</div>
{props.rateOptions && (
<label className="player-setting">
<span>{t('Speed')}</span>
<select
value={String(props.rate)}
disabled={!props.canControl}
onChange={(event) =>
props.onRate(Number(event.target.value))
}
>
{props.rateOptions.map((rate) => (
<option key={rate} value={rate}>{rate}×</option>
))}
</select>
</label>
)}
{room.map(renderControl)}
</section>
)}
</div>
)}
</div>
);
}
+20 -6
View File
@@ -18,7 +18,6 @@ import {
HeartIcon, HeartIcon,
PlayIcon, PlayIcon,
QueueIcon, QueueIcon,
RoomsIcon,
SearchIcon, SearchIcon,
StatsIcon, StatsIcon,
WatchIcon, WatchIcon,
@@ -26,13 +25,11 @@ import {
import { t, useLanguage } from '../i18n'; import { t, useLanguage } from '../i18n';
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [ const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'now', icon: <PlayIcon />, label: 'Now Playing' }, { view: 'dashboard', icon: <PlayIcon />, label: 'Dashboard' },
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' }, { view: 'queue', icon: <QueueIcon />, label: 'Queue' },
{ view: 'search', icon: <SearchIcon />, label: 'Search' }, { view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' }, { view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' }, { view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'rooms', icon: <RoomsIcon />, label: 'Listening Rooms' },
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' }, { view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' }, { view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
]; ];
@@ -74,13 +71,14 @@ export function Sidebar() {
<button <button
key={item.view} key={item.view}
className={ className={
'nav-item' + (s.view === item.view ? ' active' : '') 'nav-item' +
(s.view === item.view ? ' active' : '')
} }
onClick={() => showView(item.view)} onClick={() => showView(item.view)}
> >
<span className="nav-ico">{item.icon}</span> <span className="nav-ico">{item.icon}</span>
{t(item.label)} {t(item.label)}
{item.view === 'now' && playing && ( {item.view === 'dashboard' && playing && (
<span className="live-dot" /> <span className="live-dot" />
)} )}
{item.view === 'queue' && s.queue.length > 0 && ( {item.view === 'queue' && s.queue.length > 0 && (
@@ -88,6 +86,22 @@ export function Sidebar() {
)} )}
</button> </button>
))} ))}
{s.watchUrl && (
<a
className="nav-item"
href={s.watchUrl}
target="_blank"
rel="noreferrer"
>
<span className="nav-ico">
<WatchIcon />
</span>
{t('Watch Together')}
<span className="nav-external" aria-hidden="true">
↗
</span>
</a>
)}
</nav> </nav>
<div className="sidebar-foot"> <div className="sidebar-foot">
+472
View File
@@ -0,0 +1,472 @@
import { useCallback, useEffect, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type { RpcMethodName } from '../lib/rpc';
import { confirmDialog, promptDialog } from '../lib/dialog';
import { EmptyRow } from './TrackRow';
import { t, tf } from '../i18n';
interface AdminClient {
id: number;
databaseId: number | null;
uid: string | null;
nickname: string;
channelId: number;
talking: boolean;
muted: boolean;
deafened: boolean;
away: boolean;
groups: number[];
}
interface AdminChannel {
id: number;
name: string;
parentId: number | null;
default: boolean;
password: boolean;
maxClients: number;
currentClients: number;
clients: AdminClient[];
channels: AdminChannel[];
}
interface DirectoryResponse {
server: {
name: string;
connected: boolean;
clientCount: number;
maxClients: number;
};
channels: AdminChannel[];
}
interface Ban {
id: number;
uid: string | null;
nickname: string | null;
reason: string;
createdAt: number;
durationSeconds: number;
}
interface ServerGroup {
id: number;
name: string;
default: boolean;
}
export function TeamSpeakAdmin() {
const [directory, setDirectory] = useState<DirectoryResponse | null>(null);
const [bans, setBans] = useState<Ban[]>([]);
const [groups, setGroups] = useState<ServerGroup[]>([]);
const [loading, setLoading] = useState(false);
const refresh = useCallback(async () => {
setLoading(true);
const [nextDirectory, nextBans, nextGroups] = await Promise.all([
safeCall<DirectoryResponse>('GetTeamSpeakDirectory'),
safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'),
safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'),
]);
if (nextDirectory) setDirectory(nextDirectory);
if (nextBans) setBans(nextBans.bans || []);
if (nextGroups) setGroups(nextGroups.groups || []);
setLoading(false);
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
const mutate = useCallback(
async (
method: RpcMethodName,
params: Record<string, unknown>,
message: string
) => {
const result = await safeCall(method, params);
if (!result) return false;
toast(message);
await refresh();
return true;
},
[refresh]
);
async function sendServerMessage() {
const message = await promptDialog({
title: t('Server message'),
message: t('Message sent to every connected TeamSpeak client:'),
confirmLabel: t('Send'),
});
if (message) {
await mutate(
'SendTeamSpeakServerMessage',
{ message },
t('Server message sent')
);
}
}
async function createChannel(parentId = 0) {
const name = await promptDialog({
title: t('Create channel'),
message: t('Channel name:'),
confirmLabel: t('Create'),
});
if (name) {
await mutate(
'CreateTeamSpeakChannel',
{ name, parentId, permanent: true },
t('Channel created')
);
}
}
function ClientRow({ client }: { client: AdminClient }) {
return (
<div className="ts-admin-client">
<div className="ts-admin-client-main">
<span
className={'ts-presence' + (client.talking ? ' talking' : '')}
/>
<strong>{client.nickname}</strong>
<span className="muted">#{client.id}</span>
{client.away && <span className="ts-tag">{t('away')}</span>}
{client.muted && <span className="ts-tag">{t('muted')}</span>}
{client.deafened && <span className="ts-tag">{t('deafened')}</span>}
</div>
<div className="ts-admin-private muted">
<span>UID: {client.uid || '—'}</span>
<span>DB: {client.databaseId || '—'}</span>
<span>{t('Groups')}: {client.groups.join(', ') || '—'}</span>
</div>
<div className="ts-admin-actions">
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', client.nickname),
message: t('Private message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakPrivateMessage',
{ clientId: client.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const channelId = await promptDialog({
title: tf('Move {0}', client.nickname),
message: t('Destination channel ID:'),
confirmLabel: t('Move'),
});
if (channelId && /^\d+$/.test(channelId))
await mutate(
'MoveTeamSpeakClient',
{ clientId: client.id, channelId: Number(channelId) },
t('Client moved')
);
}}
>
{t('Move')}
</button>
{client.databaseId && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Add server group'),
message: groups.length
? groups.map((g) => `${g.id}: ${g.name}`).join('\n')
: t('Server group ID:'),
confirmLabel: t('Add'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'AddTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group added')
);
}}
>
{t('Add group')}
</button>
)}
{client.databaseId && client.groups.length > 0 && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Remove server group'),
message: `${t('Current groups')}: ${client.groups.join(', ')}`,
confirmLabel: t('Remove'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'RemoveTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group removed')
);
}}
>
{t('Remove group')}
</button>
)}
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: tf('Kick {0}', client.nickname),
message: t('Kick this client from the server?'),
confirmLabel: t('Kick'),
danger: true,
})
)
await mutate(
'KickTeamSpeakClient',
{ clientId: client.id, fromServer: true },
t('Client kicked')
);
}}
>
{t('Kick')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
const duration = await promptDialog({
title: tf('Ban {0}', client.nickname),
message: t('Duration in seconds (0 = permanent):'),
confirmLabel: t('Continue'),
});
if (!duration || !/^\d+$/.test(duration)) return;
if (
await confirmDialog({
title: tf('Ban {0}', client.nickname),
message: t('Apply this ban now?'),
confirmLabel: t('Ban'),
danger: true,
})
)
await mutate(
'BanTeamSpeakClient',
{
clientId: client.id,
durationSeconds: Number(duration),
},
t('Client banned')
);
}}
>
{t('Ban')}
</button>
</div>
</div>
);
}
function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) {
return (
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
<div className="ts-admin-channel-head">
<strong>{channel.name}</strong>
<span className="muted">#{channel.id}</span>
<span className="ts-capacity">
{channel.currentClients}/{channel.maxClients || '∞'}
</span>
<button className="btn btn-ghost" onClick={() => createChannel(channel.id)}>
{t('Add child')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const name = await promptDialog({
title: t('Rename channel'),
message: channel.name,
confirmLabel: t('Save'),
});
if (name)
await mutate(
'EditTeamSpeakChannel',
{ channelId: channel.id, name },
t('Channel updated')
);
}}
>
{t('Edit')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', channel.name),
message: t('Channel message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakChannelMessage',
{ channelId: channel.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const parentId = await promptDialog({
title: t('Reorder channel'),
message: t('Parent channel ID (0 = root):'),
confirmLabel: t('Continue'),
});
if (parentId === null || !/^\d+$/.test(parentId)) return;
const orderAfterId = await promptDialog({
title: t('Reorder channel'),
message: t('Previous sibling channel ID (0 = first):'),
confirmLabel: t('Move'),
});
if (orderAfterId === null || !/^\d+$/.test(orderAfterId)) return;
await mutate(
'ReorderTeamSpeakChannel',
{
channelId: channel.id,
parentId: Number(parentId),
orderAfterId: Number(orderAfterId),
},
t('Channel reordered')
);
}}
>
{t('Reorder')}
</button>
{!channel.default && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Delete channel'),
message: tf('Delete {0} and its contents?', channel.name),
confirmLabel: t('Delete'),
danger: true,
})
)
await mutate(
'DeleteTeamSpeakChannel',
{ channelId: channel.id, force: true },
t('Channel deleted')
);
}}
>
{t('Delete')}
</button>
)}
</div>
{channel.clients.map((client) => (
<ClientRow key={client.id} client={client} />
))}
{channel.channels.map((child) => (
<Channel key={child.id} channel={child} depth={depth + 1} />
))}
</div>
);
}
return (
<div className="admin-stack">
<div className="card">
<div className="card-head">
<div>
<h2>{directory?.server.name || t('TeamSpeak')}</h2>
<div className="muted">
{directory?.server.connected ? t('Connected') : t('Disconnected')}
{' · '}
{directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'}
</div>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={sendServerMessage}>
{t('Server message')}
</button>
<button className="btn btn-ghost" onClick={() => createChannel()}>
{t('Create channel')}
</button>
<button className="btn btn-ghost" disabled={loading} onClick={refresh}>
{loading ? t('Loading…') : t('Refresh')}
</button>
</div>
</div>
<div className="ts-admin-tree">
{directory?.channels.length ? (
directory.channels.map((channel) => (
<Channel key={channel.id} channel={channel} />
))
) : (
<EmptyRow text={t('No TeamSpeak topology available')} />
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h2>{t('Bans')}</h2>
<span className="muted">{bans.length}</span>
</div>
<div className="tracklist">
{bans.length ? (
bans.map((ban) => (
<div className="ts-ban-row" key={ban.id}>
<div>
<strong>{ban.nickname || ban.uid || `#${ban.id}`}</strong>
<div className="muted">{ban.reason || t('No reason')}</div>
</div>
<span className="muted">
{ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')}
</span>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Remove ban'),
message: t('Remove this TeamSpeak ban?'),
confirmLabel: t('Unban'),
danger: true,
})
)
await mutate(
'UnbanTeamSpeakClient',
{ banId: ban.id },
t('Ban removed')
);
}}
>
{t('Unban')}
</button>
</div>
))
) : (
<EmptyRow text={t('No bans')} />
)}
</div>
</div>
</div>
);
}
-145
View File
@@ -1,145 +0,0 @@
import { useState } from 'react';
import { rpc } from '../lib/rpc';
import { send, watchStore } from '../lib/watch';
import { toast } from '../lib/app';
import { useStore } from '../lib/store';
import { thumbFor } from '../lib/format';
import type { Track } from '../lib/types';
import { t, tf } from '../i18n';
// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a
// full twitch.tv URL, and reduce it to the channel login the embed player
// expects. Numeric ids pass through (best effort — resolving them to a login
// would need the Helix API, which isn't wired up).
function normalizeTwitchChannel(input: string): string {
let s = input.trim();
const m = s.match(/twitch\.tv\/([^/?#]+)/i);
if (m) s = m[1];
s = s.replace(/^@/, '');
return s.toLowerCase().replace(/[^a-z0-9_]/g, '');
}
// Add tracks to a watch room from inside it. YouTube uses the unauthenticated
// SearchTracks RPC (results added by title + thumbnail); Twitch has no search
// backend, so it offers an add-by-channel-name/id field instead.
export function WatchSearch({ disabled }: { disabled: boolean }) {
const w = useStore(watchStore);
const [query, setQuery] = useState('');
const [channel, setChannel] = useState('');
const [results, setResults] = useState<Track[]>([]);
const [open, setOpen] = useState(false);
if (w.sourceChoice === 'twitch') {
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={(e) => {
e.preventDefault();
const ch = normalizeTwitchChannel(channel);
if (!ch) return;
send({
type: 'watch.queue.add',
source: 'twitch',
url: ch,
title: ch,
});
toast(tf('Added “{0}” to queue', ch));
setChannel('');
}}
>
<input
value={channel}
onChange={(e) => setChannel(e.target.value)}
placeholder={t(
'Twitch channel name or id to queue…'
)}
autoComplete="off"
disabled={disabled}
/>
<button
className="btn btn-accent"
type="submit"
disabled={disabled}
>
{t('Add channel')}
</button>
</form>
</div>
);
}
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={async (e) => {
e.preventDefault();
const q = query.trim();
if (!q) return;
try {
const res = await rpc.call<{ tracks?: Track[] }>(
'SearchTracks',
{ query: q }
);
setResults((res && res.tracks) || []);
setOpen(true);
} catch (err) {
toast((err as { message?: string }).message || 'error');
}
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('Search YouTube to queue…')}
autoComplete="off"
disabled={disabled}
/>
<button className="btn btn-accent" type="submit" disabled={disabled}>
{t('Search')}
</button>
</form>
{open && results.length > 0 && (
<div className="watch-search-results">
{results.slice(0, 8).map((tr, i) => (
<button
key={tr.url || tr.id || i}
className="watch-search-item"
onClick={() => {
send({
type: 'watch.queue.add',
source: 'youtube',
url: tr.url || tr.id,
title: tr.title || '',
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
setOpen(false);
setQuery('');
}}
>
<div
className="track-cover"
style={
thumbFor(tr)
? {
background: `url("${thumbFor(tr)}") center/cover`,
}
: undefined
}
/>
<span className="watch-search-title">
{tr.title}
</span>
</button>
))}
</div>
)}
</div>
);
}
+101 -135
View File
@@ -4,15 +4,12 @@
export const ru: Record<string, string> = { export const ru: Record<string, string> = {
// Sidebar / navigation // Sidebar / navigation
'Now Playing': 'Сейчас играет', 'Dashboard': 'Панель',
'Queue': 'Очередь', 'Queue': 'Очередь',
'Search': 'Поиск', 'Search': 'Поиск',
'Library': 'Библиотека', 'Library': 'Библиотека',
'History & Stats': 'История и статистика', 'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр', 'Watch Together': 'Совместный просмотр',
'Listening Rooms': 'Комнаты прослушивания',
'Independent music streams for different groups':
'Независимые музыкальные потоки для разных групп',
'Server & Admin': 'Сервер и админ', 'Server & Admin': 'Сервер и админ',
'RPC / API': 'RPC / API', 'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3', 'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
@@ -26,15 +23,14 @@ export const ru: Record<string, string> = {
'connected': 'подключено', 'connected': 'подключено',
'disconnected': 'отключено', 'disconnected': 'отключено',
'error': 'ошибка', 'error': 'ошибка',
'listening': 'слушают',
// View headers // View headers
'What Echoion is streaming to the channel': 'Что Echoion стримит в канал', 'Live playback and TeamSpeak server activity':
'Текущее воспроизведение и активность сервера TeamSpeak',
'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков', 'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков',
'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке', 'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке',
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты', 'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
'Playback history and server insights': 'История воспроизведения и статистика сервера', 'Playback history and server insights': 'История воспроизведения и статистика сервера',
'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу',
'Manage subscribers and broadcast': 'Управление подписчиками и объявления', 'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
'Connect to Echoion programmatically': 'Подключение к Echoion из кода', 'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
@@ -125,75 +121,31 @@ export const ru: Record<string, string> = {
'{0}% skip rate': '{0}% пропусков', '{0}% skip rate': '{0}% пропусков',
'{0} requests': '{0} запросов', '{0} requests': '{0} запросов',
// Watch together // Shared playback and action labels
'Nothing loaded — paste a URL above': 'Ничего не загружено — вставьте ссылку выше',
'Twitch embeds require HTTPS — open the site via its https:// domain':
'Встраивание Twitch требует HTTPS — откройте сайт по его https:// адресу',
'YouTube URL to watch together': 'Ссылка YouTube для совместного просмотра',
'Twitch channel or URL to watch together': 'Канал или ссылка Twitch для совместного просмотра',
'Video URL': 'Видео по ссылке',
'Embed': 'Встраивание',
'Direct video or .m3u8 URL to watch together':
'Прямая ссылка на видео или .m3u8 для совместного просмотра',
'Embed URL (Kodik, etc.) to watch together':
'Ссылка для встраивания (Kodik и др.) для совместного просмотра',
'Load': 'Загрузить', 'Load': 'Загрузить',
'+ Queue': '+ В очередь',
'Add to the watch queue': 'Добавить в очередь просмотра',
'Guest — sign in to control': 'Гость — войдите, чтобы управлять',
'You are hosting': 'Вы ведущий',
'Viewer': 'Зритель',
'Synced': 'Синхронно',
'Resync': 'Синхронизировать',
'Resynced to room': 'Синхронизировано с комнатой',
'Live stream — cannot seek': 'Прямой эфир — перемотка недоступна',
'LIVE': 'ЭФИР',
'In the room': 'В комнате',
'Room chat': 'Чат комнаты',
'Say something…': 'Скажите что-нибудь…',
'Send': 'Отправить',
'Host': 'Ведущий',
'Host only': 'Только ведущий',
'Play next': 'Следующее', 'Play next': 'Следующее',
'(you)': '(вы)', 'LIVE': 'ЭФИР',
'Buffering…': 'Буферизация…', 'Send': 'Отправить',
'In sync': 'Синхронно',
'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»',
'Remove from queue': 'Убрать из очереди',
'added by {0}': 'добавил {0}',
'Fullscreen': 'Во весь экран', 'Fullscreen': 'Во весь экран',
'Fullscreen unavailable': 'Полноэкранный режим недоступен',
'Playback quality (best effort — YouTube may keep auto)':
'Качество (по возможности — YouTube может оставить авто)',
'Auto': 'Авто',
'Not allowed': 'Недостаточно прав',
// Watch Together protocol extensions (items 3, 4, 5)
'New room name…': 'Название новой комнаты…',
'Create / join': 'Создать / войти',
'Make host': 'Назначить ведущим',
'That viewer is no longer here': 'Этого зрителя уже нет',
'Only signed-in viewers can host': 'Вести может только вошедший зритель',
// Watch player & UX (items 7, 8, 16, 20)
'Playback speed': 'Скорость воспроизведения',
'Search YouTube to queue…': 'Найти на YouTube для очереди…',
'Recent': 'Недавние',
'Custom': 'Свои',
'Custom emojis': 'Свои эмодзи',
'Add emoji': 'Добавить эмодзи',
'Emoji added': 'Эмодзи добавлено',
'Emoji removed': 'Эмодзи удалено',
'shortcode (a-z0-9_)': 'код (a-z0-9_)',
'Choose an image file': 'Выберите файл изображения',
'Emoji name must be 1-32 chars of a-z, 0-9, _': 'Имя: 1–32 символа a-z, 0-9, _',
'Emoji image too large (max ~64KB)': 'Изображение слишком большое (макс ~64КБ)',
// Server & admin // Server & admin
'Administration': 'Администрирование',
'Administrator authentication required': 'Требуется вход администратора',
'Sign in with an account in a configured TeamSpeak admin group.':
'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.',
'TeamSpeak': 'TeamSpeak',
'Echoion service': 'Служба Echoion',
'Bot messaging and runtime operations':
'Сообщения бота и управление службой',
'Subscribers': 'Подписчики', 'Subscribers': 'Подписчики',
'Emojis': 'Эмодзи',
'Audit history': 'Журнал действий',
'Room emojis moved to VoidWatch and are managed from its administration page.':
'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.',
'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗',
'Announce…': 'Объявление…', 'Announce…': 'Объявление…',
'Reload config': 'Перезагрузить конфиг', 'Reload config': 'Перезагрузить конфиг',
'Restart web UI': 'Перезапустить веб-интерфейс', 'Restart web UI': 'Перезапустить веб-интерфейс',
'Stop and start the web server without touching the bot':
'Остановить и запустить веб-сервер, не трогая бота',
'Unsub all': 'Отписать всех', 'Unsub all': 'Отписать всех',
'No subscribers': 'Нет подписчиков', 'No subscribers': 'Нет подписчиков',
'Nobody online right now': 'Сейчас никого нет в сети', 'Nobody online right now': 'Сейчас никого нет в сети',
@@ -201,7 +153,6 @@ export const ru: Record<string, string> = {
'Offline': 'Не в сети', 'Offline': 'Не в сети',
'Unsub': 'Отписать', 'Unsub': 'Отписать',
'Unsubscribe {0}?': 'Отписать {0}?', 'Unsubscribe {0}?': 'Отписать {0}?',
'Unsubscribed {0}': '{0} отписан',
'Announcement to all subscribers:': 'Объявление всем подписчикам:', 'Announcement to all subscribers:': 'Объявление всем подписчикам:',
'Announcement sent': 'Объявление отправлено', 'Announcement sent': 'Объявление отправлено',
'Configuration reloaded': 'Конфигурация перезагружена', 'Configuration reloaded': 'Конфигурация перезагружена',
@@ -213,11 +164,92 @@ export const ru: Record<string, string> = {
'Удалить ВСЕ подписки? Это нельзя отменить.', 'Удалить ВСЕ подписки? Это нельзя отменить.',
'All subscriptions removed': 'Все подписки удалены', 'All subscriptions removed': 'Все подписки удалены',
'Listening': 'Слушает', 'Listening': 'Слушает',
'Audit log': 'Журнал аудита',
'Refresh': 'Обновить', 'Refresh': 'Обновить',
'No audit entries yet': 'Записей аудита пока нет', 'No audit entries yet': 'Записей аудита пока нет',
'client #{0}': 'клиент №{0}', 'client #{0}': 'клиент №{0}',
// Public TeamSpeak directory
'TeamSpeak server': 'Сервер TeamSpeak',
'Complete channel directory': 'Полное дерево каналов',
'Connected': 'Подключено',
'Disconnected': 'Отключено',
'No channels available': 'Нет доступных каналов',
'Password protected': 'Защищён паролем',
'Talking': 'Говорит',
'Away': 'Отошёл',
'Muted': 'Микрофон выключен',
'Deafened': 'Звук выключен',
'clients': 'клиентов',
'channels': 'каналов',
'capacity': 'вместимость',
'online': 'в сети',
'default': 'по умолчанию',
'locked': 'закрыт',
'away': 'отошёл',
'muted': 'микрофон выкл.',
'deafened': 'звук выкл.',
// TeamSpeak administration
'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно',
'Message': 'Сообщение',
'Message {0}': 'Сообщение для {0}',
'Private message:': 'Личное сообщение:',
'Channel message:': 'Сообщение в канал:',
'Message sent': 'Сообщение отправлено',
'Server message': 'Сообщение серверу',
'Message sent to every connected TeamSpeak client:':
'Сообщение всем подключённым клиентам TeamSpeak:',
'Server message sent': 'Сообщение серверу отправлено',
'Move': 'Переместить',
'Move {0}': 'Переместить {0}',
'Destination channel ID:': 'ID целевого канала:',
'Client moved': 'Клиент перемещён',
'Kick': 'Выгнать',
'Kick {0}': 'Выгнать {0}',
'Kick this client from the server?': 'Выгнать этого клиента с сервера?',
'Client kicked': 'Клиент выгнан',
'Ban': 'Заблокировать',
'Ban {0}': 'Заблокировать {0}',
'Duration in seconds (0 = permanent):':
'Срок в секундах (0 = бессрочно):',
'Apply this ban now?': 'Заблокировать этого клиента сейчас?',
'Client banned': 'Клиент заблокирован',
'Bans': 'Блокировки',
'No bans': 'Блокировок нет',
'No reason': 'Без причины',
'Permanent': 'Бессрочно',
'Remove ban': 'Снять блокировку',
'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?',
'Unban': 'Разблокировать',
'Ban removed': 'Блокировка снята',
'Groups': 'Группы',
'Current groups': 'Текущие группы',
'Server group ID:': 'ID серверной группы:',
'Add server group': 'Добавление в серверную группу',
'Add group': 'Добавить в группу',
'Group added': 'Клиент добавлен в группу',
'Remove server group': 'Удаление из серверной группы',
'Remove group': 'Удалить из группы',
'Group removed': 'Клиент удалён из группы',
'Create channel': 'Создать канал',
'Channel name:': 'Название канала:',
'Create': 'Создать',
'Channel created': 'Канал создан',
'Add child': 'Добавить подканал',
'Rename channel': 'Переименовать канал',
'Edit': 'Изменить',
'Channel updated': 'Канал обновлён',
'Reorder': 'Переместить',
'Reorder channel': 'Переместить канал',
'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):',
'Previous sibling channel ID (0 = first):':
'ID предыдущего канала на этом уровне (0 = первый):',
'Channel reordered': 'Канал перемещён',
'Delete channel': 'Удалить канал',
'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?',
'Channel deleted': 'Канал удалён',
'Continue': 'Продолжить',
// RPC view // RPC view
'Connect programmatically': 'Программное подключение', 'Connect programmatically': 'Программное подключение',
'Copy snippet': 'Скопировать пример', 'Copy snippet': 'Скопировать пример',
@@ -262,22 +294,7 @@ export const ru: Record<string, string> = {
'Menu': 'Меню', 'Menu': 'Меню',
'Back 10 seconds': 'Назад на 10 секунд', 'Back 10 seconds': 'Назад на 10 секунд',
'Forward 10 seconds': 'Вперёд на 10 секунд', 'Forward 10 seconds': 'Вперёд на 10 секунд',
'Leave room': 'Покинуть комнату',
'Leave this room': 'Покинуть эту комнату',
'Room': 'Комната',
'Watch together': 'Смотреть вместе',
'Refresh rooms': 'Обновить список комнат',
'Join a room to watch in sync, or create your own.':
'Войдите в комнату для синхронного просмотра или создайте свою.',
'No active rooms yet — create one below.':
'Активных комнат пока нет — создайте свою ниже.',
'{0} watching': '{0} смотрят',
'Tap to unmute': 'Нажмите, чтобы включить звук',
'Add channel': 'Добавить канал',
'Twitch channel name or id to queue…': 'Имя или ID Twitch-канала для очереди…',
'Clear queue': 'Очистить очередь', 'Clear queue': 'Очистить очередь',
'Watch queue is full': 'Очередь просмотра заполнена',
'Watch queue is empty': 'Очередь просмотра пуста',
'Confirm': 'Подтвердить', 'Confirm': 'Подтвердить',
'OK': 'ОК', 'OK': 'ОК',
'Save': 'Сохранить', 'Save': 'Сохранить',
@@ -289,56 +306,5 @@ export const ru: Record<string, string> = {
'Playlist name': 'Название плейлиста', 'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист', 'Save playlist': 'Сохранить плейлист',
// Independent TeamSpeak listening rooms
'MULTI-STREAM': 'МУЛЬТИПОТОК',
'NOW TUNED': 'СЕЙЧАС В КОМНАТЕ',
'Your channel, split into listening spaces':
'Разделите канал на пространства для прослушивания',
'Each room has its own queue and bot stream. Join one to hear and control it.':
'У каждой комнаты своя очередь и поток бота. Войдите, чтобы слушать и управлять.',
'Room name': 'Название комнаты',
'Create room': 'Создать комнату',
'Created room “{0}”': 'Комната «{0}» создана',
'Live rooms': 'Активные комнаты',
'No listening rooms yet': 'Комнат прослушивания пока нет',
'{0} listeners · {1} queued': '{0} слушателей · {1} в очереди',
'JOINED': 'ВЫ В КОМНАТЕ',
'PAUSED': 'ПАУЗА',
'IDLE': 'ТИШИНА',
'Choose a room': 'Выберите комнату',
'Your TeamSpeak audio follows the room you join.':
'Звук TeamSpeak переключается на комнату, в которую вы вошли.',
'Leave': 'Выйти',
'Delete room': 'Удалить комнату',
'Delete “{0}” for everyone?': 'Удалить «{0}» для всех?',
'Stop': 'Остановить',
'Skip': 'Пропустить',
'Move up': 'Переместить выше',
'Move down': 'Переместить ниже',
'Pause': 'Пауза',
'Resume': 'Продолжить',
'Paused': 'На паузе',
'Streaming now': 'Сейчас транслируется',
'Ready': 'Готово',
'{0} people are tuned in': 'Подключено: {0}',
'Paste a URL or search for a track…':
'Вставьте ссылку или найдите трек…',
'Add': 'Добавить', 'Add': 'Добавить',
'Added to room queue': 'Добавлено в очередь комнаты',
'Room queue': 'Очередь комнаты',
'This room queue is empty': 'Очередь этой комнаты пуста',
// Controllable embeds (Kodik / Playerjs)
'Embed synced': 'Встраиваемый плеер синхронизирован',
'Embed is view-only': 'Встраиваемый плеер — только просмотр',
'Settings': 'Настройки',
'Local': 'Локально',
'Quality': 'Качество',
'Speed': 'Скорость',
'Voiceover': 'Озвучка',
'Episode': 'Серия',
'Subtitles': 'Субтитры',
'Off': 'Выкл.',
'Choose': 'Выбрать',
'Only the host can change this': 'Изменять может только ведущий',
}; };
+155 -15
View File
@@ -5,10 +5,9 @@
import { rpc, type RpcMethodName } from './rpc'; import { rpc, type RpcMethodName } from './rpc';
import { Store } from './store'; import { Store } from './store';
import { t, tf, setLanguage, getLanguage } from '../i18n'; import { t, tf, setLanguage, getLanguage } from '../i18n';
import { setWatchName } from './watch';
import { loadCustomEmojis } from './emoji';
import type { import type {
Identity, Identity,
PublicDashboard,
QueueEntry, QueueEntry,
ServerInfo, ServerInfo,
Status, Status,
@@ -17,13 +16,11 @@ import type {
} from './types'; } from './types';
export type ViewName = export type ViewName =
| 'now' | 'dashboard'
| 'queue' | 'queue'
| 'search' | 'search'
| 'library' | 'library'
| 'stats' | 'stats'
| 'rooms'
| 'watch'
| 'server' | 'server'
| 'rpc'; | 'rpc';
@@ -42,6 +39,8 @@ export interface AppState {
durationMs: number; durationMs: number;
onlineCount: number; onlineCount: number;
listeners: Subscriber[]; listeners: Subscriber[];
publicDashboard: PublicDashboard | null;
watchUrl: string;
toast: string | null; toast: string | null;
// Server-wide switch for the Now Playing video preview (item 11), from // Server-wide switch for the Now Playing video preview (item 11), from
// /config.json; users can still disable it locally. // /config.json; users can still disable it locally.
@@ -51,10 +50,14 @@ export interface AppState {
// Sidebar drawer on small screens (hamburger in the header); ignored by // Sidebar drawer on small screens (hamburger in the header); ignored by
// CSS on desktop widths where the sidebar is always visible. // CSS on desktop widths where the sidebar is always visible.
sidebarOpen: boolean; sidebarOpen: boolean;
capabilities: {
plugins: boolean;
webExtensions: boolean;
};
} }
export const appStore = new Store<AppState>({ export const appStore = new Store<AppState>({
view: 'now', view: 'dashboard',
connection: 'disconnected', connection: 'disconnected',
identity: null, identity: null,
status: null, status: null,
@@ -68,10 +71,16 @@ export const appStore = new Store<AppState>({
durationMs: 0, durationMs: 0,
onlineCount: 0, onlineCount: 0,
listeners: [], listeners: [],
publicDashboard: null,
watchUrl: '',
toast: null, toast: null,
nowPlayingVideoAllowed: true, nowPlayingVideoAllowed: true,
shortcutsOpen: false, shortcutsOpen: false,
sidebarOpen: false, sidebarOpen: false,
capabilities: {
plugins: false,
webExtensions: false,
},
}); });
// ── toast ──────────────────────────────────────────────────────────────────── // ── toast ────────────────────────────────────────────────────────────────────
@@ -124,9 +133,7 @@ export async function changeLanguage(language: 'en' | 'ru') {
export function applyIdentity(auth: Identity | null) { export function applyIdentity(auth: Identity | null) {
appStore.set({ identity: auth }); appStore.set({ identity: auth });
if (auth) { if (auth) {
setWatchName(auth.nickname || null);
void loadUserPrefs(); void loadUserPrefs();
void loadCustomEmojis();
} }
} }
@@ -176,6 +183,7 @@ export async function connectWithToken(tokenInput: string) {
const auth = (await rpc.authenticate(token)) as Identity; const auth = (await rpc.authenticate(token)) as Identity;
localStorage.setItem('echoion.token', token); localStorage.setItem('echoion.token', token);
applyIdentity(auth); applyIdentity(auth);
await loadCapabilities();
toast(tf('Welcome, {0}!', auth.nickname || t('friend'))); toast(tf('Welcome, {0}!', auth.nickname || t('friend')));
} }
refreshAll(); refreshAll();
@@ -210,9 +218,6 @@ export function showView(view: ViewName) {
// Navigation closes the mobile drawer. // Navigation closes the mobile drawer.
appStore.set({ view, sidebarOpen: false }); appStore.set({ view, sidebarOpen: false });
// Reflect the selection in the URL for back/forward + shareable links. // 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}`; const target = `#${view}`;
if (location.hash !== target) location.hash = target; if (location.hash !== target) location.hash = target;
} }
@@ -275,6 +280,47 @@ export async function loadFavorites() {
// ── boot ───────────────────────────────────────────────────────────────────── // ── boot ─────────────────────────────────────────────────────────────────────
let booted = false; let booted = false;
let dashboardEtag = '';
export async function refreshPublicDashboard() {
try {
const response = await fetch('/api/public/dashboard', {
headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {},
cache: 'no-cache',
});
if (response.status === 304) return;
if (!response.ok) return;
const dashboard = (await response.json()) as PublicDashboard;
dashboardEtag = response.headers.get('ETag') || '';
const state = appStore.get();
const publicTrack = dashboard.playback.track;
const sameTrack =
publicTrack && state.current && publicTrack.id === state.current.id;
const current = publicTrack
? {
...(sameTrack ? state.current! : {}),
...publicTrack,
duration:
publicTrack.durationMs ?? publicTrack.duration ?? 0,
}
: null;
appStore.set({
publicDashboard: dashboard,
current,
status: {
...(state.status || {}),
isPlaying: dashboard.playback.isPlaying,
isPaused: dashboard.playback.isPaused,
volume: dashboard.playback.volume,
},
positionMs: dashboard.playback.positionMs,
durationMs: current?.duration || 0,
onlineCount: dashboard.server.clientCount,
});
} catch {
/* The RPC login remains usable if the public snapshot is unavailable. */
}
}
export function boot() { export function boot() {
if (booted) return; if (booted) return;
@@ -283,24 +329,29 @@ export function boot() {
// Apply the persisted language before anything renders text. // Apply the persisted language before anything renders text.
setLanguage(getLanguage(), false); setLanguage(getLanguage(), false);
// Server config: the Now Playing video preview can be disabled globally. // Server config: the video preview policy and external VoidWatch link.
fetch('/config.json') fetch('/config.json')
.then((r) => r.json()) .then((r) => r.json())
.then((cfg) => { .then((cfg) => {
if (cfg && cfg.nowPlayingVideo === false) { appStore.set({
appStore.set({ nowPlayingVideoAllowed: false }); nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false,
} watchUrl:
typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '',
});
}) })
.catch(() => { .catch(() => {
/* keep the default (allowed) */ /* keep the default (allowed) */
}); });
rpc.onState = (s) => appStore.set({ connection: s }); rpc.onState = (s) => appStore.set({ connection: s });
void refreshPublicDashboard();
setInterval(() => void refreshPublicDashboard(), 5000);
// After an automatic reconnect, restore the authenticated session from // After an automatic reconnect, restore the authenticated session from
// the stored token (or autologin) and pull fresh state. // the stored token (or autologin) and pull fresh state.
rpc.onReconnected = async () => { rpc.onReconnected = async () => {
await restoreSession(); await restoreSession();
await loadCapabilities();
refreshAll(); refreshAll();
toast(t('Reconnected')); toast(t('Reconnected'));
}; };
@@ -335,6 +386,9 @@ export function boot() {
}); });
} }
}); });
rpc.on('plugins.updated', () => {
if (appStore.get().capabilities.webExtensions) void loadWebExtensions();
});
// Local 1s ticker keeps the progress bar moving between server updates. // Local 1s ticker keeps the progress bar moving between server updates.
setInterval(() => { setInterval(() => {
@@ -361,6 +415,92 @@ export function boot() {
// Session restore is independent of the connection: even if auth fails // Session restore is independent of the connection: even if auth fails
// we still refresh so guests see live state instead of a blank app. // we still refresh so guests see live state instead of a blank app.
await restoreSession(); await restoreSession();
await loadCapabilities();
refreshAll(); refreshAll();
})(); })();
} }
async function loadCapabilities() {
const capabilities = await safeCall<AppState['capabilities']>(
'GetCapabilities'
);
if (capabilities) {
appStore.set({ capabilities });
if (capabilities.webExtensions) await loadWebExtensions();
}
}
interface PluginWebAsset {
id: string;
javascript: string;
css: string;
}
interface LoadedWebExtension {
signature: string;
cleanup?: () => void;
}
const loadedWebExtensions = new Map<string, LoadedWebExtension>();
function unloadWebExtension(id: string) {
const loaded = loadedWebExtensions.get(id);
if (!loaded) return;
try {
loaded.cleanup?.();
} catch (error) {
console.error(`Echoion plugin web asset ${id} cleanup failed`, error);
}
document
.querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`)
.forEach((style) => style.remove());
loadedWebExtensions.delete(id);
}
async function loadWebExtensions() {
const response = await safeCall<{ assets?: PluginWebAsset[] }>(
'GetPluginExtensions'
);
if (!response) return;
const assets = response.assets || [];
const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean));
for (const id of loadedWebExtensions.keys()) {
if (!currentIds.has(id)) unloadWebExtension(id);
}
for (const asset of assets) {
if (!asset.id) continue;
const signature = `${asset.javascript}\0${asset.css}`;
if (loadedWebExtensions.get(asset.id)?.signature === signature) continue;
unloadWebExtension(asset.id);
let style: HTMLStyleElement | undefined;
if (asset.css) {
style = document.createElement('style');
style.dataset.echoionPlugin = asset.id;
style.textContent = asset.css;
document.head.appendChild(style);
}
try {
const host = {
call: async (plugin: string, method: string, params: unknown = {}) =>
rpc.call('PluginCall', {
plugin,
method,
params: JSON.stringify(params),
}),
store: appStore,
toast,
};
const cleanup = new Function(
'Echoion',
`'use strict';\n${asset.javascript}`
)(host);
loadedWebExtensions.set(asset.id, {
signature,
cleanup: typeof cleanup === 'function' ? cleanup : undefined,
});
} catch (error) {
style?.remove();
console.error(`Echoion plugin web asset ${asset.id} failed`, error);
}
}
}
+7 -5
View File
@@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest';
import { auditMethodName } from './auditMethods'; import { auditMethodName } from './auditMethods';
describe('audit RPC method mapping', () => { describe('audit RPC method mapping', () => {
it('keeps listening-room methods append-only and aligned with RpcTypes.hpp', () => { it('keeps removed room audit slots and newer methods aligned', () => {
expect(auditMethodName(53)).toBe('ListListeningRooms'); expect(auditMethodName(53)).toBe('Reserved53');
expect(auditMethodName(62)).toBe('GetListeningRoomQueue'); expect(auditMethodName(66)).toBe('Reserved66');
expect(auditMethodName(63)).toBe('SkipListeningRoom'); expect(auditMethodName(67)).toBe('GetCapabilities');
expect(auditMethodName(66)).toBe('ClearListeningRoomQueue'); expect(auditMethodName(72)).toBe('Reserved72');
expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory');
expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage');
}); });
}); });
+39 -17
View File
@@ -54,24 +54,46 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
'ToggleAutoplay', 'ToggleAutoplay',
'GetUserPrefs', 'GetUserPrefs',
'SetUserPrefs', 'SetUserPrefs',
'GetCustomEmojis', 'Reserved49',
'AddCustomEmoji', // 50 'Reserved50',
'RemoveCustomEmoji', 'Reserved51',
'GetLyrics', 'GetLyrics',
'ListListeningRooms', 'Reserved53',
'CreateListeningRoom', 'Reserved54',
'DeleteListeningRoom', 'Reserved55',
'JoinListeningRoom', 'Reserved56',
'LeaveListeningRoom', 'Reserved57',
'PlayInListeningRoom', 'Reserved58',
'PauseListeningRoom', 'Reserved59',
'ResumeListeningRoom', 'Reserved60',
'StopListeningRoom', 'Reserved61',
'GetListeningRoomQueue', 'Reserved62',
'SkipListeningRoom', 'Reserved63',
'RemoveFromListeningRoomQueue', 'Reserved64',
'MoveInListeningRoomQueue', 'Reserved65',
'ClearListeningRoomQueue', 'Reserved66',
'GetCapabilities',
'GetPluginExtensions',
'PluginCall',
'Reserved70',
'Reserved71',
'Reserved72',
'GetTeamSpeakDirectory',
'MoveTeamSpeakClient',
'KickTeamSpeakClient',
'BanTeamSpeakClient',
'GetTeamSpeakBans',
'UnbanTeamSpeakClient',
'CreateTeamSpeakChannel',
'EditTeamSpeakChannel',
'ReorderTeamSpeakChannel',
'DeleteTeamSpeakChannel',
'GetTeamSpeakServerGroups',
'AddTeamSpeakServerGroupMember',
'RemoveTeamSpeakServerGroupMember',
'SendTeamSpeakPrivateMessage',
'SendTeamSpeakChannelMessage',
'SendTeamSpeakServerMessage',
]; ];
export function auditMethodName(method: number): string { export function auditMethodName(method: number): string {
-254
View File
@@ -1,254 +0,0 @@
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'
);
});
});
-972
View File
@@ -1,972 +0,0 @@
// 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);
});
}
-96
View File
@@ -1,96 +0,0 @@
// 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;
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { viewFromHash } from './router';
describe('dashboard routing', () => {
it('uses dashboard as the default and redirects the retired now view', () => {
expect(viewFromHash('')).toBe('dashboard');
expect(viewFromHash('#now')).toBe('dashboard');
expect(viewFromHash('#dashboard')).toBe('dashboard');
});
it('keeps the remaining flat views bookmarkable', () => {
expect(viewFromHash('#queue')).toBe('queue');
expect(viewFromHash('#server')).toBe('server');
});
});
+13 -24
View File
@@ -1,51 +1,40 @@
// Tiny hash router: keeps the active view in the URL so views are // Tiny hash router: keeps the active view in the URL so views are
// bookmarkable and the browser back/forward buttons work. No dependency — // 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 // the app has a single flat set of views.
// `#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 { appStore, type ViewName } from './app';
import { joinRoom, watchStore } from './watch';
const VIEWS: readonly ViewName[] = [ const VIEWS: readonly ViewName[] = [
'now', 'dashboard',
'queue', 'queue',
'search', 'search',
'library', 'library',
'stats', 'stats',
'rooms',
'watch',
'server', 'server',
'rpc', 'rpc',
]; ];
// The view named by the current hash, defaulting to `now`. Handles both // The view named by the current hash, defaulting to `dashboard`. Old `#now`
// `#queue` and the watch form `#watch/<room>`. // bookmarks are intentionally canonicalized during router initialization.
export function viewFromHash(): ViewName { export function viewFromHash(hash = location.hash): ViewName {
const raw = location.hash.replace(/^#\/?/, ''); const raw = hash.replace(/^#\/?/, '');
const base = raw.split(/[/?]/)[0]; const base = raw.split(/[/?]/)[0];
if (base === 'now') return 'dashboard';
return (VIEWS as readonly string[]).includes(base) return (VIEWS as readonly string[]).includes(base)
? (base as ViewName) ? (base as ViewName)
: 'now'; : 'dashboard';
}
function roomFromHash(): string | null {
const m = location.hash.match(/^#watch\/([\w-]{1,48})/);
return m ? m[1] : null;
} }
export function initRouter() { export function initRouter() {
// Initial view comes from the hash (refresh / shared link). // Initial view comes from the hash (refresh / shared link).
appStore.set({ view: viewFromHash() }); const initial = viewFromHash();
appStore.set({ view: initial });
if (location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] === 'now') {
history.replaceState(null, '', '#dashboard');
}
window.addEventListener('hashchange', () => { window.addEventListener('hashchange', () => {
const view = viewFromHash(); const view = viewFromHash();
appStore.set({ view }); 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);
}
}); });
} }
+19 -17
View File
@@ -62,23 +62,25 @@ export type RpcMethodName =
| 'GetAuditLog' | 'GetAuditLog'
| 'GetUserPrefs' | 'GetUserPrefs'
| 'SetUserPrefs' | 'SetUserPrefs'
| 'GetCustomEmojis' | 'GetCapabilities'
| 'AddCustomEmoji' | 'GetPluginExtensions'
| 'RemoveCustomEmoji' | 'PluginCall'
| 'ListListeningRooms' | 'GetTeamSpeakDirectory'
| 'CreateListeningRoom' | 'MoveTeamSpeakClient'
| 'DeleteListeningRoom' | 'KickTeamSpeakClient'
| 'JoinListeningRoom' | 'BanTeamSpeakClient'
| 'LeaveListeningRoom' | 'GetTeamSpeakBans'
| 'PlayInListeningRoom' | 'UnbanTeamSpeakClient'
| 'PauseListeningRoom' | 'CreateTeamSpeakChannel'
| 'ResumeListeningRoom' | 'EditTeamSpeakChannel'
| 'StopListeningRoom' | 'ReorderTeamSpeakChannel'
| 'GetListeningRoomQueue' | 'DeleteTeamSpeakChannel'
| 'SkipListeningRoom' | 'GetTeamSpeakServerGroups'
| 'RemoveFromListeningRoomQueue' | 'AddTeamSpeakServerGroupMember'
| 'MoveInListeningRoomQueue' | 'RemoveTeamSpeakServerGroupMember'
| 'ClearListeningRoomQueue'; | 'SendTeamSpeakPrivateMessage'
| 'SendTeamSpeakChannelMessage'
| 'SendTeamSpeakServerMessage';
type Pending = { type Pending = {
+42 -15
View File
@@ -12,6 +12,48 @@ export interface Track {
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
} }
export interface PublicDashboardClient {
nickname: string;
talking: boolean;
muted: boolean;
deafened: boolean;
away: boolean;
}
export interface PublicDashboardChannel {
id: number;
name: string;
parentId: number | null;
order: number;
default: boolean;
permanent: boolean;
semiPermanent: boolean;
password: boolean;
maxClients: number;
currentClients: number;
clients: PublicDashboardClient[];
channels: PublicDashboardChannel[];
}
export interface PublicDashboard {
server: {
name: string;
connected: boolean;
clientCount: number;
maxClients: number;
channelCount: number;
revision: number;
};
channels: PublicDashboardChannel[];
playback: {
isPlaying: boolean;
isPaused: boolean;
positionMs: number;
volume: number;
track: (Track & { durationMs?: number; album?: string }) | null;
};
}
export interface QueueEntry { export interface QueueEntry {
queueId: number; queueId: number;
track: Track; track: Track;
@@ -19,21 +61,6 @@ export interface QueueEntry {
addedBy?: string; addedBy?: string;
} }
export interface ListeningRoom {
name: string;
ownerId: number;
members: number[];
isPlaying: boolean;
isPaused: boolean;
queueSize: number;
isOwner: boolean;
}
export interface ListeningRoomList {
rooms: ListeningRoom[];
currentRoom?: string;
}
export interface Status { export interface Status {
isPlaying?: boolean; isPlaying?: boolean;
isPaused?: boolean; isPaused?: boolean;
-53
View File
@@ -1,53 +0,0 @@
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
+2 -3
View File
@@ -1,6 +1,5 @@
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now // Shared loader for the dashboard's muted YouTube preview. The script is
// Playing video preview use it; the script is injected once and callers await // injected once and callers await the same readiness promise.
// the same readiness promise.
// //
// Console-error triage for the YouTube embeds (as seen in production behind // Console-error triage for the YouTube embeds (as seen in production behind
// the reverse proxy): // the reverse proxy):
+1 -1
View File
@@ -5,7 +5,7 @@ import './styles/style.css';
// Human-readable fingerprint for deployment/debugging. Vite's filename hash // Human-readable fingerprint for deployment/debugging. Vite's filename hash
// can legitimately match an older backup when the emitted code becomes // can legitimately match an older backup when the emitted code becomes
// byte-identical after a revert, so expose an explicit release identity too. // byte-identical after a revert, so expose an explicit release identity too.
export const WEB_BUILD_ID = '2026.07.10-player-fix.3'; export const WEB_BUILD_ID = '2026.07.13-external-player-fix.1';
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID; document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
console.info(`[Echoion] web build ${WEB_BUILD_ID}`); console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
+109 -270
View File
@@ -166,7 +166,7 @@ select:focus:not(:focus-visible) { outline: none; }
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons /* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
and never shrink in flex rows. */ and never shrink in flex rows. */
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg { .btn svg, .icon-btn svg, .ctrl svg, .pill svg, .link svg {
vertical-align: -0.125em; flex: none; vertical-align: -0.125em; flex: none;
} }
@@ -398,145 +398,15 @@ select:focus:not(:focus-visible) { outline: none; }
.split-legend span { display: inline-flex; align-items: center; gap: 6px; } .split-legend span { display: inline-flex; align-items: center; gap: 6px; }
.split-legend b { color: var(--text-2); margin-left: 2px; } .split-legend b { color: var(--text-2); margin-left: 2px; }
/* ── Watch Together ───────────────────────────────────────────────────── */ /* ── Shared playback controls ─────────────────────────────────────────── */
.watch-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 18px; align-items: start; } .player-control-row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.src-yt.active { background: rgba(255, 92, 92, 0.16); border-color: rgba(255, 92, 92, 0.4); color: var(--red-text); } .player-control-row .ctrl-main { width: 42px; height: 42px; }
.src-tw.active { background: rgba(169, 112, 255, 0.18); border-color: rgba(169, 112, 255, 0.4); color: #c3a3ff; } .player-local-row .bar { flex: 0 0 130px; }
.src-direct.active { background: rgba(95, 224, 148, 0.16); border-color: rgba(95, 224, 148, 0.4); color: var(--green-text); } .player-local-row[hidden] { display: none; }
.src-iframe.active { background: rgba(255, 217, 119, 0.16); border-color: rgba(255, 217, 119, 0.4); color: #ffd977; }
/* The direct <video> and generic <iframe> fill the player box like the embeds. */
#watchPlayer video, #watchPlayer iframe { width: 100%; height: 100%; display: block; background: #000; }
.player-box {
position: relative; width: 100%; aspect-ratio: 16 / 9;
border-radius: 12px; overflow: hidden;
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
margin-bottom: 14px;
}
.player-box iframe, .player-box > div:first-child { position: absolute; inset: 0; width: 100%; height: 100%; }
/* The shell owns the outer spacing; the control bar overlays the video bottom
(windowed and fullscreen) so it can fade out when idle. */
.player-shell { position: relative; margin-bottom: 14px; }
.player-shell .player-box { margin-bottom: 0; }
.player-shell.youtube-native .player-overlay { bottom: 42px; }
.player-overlay {
position: absolute; left: 0; right: 0; bottom: 0; z-index: 5;
padding: 34px 14px 8px;
background: linear-gradient(to top,
rgba(0,0,0,0.82) 0%, rgba(0,0,0,0.45) 46%, rgba(0,0,0,0) 100%);
opacity: 1; transition: opacity 0.25s ease;
}
.player-overlay .watch-controls { margin-bottom: 8px; }
.player-overlay .watch-controls:last-child { margin-bottom: 0; }
/* Lift muted/mono text for legibility over video. */
.player-overlay .muted, .player-overlay .mono { color: #e9e9f2; }
/* Idle-hidden while playing (the hook removes the class when paused). Hover /
keyboard focus (incl. an open quality/speed dropdown) reveals regardless. */
.player-shell.controls-hidden .player-overlay { opacity: 0; pointer-events: none; }
.player-shell.controls-hidden { cursor: none; }
.player-shell.controls-hidden:hover .player-overlay,
.player-shell.controls-hidden:focus-within .player-overlay {
opacity: 1; pointer-events: auto;
}
.player-shell.controls-hidden:hover,
.player-shell.controls-hidden:focus-within { cursor: auto; }
/* Fullscreen targets the shell: the player fills the screen and the overlay
floats at the bottom (controls stay usable while fullscreen). */
.player-shell:fullscreen { background: #000; padding: 0; }
.player-shell:fullscreen .player-box {
width: 100%; height: 100%; aspect-ratio: auto;
border-radius: 0; margin: 0;
}
.player-shell:fullscreen .player-overlay { padding: 46px 24px 18px; }
.player-empty {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
color: var(--faint); font-size: 13.5px;
pointer-events: none;
text-align: center; padding: 0 24px;
}
.player-empty[hidden] { display: none; }
/* Muted-autoplay affordance overlaid on the player until the user unmutes. */
.unmute-btn {
position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%);
z-index: 6; box-shadow: 0 4px 16px rgba(0,0,0,0.5);
}
/* Watch lobby (no room joined). */
.watch-lobby { max-width: 640px; margin: 0 auto; }
.watch-lobby .rooms-list { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }
.watch-lobby .room-chip { justify-content: flex-start; text-align: left; }
.room-now { font-style: italic; }
.watch-controls { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.watch-controls .ctrl-main { width: 42px; height: 42px; }
.watch-local .bar { flex: 0 0 130px; }
.watch-local[hidden] { display: none; }
.quality-select {
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--line);
color: var(--text-2);
border-radius: 8px;
padding: 6px 8px;
font: inherit;
font-size: 12.5px;
}
.player-settings { position: relative; }
.player-settings-popover {
position: absolute; right: 0; bottom: calc(100% + 10px); z-index: 20;
width: min(290px, 80vw); padding: 10px;
border: 1px solid rgba(255,255,255,0.14); border-radius: 12px;
background: rgba(14, 14, 28, 0.96);
box-shadow: 0 18px 46px rgba(0,0,0,0.5);
backdrop-filter: blur(18px);
}
.player-settings-popover section + section {
margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--line);
}
.player-settings-heading {
margin: 0 2px 7px; color: var(--faint); font-size: 10px;
font-weight: 800; letter-spacing: .13em; text-transform: uppercase;
}
.player-setting {
display: grid; grid-template-columns: minmax(80px, 1fr) minmax(110px, 1.35fr);
align-items: center; gap: 10px; padding: 5px 2px;
color: var(--text-2); font-size: 12.5px;
}
.player-setting select {
min-width: 0; width: 100%; padding: 6px 8px;
border: 1px solid var(--line); border-radius: 8px;
background: #1b1b31; color: var(--text-2); font: inherit;
}
.ctrl:disabled, .btn:disabled, .icon-btn:disabled { .ctrl:disabled, .btn:disabled, .icon-btn:disabled {
opacity: 0.4; opacity: 0.4;
cursor: not-allowed; cursor: not-allowed;
} }
.reactions { display: flex; gap: 8px; }
.reaction {
padding: 8px 14px; border-radius: 10px;
border: 1px solid var(--line); background: transparent;
cursor: pointer; font-size: 16px;
}
.reaction:hover { background: rgba(255, 255, 255, 0.06); }
.reaction-fly {
position: fixed; font-size: 26px; pointer-events: none;
animation: fly-up 1.6s ease-out forwards; z-index: 60;
}
@keyframes fly-up { to { transform: translateY(-120px); opacity: 0; } }
.chat-card { display: flex; flex-direction: column; }
.chat-log {
display: flex; flex-direction: column; gap: 10px;
max-height: 320px; overflow-y: auto;
margin-bottom: 12px; padding-right: 4px;
}
.chat-msg { display: flex; gap: 10px; align-items: flex-start; }
.chat-body { min-width: 0; }
.chat-name { font-weight: 700; font-size: 12.5px; color: var(--accent-2); }
.chat-time { color: var(--faint); font-size: 11px; margin-left: 6px; }
.chat-text { font-size: 13px; color: var(--text-2); margin-top: 1px; word-break: break-word; }
.chat-row { display: flex; gap: 8px; }
.chat-row input { flex: 1; }
/* ── RPC view ─────────────────────────────────────────────────────────── */ /* ── RPC view ─────────────────────────────────────────────────────────── */
.rpc-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; } .rpc-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }
@@ -587,7 +457,7 @@ select:focus:not(:focus-visible) { outline: none; }
.drawer-backdrop { display: none; } .drawer-backdrop { display: none; }
@media (max-width: 1080px) { @media (max-width: 1080px) {
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; } .now-grid, .stats-grid { grid-template-columns: 1fr; }
} }
/* Tablet and below: the sidebar becomes a slide-in drawer. */ /* Tablet and below: the sidebar becomes a slide-in drawer. */
@@ -620,10 +490,10 @@ select:focus:not(:focus-visible) { outline: none; }
.header h1 { font-size: 20px; } .header h1 { font-size: 20px; }
.card { padding: 14px; } .card { padding: 14px; }
.np-title { font-size: 19px; } .np-title { font-size: 19px; }
.search-row, .chat-row, .rooms-create, .row-gap { flex-wrap: wrap; } .search-row, .row-gap { flex-wrap: wrap; }
.search-row input, .chat-row input { min-width: 0; flex: 1 1 160px; } .search-row input { min-width: 0; flex: 1 1 160px; }
.watch-controls { flex-wrap: wrap; row-gap: 8px; } .player-control-row { flex-wrap: wrap; row-gap: 8px; }
.watch-local .bar { flex: 1 1 100px; } .player-local-row .bar { flex: 1 1 100px; }
.tabs { overflow-x: auto; } .tabs { overflow-x: auto; }
.audit-row { grid-template-columns: 1fr auto; } .audit-row { grid-template-columns: 1fr auto; }
.audit-time { grid-column: 1 / -1; } .audit-time { grid-column: 1 / -1; }
@@ -653,9 +523,6 @@ select:focus:not(:focus-visible) { outline: none; }
/* Reactions rendered inside the player box (the vanilla UI appended them /* Reactions rendered inside the player box (the vanilla UI appended them
to <body> at fixed coordinates). */ to <body> at fixed coordinates). */
.reaction-layer { position: absolute; inset: 0; pointer-events: none; overflow: hidden; }
.reaction-fly-abs { position: absolute; bottom: 50px; }
.player-box { position: relative; }
/* Drop indicator for queue drag-and-drop (item 9). */ /* Drop indicator for queue drag-and-drop (item 9). */
.drop-indicator { .drop-indicator {
@@ -675,6 +542,104 @@ select:focus:not(:focus-visible) { outline: none; }
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; } .np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
.np-video-toggle.on { color: #b28dff; } .np-video-toggle.on { color: #b28dff; }
/* Public TeamSpeak directory. Nested channels keep their server order while
the guide line makes deep trees readable without turning them into tables. */
.ts-directory-card { min-height: 360px; }
.ts-server-head { align-items: flex-start; }
.ts-server-head h2 { margin-bottom: 2px; }
.ts-connected { color: #74e5a2; border-color: rgba(95, 224, 148, 0.3); }
.ts-disconnected { color: #ef8a8a; border-color: rgba(239, 99, 99, 0.28); }
.ts-summary {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
margin: 14px 0 16px;
}
.ts-summary > div {
display: flex; flex-direction: column; gap: 2px;
padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.ts-summary strong { font-size: 18px; }
.ts-summary span { color: var(--muted-2); font-size: 11px; }
.ts-tree { display: flex; flex-direction: column; gap: 3px; }
.ts-channel {
position: relative;
margin-left: calc(var(--tree-depth, 0) * 18px);
}
.ts-channel::before {
content: ''; position: absolute; left: -10px; top: 0; bottom: 0;
border-left: 1px solid rgba(255, 255, 255, 0.08);
}
.ts-channel-row, .ts-client-row {
display: flex; align-items: center; min-width: 0;
border-radius: 8px;
}
.ts-channel-row { min-height: 34px; padding: 4px 7px; gap: 7px; }
.ts-channel-row:hover, .ts-client-row:hover { background: rgba(255, 255, 255, 0.035); }
.ts-channel-caret { width: 14px; color: var(--faint); text-align: center; }
.ts-channel-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-weight: 650; }
.ts-capacity { margin-left: auto; color: var(--faint); font: 11px var(--font-mono); }
.ts-tag {
padding: 2px 6px; border-radius: 999px; color: var(--muted-2);
background: rgba(255, 255, 255, 0.06); font-size: 9px;
letter-spacing: 0.04em; text-transform: uppercase;
}
.ts-client-row { min-height: 30px; margin-left: 26px; padding: 3px 8px; gap: 8px; }
.ts-presence { width: 7px; height: 7px; flex: none; border-radius: 50%; background: #687080; }
.ts-presence.talking { background: #5fe094; box-shadow: 0 0 0 4px rgba(95, 224, 148, 0.1); }
.ts-client-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
.ts-client-flags { display: flex; gap: 5px; margin-left: auto; }
.ts-client-flags span {
color: var(--faint); font-size: 9px; text-transform: uppercase;
letter-spacing: 0.04em;
}
.nav-external { margin-left: auto; color: var(--faint); }
/* Guarded administration surface. */
.admin-tabs {
display: flex; gap: 4px; overflow-x: auto; margin-bottom: 14px;
padding: 4px; border: 1px solid var(--line); border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.admin-tab {
flex: none; border: 0; border-radius: 8px; padding: 8px 13px;
background: transparent; color: var(--muted-2); cursor: pointer;
font: inherit; font-size: 12px; font-weight: 650;
}
.admin-tab.active { background: rgba(124, 92, 255, 0.16); color: #c9bfff; }
.admin-stack { display: flex; flex-direction: column; gap: 14px; }
.admin-action-grid { display: flex; flex-wrap: wrap; gap: 10px; }
.admin-guard { max-width: 620px; }
.ts-admin-tree { display: flex; flex-direction: column; gap: 7px; }
.ts-admin-channel {
border-left: 1px solid rgba(255, 255, 255, 0.08);
padding: 7px 0 2px 10px;
}
.ts-admin-channel-head {
display: flex; align-items: center; gap: 7px; flex-wrap: wrap;
min-height: 34px;
}
.ts-admin-channel-head .ts-capacity { margin-left: 0; margin-right: auto; }
.ts-admin-client {
display: grid; grid-template-columns: minmax(180px, 0.8fr) minmax(250px, 1.2fr) auto;
gap: 10px; align-items: center; margin: 5px 0 5px 20px; padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.055); border-radius: 9px;
background: rgba(255, 255, 255, 0.018);
}
.ts-admin-client-main, .ts-admin-private, .ts-admin-actions {
display: flex; align-items: center; gap: 7px; min-width: 0; flex-wrap: wrap;
}
.ts-admin-private { font: 10px var(--font-mono); }
.ts-admin-actions { justify-content: flex-end; }
.ts-admin-actions .btn, .ts-admin-channel-head .btn { padding: 5px 8px; font-size: 10px; }
.ts-ban-row {
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
align-items: center; padding: 9px 0; border-bottom: 1px solid var(--line);
}
@media (max-width: 900px) {
.ts-admin-client { grid-template-columns: 1fr; }
.ts-admin-actions { justify-content: flex-start; }
}
/* Announce composer modal (item 14). */ /* Announce composer modal (item 14). */
.modal-backdrop { .modal-backdrop {
position: fixed; inset: 0; z-index: 100; display: flex; position: fixed; inset: 0; z-index: 100; display: flex;
@@ -720,129 +685,3 @@ select:focus:not(:focus-visible) { outline: none; }
} }
.ts-markup details { margin: 0.4em 0; } .ts-markup details { margin: 0.4em 0; }
.ts-markup summary { cursor: pointer; font-weight: 600; } .ts-markup summary { cursor: pointer; font-weight: 600; }
/* Watch Together room switcher (item 3). */
.pill-room { cursor: pointer; border: none; font: inherit; }
.rooms-panel {
display: flex; flex-direction: column; gap: 10px;
padding: 12px; margin: 4px 0 2px;
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px;
background: rgba(255, 255, 255, 0.03);
}
.rooms-list { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.room-chip {
background: rgba(255, 255, 255, 0.06); border: 1px solid transparent;
border-radius: 8px; padding: 5px 10px; cursor: pointer;
color: inherit; font: inherit; font-size: 13px;
}
.room-chip.active { border-color: #7c5cff; color: #b28dff; }
.rooms-create { display: flex; gap: 8px; }
.rooms-create input { flex: 1; }
/* ── Independent listening rooms ─────────────────────────────────────── */
.listening-rooms-view { --room-cyan: #61e4d8; --room-cyan-soft: rgba(97, 228, 216, .12); }
.rooms-hero {
display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(280px, .7fr);
gap: 28px; align-items: end; margin-bottom: 18px; padding: 24px;
border: 1px solid rgba(97, 228, 216, .15); border-radius: 18px;
background: radial-gradient(circle at 92% 8%, rgba(97, 228, 216, .14), transparent 34%), linear-gradient(115deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025));
position: relative; overflow: hidden;
}
.rooms-hero::after {
content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .22;
background-image: linear-gradient(rgba(255,255,255,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.035) 1px, transparent 1px);
background-size: 28px 28px; mask-image: linear-gradient(90deg, transparent, #000);
}
.rooms-hero > * { position: relative; z-index: 1; }
.rooms-hero h2 { font-size: clamp(20px, 2.5vw, 31px); max-width: 620px; letter-spacing: -.035em; }
.rooms-hero p { color: var(--muted); line-height: 1.55; max-width: 620px; margin-top: 8px; }
.rooms-kicker { display: block; margin-bottom: 7px; color: var(--room-cyan); font-family: var(--font-mono); font-size: 10px; font-weight: 700; letter-spacing: .18em; }
.listening-room-create { display: flex; gap: 8px; }
.listening-room-create input { flex: 1; min-width: 0; }
.listening-room-create .btn, .room-play-form .btn { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.listening-room-grid { display: grid; grid-template-columns: minmax(260px, .7fr) minmax(0, 1.3fr); gap: 18px; align-items: start; }
.room-directory, .room-console { min-height: 440px; }
.listening-room-list { display: flex; flex-direction: column; gap: 8px; }
.listening-room-card { width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding: 12px; text-align: left; color: var(--text-2); background: rgba(255,255,255,.025); border: 1px solid rgba(255,255,255,.055); border-radius: 11px; cursor: pointer; transition: border-color .16s, background .16s, transform .16s; }
.listening-room-card:hover { transform: translateX(2px); border-color: rgba(97,228,216,.22); background: rgba(97,228,216,.045); }
.listening-room-card.active { border-color: rgba(97,228,216,.5); background: var(--room-cyan-soft); box-shadow: inset 3px 0 0 var(--room-cyan); }
.room-signal { width: 9px; height: 9px; border-radius: 50%; background: var(--faint); box-shadow: 0 0 0 4px rgba(255,255,255,.025); }
.room-signal.playing { background: var(--room-cyan); box-shadow: 0 0 0 4px rgba(97,228,216,.1), 0 0 14px rgba(97,228,216,.45); animation: ech-pulse 1.6s infinite; }
.room-card-copy { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.room-card-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.room-card-copy small { color: var(--muted-2); }
.room-state { font-family: var(--font-mono); font-size: 9px; font-weight: 700; letter-spacing: .1em; color: var(--room-cyan); }
.room-console { position: relative; overflow: hidden; }
.room-console::before { content: ''; position: absolute; top: 0; right: 0; width: 180px; height: 180px; background: radial-gradient(circle at top right, rgba(124,92,255,.1), transparent 68%); pointer-events: none; }
.room-console-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; margin-bottom: 18px; position: relative; }
.room-console-head h2 { font-size: 25px; }
.room-console-empty { min-height: 390px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; color: var(--muted); }
.room-console-empty h2 { color: var(--text); margin: 8px 0 5px; }
.room-console-glyph { font-family: var(--font-mono); font-size: 54px; font-weight: 700; color: rgba(97,228,216,.15); letter-spacing: -.12em; }
.room-transport { display: flex; align-items: center; gap: 12px; padding: 14px; margin-bottom: 14px; border: 1px solid rgba(97,228,216,.12); border-radius: 13px; background: linear-gradient(90deg, rgba(97,228,216,.07), rgba(255,255,255,.025)); }
.room-transport .ctrl-main { background: var(--room-cyan); color: #061715; box-shadow: 0 5px 22px rgba(97,228,216,.22); }
.stop-square { width: 9px; height: 9px; background: currentColor; border-radius: 1px; }
.room-transport-copy { display: flex; flex-direction: column; gap: 2px; }
.room-transport-copy small { color: var(--muted-2); }
.room-play-form { display: flex; gap: 8px; margin-bottom: 20px; }
.room-play-form input { flex: 1; min-width: 0; }
.room-queue-head { display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--line); padding-top: 16px; margin-bottom: 5px; }
.room-queue-head span { color: var(--muted-2); font-family: var(--font-mono); font-size: 11px; }
.room-tracklist { max-height: 330px; overflow-y: auto; }
@media (max-width: 1080px) {
.listening-room-grid { grid-template-columns: 1fr; }
.room-directory, .room-console { min-height: 0; }
}
@media (max-width: 560px) {
.rooms-hero { grid-template-columns: 1fr; padding: 18px; }
.listening-room-create, .room-play-form { flex-wrap: wrap; }
.listening-room-create input, .room-play-form input { flex-basis: 100%; }
.room-console-head { flex-direction: column; }
}
/* Watch search (item 20). */
.watch-search { position: relative; margin-bottom: 8px; }
.watch-search-results {
position: absolute; z-index: 30; left: 0; right: 0; top: 100%;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px; margin-top: 4px; max-height: 320px; overflow: auto;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.watch-search-item {
display: flex; align-items: center; gap: 10px; width: 100%;
padding: 6px 10px; background: transparent; border: none; cursor: pointer;
color: inherit; text-align: left; font: inherit;
}
.watch-search-item:hover { background: rgba(255, 255, 255, 0.06); }
.watch-search-item .track-cover { width: 48px; height: 27px; flex: none; border-radius: 4px; }
.watch-search-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Emoji picker + custom emojis (item 16). */
.emoji-anchor { position: relative; display: inline-flex; }
.emoji-trigger { padding: 6px 8px; }
.emoji-picker {
position: absolute; bottom: 100%; left: 0; z-index: 40; width: 300px;
max-height: 320px; overflow-y: auto; margin-bottom: 6px; padding: 8px;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.emoji-section { margin-bottom: 8px; }
.emoji-section-label {
font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
color: #8a8a98; margin: 4px 2px;
}
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; }
.emoji-btn {
background: transparent; border: none; cursor: pointer; font-size: 20px;
line-height: 1; padding: 4px; border-radius: 6px;
}
.emoji-btn:hover { background: rgba(255, 255, 255, 0.08); }
.emoji-img { width: 20px; height: 20px; vertical-align: middle; object-fit: contain; }
.emoji-img-lg { width: 30px; height: 30px; object-fit: contain; }
.emoji-manage-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; }
.emoji-manage-grid { display: flex; flex-wrap: wrap; gap: 12px; }
.emoji-manage-item {
display: flex; align-items: center; gap: 6px;
background: rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 6px 10px;
}
@@ -1,4 +1,4 @@
import { useState } from 'react'; import { useState, type CSSProperties } from 'react';
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app'; import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
import { useStore } from '../lib/store'; import { useStore } from '../lib/store';
import { PlayerControls } from '../components/PlayerControls'; import { PlayerControls } from '../components/PlayerControls';
@@ -15,8 +15,9 @@ import {
SkipPrevIcon, SkipPrevIcon,
} from '../components/icons'; } from '../components/icons';
import { t, tf } from '../i18n'; import { t, tf } from '../i18n';
import type { PublicDashboardChannel } from '../lib/types';
const VIDEO_PREF_KEY = 'echoion.npVideo'; const DASHBOARD_VIDEO_PREF_KEY = 'echoion.npVideo';
async function togglePlay() { async function togglePlay() {
const st = appStore.get().status || {}; const st = appStore.get().status || {};
@@ -24,10 +25,62 @@ async function togglePlay() {
else await safeCall('Resume'); else await safeCall('Resume');
} }
export function NowView() { function ChannelNode({
channel,
depth = 0,
}: {
channel: PublicDashboardChannel;
depth?: number;
}) {
return (
<div
className="ts-channel"
style={{ '--tree-depth': depth } as CSSProperties}
>
<div className="ts-channel-row">
<span className="ts-channel-caret" aria-hidden="true">
{channel.channels.length || channel.clients.length ? '⌄' : '·'}
</span>
<span className="ts-channel-name">{channel.name}</span>
{channel.default && <span className="ts-tag">{t('default')}</span>}
{channel.password && (
<span className="ts-tag" title={t('Password protected')}>
{t('locked')}
</span>
)}
<span className="ts-capacity">
{channel.currentClients}/
{channel.maxClients > 0 ? channel.maxClients : '∞'}
</span>
</div>
{channel.clients.map((client, index) => (
<div
className="ts-client-row"
key={`${client.nickname}-${index}`}
>
<span
className={'ts-presence' + (client.talking ? ' talking' : '')}
aria-label={client.talking ? t('Talking') : t('Online')}
/>
<span className="ts-client-name">{client.nickname}</span>
<div className="ts-client-flags">
{client.away && <span title={t('Away')}>away</span>}
{client.muted && <span title={t('Muted')}>mic off</span>}
{client.deafened && <span title={t('Deafened')}>sound off</span>}
</div>
</div>
))}
{channel.channels.map((child) => (
<ChannelNode key={child.id} channel={child} depth={depth + 1} />
))}
</div>
);
}
export function DashboardView() {
const s = useStore(appStore); const s = useStore(appStore);
const [videoOn, setVideoOn] = useState( const [videoOn, setVideoOn] = useState(
localStorage.getItem(VIDEO_PREF_KEY) === '1' localStorage.getItem(DASHBOARD_VIDEO_PREF_KEY) === '1'
); );
const track = s.current; const track = s.current;
const videoId = youtubeIdFromUrl(track?.url); const videoId = youtubeIdFromUrl(track?.url);
@@ -50,7 +103,7 @@ export function NowView() {
const needed = st.skipVotesNeeded || 0; const needed = st.skipVotesNeeded || 0;
return ( return (
<section className="view" id="view-now"> <section className="view" id="view-dashboard">
<div className="now-grid"> <div className="now-grid">
<div className="card np-card"> <div className="card np-card">
{showVideo && videoId ? ( {showVideo && videoId ? (
@@ -72,7 +125,7 @@ export function NowView() {
const next = !videoOn; const next = !videoOn;
setVideoOn(next); setVideoOn(next);
localStorage.setItem( localStorage.setItem(
VIDEO_PREF_KEY, DASHBOARD_VIDEO_PREF_KEY,
next ? '1' : '0' next ? '1' : '0'
); );
}} }}
@@ -94,7 +147,7 @@ export function NowView() {
playing={playing} playing={playing}
positionMs={s.positionMs} positionMs={s.positionMs}
durationMs={durationMs} durationMs={durationMs}
canControl canControl={!!s.identity}
volumePct={volumePct} volumePct={volumePct}
onTogglePlay={togglePlay} onTogglePlay={togglePlay}
onSeekMs={(ms) => onSeekMs={(ms) =>
@@ -108,7 +161,7 @@ export function NowView() {
? () => safeCall('Skip', { count: 1 }) ? () => safeCall('Skip', { count: 1 })
: undefined : undefined
} }
extra={ extra={s.identity ? (
<> <>
<button <button
className={ className={
@@ -210,8 +263,8 @@ export function NowView() {
</span> </span>
</button> </button>
</> </>
} ) : undefined}
extraLocal={ extraLocal={s.identity ? (
<label className="toggle-row"> <label className="toggle-row">
<span className="muted">{t('Radio')}</span> <span className="muted">{t('Radio')}</span>
<button <button
@@ -251,11 +304,66 @@ export function NowView() {
<span className="knob" /> <span className="knob" />
</button> </button>
</label> </label>
} ) : undefined}
/> />
</div> </div>
</div> </div>
<div className="col"> <div className="col">
<div className="card ts-directory-card">
<div className="card-head ts-server-head">
<div>
<h2>
{s.publicDashboard?.server.name ||
t('TeamSpeak server')}
</h2>
<span className="muted">
{t('Complete channel directory')}
</span>
</div>
<span
className={
'pill ' +
(s.publicDashboard?.server.connected
? 'ts-connected'
: 'ts-disconnected')
}
>
{s.publicDashboard?.server.connected
? t('Connected')
: t('Disconnected')}
</span>
</div>
<div className="ts-summary">
<div>
<strong>
{s.publicDashboard?.server.clientCount || 0}
</strong>
<span>{t('clients')}</span>
</div>
<div>
<strong>
{s.publicDashboard?.server.channelCount || 0}
</strong>
<span>{t('channels')}</span>
</div>
<div>
<strong>
{s.publicDashboard?.server.maxClients || '∞'}
</strong>
<span>{t('capacity')}</span>
</div>
</div>
<div className="ts-tree">
{s.publicDashboard?.channels.length ? (
s.publicDashboard.channels.map((channel) => (
<ChannelNode key={channel.id} channel={channel} />
))
) : (
<EmptyRow text={t('No channels available')} />
)}
</div>
</div>
{s.identity && (
<div className="card"> <div className="card">
<div className="card-head"> <div className="card-head">
<h2>{t('Up Next')}</h2> <h2>{t('Up Next')}</h2>
@@ -286,7 +394,9 @@ export function NowView() {
})()} })()}
</div> </div>
</div> </div>
<LyricsPanel /> )}
{s.identity && <LyricsPanel />}
{s.identity && (
<div className="card"> <div className="card">
<div className="card-head"> <div className="card-head">
<h3>{t('Listening now')}</h3> <h3>{t('Listening now')}</h3>
@@ -311,6 +421,7 @@ export function NowView() {
)} )}
</div> </div>
</div> </div>
)}
</div> </div>
</div> </div>
</section> </section>
-244
View File
@@ -1,244 +0,0 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type {
ListeningRoom,
ListeningRoomList,
QueueEntry,
} from '../lib/types';
import { confirmDialog } from '../lib/dialog';
import {
CloseIcon,
ArrowDownIcon,
ArrowUpIcon,
PauseIcon,
PlayIcon,
PlusIcon,
RefreshIcon,
SkipNextIcon,
} from '../components/icons';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { t, tf } from '../i18n';
import { rpc } from '../lib/rpc';
export function RoomsView() {
const [rooms, setRooms] = useState<ListeningRoom[]>([]);
const [currentRoom, setCurrentRoom] = useState<string | null>(null);
const [queue, setQueue] = useState<QueueEntry[]>([]);
const [roomName, setRoomName] = useState('');
const [query, setQuery] = useState('');
const [busy, setBusy] = useState(false);
const current = useMemo(
() => rooms.find((room) => room.name === currentRoom) || null,
[rooms, currentRoom]
);
const refresh = useCallback(async () => {
const result = await safeCall<ListeningRoomList>('ListListeningRooms');
if (!result) return;
setRooms(result.rooms || []);
setCurrentRoom(result.currentRoom || null);
if (result.currentRoom) {
const queueResult = await safeCall<{ queue?: QueueEntry[] }>(
'GetListeningRoomQueue',
{ room: result.currentRoom }
);
setQueue(queueResult?.queue || []);
} else {
setQueue([]);
}
}, []);
useEffect(() => {
void refresh();
const unsubscribe = rpc.on('listening_rooms.updated', () => void refresh());
const timer = window.setInterval(refresh, 30000);
return () => {
unsubscribe();
window.clearInterval(timer);
};
}, [refresh]);
const action = async (
method:
| 'JoinListeningRoom'
| 'LeaveListeningRoom'
| 'PauseListeningRoom'
| 'ResumeListeningRoom'
| 'StopListeningRoom'
| 'SkipListeningRoom'
| 'ClearListeningRoomQueue',
room?: string
) => {
setBusy(true);
const result = await safeCall(method, room ? { room } : undefined);
setBusy(false);
if (result) await refresh();
};
return (
<section className="view listening-rooms-view" id="view-rooms">
<div className="rooms-hero">
<div>
<span className="rooms-kicker">{t('MULTI-STREAM')}</span>
<h2>{t('Your channel, split into listening spaces')}</h2>
<p>
{t(
'Each room has its own queue and bot stream. Join one to hear and control it.'
)}
</p>
</div>
<form
className="listening-room-create"
onSubmit={async (event) => {
event.preventDefault();
const name = roomName.trim();
if (!name) return;
setBusy(true);
const result = await safeCall('CreateListeningRoom', {
room: name,
});
setBusy(false);
if (result) {
setRoomName('');
toast(tf('Created room “{0}”', name));
await refresh();
}
}}
>
<input
value={roomName}
onChange={(event) => setRoomName(event.target.value)}
placeholder={t('Room name')}
maxLength={48}
/>
<button className="btn btn-accent" disabled={busy || !roomName.trim()}>
<PlusIcon /> {t('Create room')}
</button>
</form>
</div>
<div className="listening-room-grid">
<div className="card room-directory">
<div className="card-head">
<h2>{t('Live rooms')}</h2>
<button className="icon-btn" onClick={refresh} title={t('Refresh rooms')}>
<RefreshIcon />
</button>
</div>
{rooms.length === 0 ? (
<EmptyRow text={t('No listening rooms yet')} />
) : (
<div className="listening-room-list">
{rooms.map((room) => {
const selected = room.name === currentRoom;
return (
<button
key={room.name}
className={'listening-room-card' + (selected ? ' active' : '')}
disabled={busy}
onClick={() => !selected && action('JoinListeningRoom', room.name)}
>
<span className={'room-signal' + (room.isPlaying ? ' playing' : '')} />
<span className="room-card-copy">
<strong>{room.name}</strong>
<small>
{tf('{0} listeners · {1} queued', room.members.length, room.queueSize)}
</small>
</span>
<span className="room-state">
{selected ? t('JOINED') : room.isPaused ? t('PAUSED') : room.isPlaying ? t('LIVE') : t('IDLE')}
</span>
</button>
);
})}
</div>
)}
</div>
<div className="card room-console">
{!current ? (
<div className="room-console-empty">
<span className="room-console-glyph">04</span>
<h2>{t('Choose a room')}</h2>
<p>{t('Your TeamSpeak audio follows the room you join.')}</p>
</div>
) : (
<>
<div className="room-console-head">
<div>
<span className="rooms-kicker">{t('NOW TUNED')}</span>
<h2>{current.name}</h2>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={() => action('LeaveListeningRoom')} disabled={busy}>
{t('Leave')}
</button>
{current.isOwner && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (!(await confirmDialog({ title: t('Delete room'), message: tf('Delete “{0}” for everyone?', current.name), confirmLabel: t('Delete'), danger: true }))) return;
const result = await safeCall('DeleteListeningRoom', { room: current.name });
if (result) await refresh();
}}
>
<CloseIcon /> {t('Delete')}
</button>
)}
</div>
</div>
<div className="room-transport">
<button className="ctrl" title={t('Stop')} onClick={() => action('StopListeningRoom', current.name)}><span className="stop-square" /></button>
<button
className="ctrl ctrl-main"
title={current.isPlaying && !current.isPaused ? t('Pause') : t('Resume')}
onClick={() => action(current.isPlaying && !current.isPaused ? 'PauseListeningRoom' : 'ResumeListeningRoom', current.name)}
>
{current.isPlaying && !current.isPaused ? <PauseIcon /> : <PlayIcon />}
</button>
<button className="ctrl" title={t('Skip')} onClick={() => action('SkipListeningRoom', current.name)}><SkipNextIcon /></button>
<div className="room-transport-copy">
<strong>{current.isPlaying ? (current.isPaused ? t('Paused') : t('Streaming now')) : t('Ready')}</strong>
<small>{tf('{0} people are tuned in', current.members.length)}</small>
</div>
</div>
<form
className="room-play-form"
onSubmit={async (event) => {
event.preventDefault();
const value = query.trim();
if (!value) return;
const result = await safeCall<{ message?: string }>('PlayInListeningRoom', { room: current.name, query: value });
if (result) { setQuery(''); toast(result.message || t('Added to room queue')); await refresh(); }
}}
>
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t('Paste a URL or search for a track…')} />
<button className="btn btn-accent" disabled={!query.trim()}><PlusIcon /> {t('Add')}</button>
</form>
<div className="room-queue-head">
<h3>{t('Room queue')}</h3>
<div className="row-gap">
<span>{tf('{0} tracks', queue.length)}</span>
{!!queue.length && <button className="btn btn-danger-ghost" onClick={() => action('ClearListeningRoomQueue', current.name)}>{t('Clear')}</button>}
</div>
</div>
<div className="tracklist room-tracklist">
{queue.length ? queue.map((entry, index) => (
<TrackRow key={entry.queueId} track={entry.track} num={index + 1} playing={entry.isPlaying} actions={[
index > 0 && { icon: <ArrowUpIcon />, title: t('Move up'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index - 1 }); await refresh(); } },
index + 1 < queue.length && { icon: <ArrowDownIcon />, title: t('Move down'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index + 1 }); await refresh(); } },
{ icon: <CloseIcon />, title: t('Remove'), cls: 'danger', onClick: async () => { await safeCall('RemoveFromListeningRoomQueue', { room: current.name, queueId: entry.queueId }); await refresh(); } },
]} />
)) : <EmptyRow text={t('This room queue is empty')} />}
</div>
</>
)}
</div>
</div>
</section>
);
}
+140 -136
View File
@@ -4,25 +4,36 @@ import { useStore } from '../lib/store';
import { EmptyRow } from '../components/TrackRow'; import { EmptyRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow'; import { PersonRow } from '../components/PersonRow';
import { AnnounceModal } from '../components/AnnounceModal'; import { AnnounceModal } from '../components/AnnounceModal';
import { EmojiManager } from '../components/EmojiManager'; import { TeamSpeakAdmin } from '../components/TeamSpeakAdmin';
import type { AuditEntry, Subscriber } from '../lib/types'; import type { AuditEntry, Subscriber } from '../lib/types';
import { auditMethodName } from '../lib/auditMethods'; import { auditMethodName } from '../lib/auditMethods';
import { confirmDialog } from '../lib/dialog'; import { confirmDialog } from '../lib/dialog';
import { t, tf } from '../i18n'; import { t, tf } from '../i18n';
type AdminTab = 'teamspeak' | 'echoion' | 'subscribers' | 'emojis' | 'audit';
const TABS: Array<{ id: AdminTab; label: string }> = [
{ id: 'teamspeak', label: 'TeamSpeak' },
{ id: 'echoion', label: 'Echoion' },
{ id: 'subscribers', label: 'Subscribers' },
{ id: 'emojis', label: 'Emojis' },
{ id: 'audit', label: 'Audit history' },
];
export function ServerView() { export function ServerView() {
const s = useStore(appStore); const s = useStore(appStore);
const [tab, setTab] = useState<AdminTab>('teamspeak');
const [users, setUsers] = useState<Subscriber[]>([]); const [users, setUsers] = useState<Subscriber[]>([]);
const [audit, setAudit] = useState<AuditEntry[]>([]); const [audit, setAudit] = useState<AuditEntry[]>([]);
const [announceOpen, setAnnounceOpen] = useState(false); const [announceOpen, setAnnounceOpen] = useState(false);
const isAdmin = !!(s.identity && s.identity.isAdmin); const isAdmin = !!s.identity?.isAdmin;
const loadSubscribers = useCallback(async () => { const loadSubscribers = useCallback(async () => {
if (!isAdmin) return; if (!isAdmin) return;
const res = await safeCall<{ users?: Subscriber[] }>('ManageUsers', { const res = await safeCall<{ users?: Subscriber[] }>('ManageUsers', {
action: 'list', action: 'list',
}); });
const list = (res && res.users) || []; const list = res?.users || [];
setUsers(list); setUsers(list);
appStore.set({ listeners: list }); appStore.set({ listeners: list });
}, [isAdmin]); }, [isAdmin]);
@@ -30,186 +41,179 @@ export function ServerView() {
const loadAudit = useCallback(async () => { const loadAudit = useCallback(async () => {
if (!isAdmin) return; if (!isAdmin) return;
const res = await safeCall<{ entries?: AuditEntry[] }>('GetAuditLog'); const res = await safeCall<{ entries?: AuditEntry[] }>('GetAuditLog');
// Newest first — the server keeps a bounded ring in insertion order. setAudit((res?.entries || []).slice().reverse());
setAudit(((res && res.entries) || []).slice().reverse());
}, [isAdmin]); }, [isAdmin]);
useEffect(() => { useEffect(() => {
loadSubscribers(); if (tab === 'subscribers') void loadSubscribers();
loadAudit(); if (tab === 'audit') void loadAudit();
}, [loadSubscribers, loadAudit]); }, [tab, loadSubscribers, loadAudit]);
if (!isAdmin) {
return (
<section className="view" id="view-server">
<div className="card admin-guard">
<h2>{t('Administrator authentication required')}</h2>
<p className="muted">
{t('Sign in with an account in a configured TeamSpeak admin group.')}
</p>
</div>
</section>
);
}
return ( return (
<section className="view" id="view-server"> <section className="view" id="view-server">
<div className="card"> <div className="admin-tabs" role="tablist" aria-label={t('Administration')}>
<div className="card-head"> {TABS.map((item) => (
<h2> <button
{t('Subscribers')}{' '} key={item.id}
<span className="muted"> className={'admin-tab' + (tab === item.id ? ' active' : '')}
{users.length ? `· ${users.length}` : ''} role="tab"
</span> aria-selected={tab === item.id}
</h2> onClick={() => setTab(item.id)}
<div className="row-gap"> >
<button {t(item.label)}
className="btn btn-ghost" </button>
onClick={() => setAnnounceOpen(true)} ))}
> </div>
{tab === 'teamspeak' && <TeamSpeakAdmin />}
{tab === 'echoion' && (
<div className="card">
<div className="card-head">
<div>
<h2>{t('Echoion service')}</h2>
<p className="muted">{t('Bot messaging and runtime operations')}</p>
</div>
</div>
<div className="admin-action-grid">
<button className="btn btn-ghost" onClick={() => setAnnounceOpen(true)}>
{t('Announce…')} {t('Announce…')}
</button> </button>
<button <button
className="btn btn-ghost" className="btn btn-ghost"
onClick={async () => { onClick={async () => {
await safeCall('ReloadConfig'); if (await safeCall('ReloadConfig')) toast(t('Configuration reloaded'));
toast(t('Configuration reloaded'));
}} }}
> >
{t('Reload config')} {t('Reload config')}
</button> </button>
<button <button
className="btn btn-ghost" className="btn btn-ghost"
title={t(
'Stop and start the web server without touching the bot'
)}
onClick={async () => { onClick={async () => {
if ( if (
!(await confirmDialog({ !(await confirmDialog({
title: t('Restart web UI'), title: t('Restart web UI'),
message: t( message: t('Restart the web interface? Everyone disconnects briefly.'),
'Restart the web interface? Everyone disconnects briefly.'
),
confirmLabel: t('Restart'), confirmLabel: t('Restart'),
})) }))
) { ) return;
return; if (await safeCall('RestartWebInterface'))
} toast(t('Web interface restarting — this page will reconnect'));
const res = await safeCall(
'RestartWebInterface'
);
if (res) {
toast(
t(
'Web interface restarting — this page will reconnect'
)
);
}
}} }}
> >
{t('Restart web UI')} {t('Restart web UI')}
</button> </button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
!(await confirmDialog({
title: t('Unsub all'),
message: t(
'Remove ALL subscriptions? This cannot be undone.'
),
confirmLabel: t('Remove all'),
danger: true,
}))
) {
return;
}
await safeCall('ManageUsers', {
action: 'clearAll',
});
toast(t('All subscriptions removed'));
loadSubscribers();
}}
>
{t('Unsub all')}
</button>
</div> </div>
</div> </div>
<div className="people"> )}
{!users.length ? (
<EmptyRow text={t('No subscribers')} /> {tab === 'subscribers' && (
) : ( <div className="card">
users.map((u) => ( <div className="card-head">
<h2>{t('Subscribers')} <span className="muted">· {users.length}</span></h2>
<div className="row-gap">
<button className="btn btn-ghost" onClick={loadSubscribers}>{t('Refresh')}</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
!(await confirmDialog({
title: t('Unsub all'),
message: t('Remove ALL subscriptions? This cannot be undone.'),
confirmLabel: t('Remove all'),
danger: true,
}))
) return;
if (await safeCall('ManageUsers', { action: 'clearAll' })) {
toast(t('All subscriptions removed'));
void loadSubscribers();
}
}}
>
{t('Unsub all')}
</button>
</div>
</div>
<div className="people">
{users.length ? users.map((user) => (
<PersonRow <PersonRow
key={u.uid} key={user.uid}
name={u.nickname || u.uid} name={user.nickname || user.uid}
uid={u.uid} uid={user.uid}
sub={u.uid} sub={user.uid}
status={u.online ? t('Online') : t('Offline')} status={user.online ? t('Online') : t('Offline')}
statusColor={u.online ? '#5fe094' : '#6a6a78'} statusColor={user.online ? '#5fe094' : '#6a6a78'}
> >
<button <button
className="btn btn-danger-ghost" className="btn btn-danger-ghost"
onClick={async () => { onClick={async () => {
const who = u.nickname || u.uid; const who = user.nickname || user.uid;
if ( if (
!(await confirmDialog({ !(await confirmDialog({
title: t('Unsubscribe'), title: t('Unsubscribe'),
message: tf( message: tf('Unsubscribe {0}?', who),
'Unsubscribe {0}?',
who
),
confirmLabel: t('Unsub'), confirmLabel: t('Unsub'),
danger: true, danger: true,
})) }))
) { ) return;
return; if (await safeCall('ManageUsers', { action: 'remove', uid: user.uid }))
} void loadSubscribers();
await safeCall('ManageUsers', {
action: 'remove',
uid: u.uid,
});
toast(tf('Unsubscribed {0}', who));
loadSubscribers();
}} }}
> >
{t('Unsub')} {t('Unsub')}
</button> </button>
</PersonRow> </PersonRow>
)) )) : <EmptyRow text={t('No subscribers')} />}
)} </div>
</div> </div>
</div>
<div className="card">
<div className="card-head">
<h2>
{t('Audit log')}{' '}
<span className="muted">
{audit.length ? `· ${audit.length}` : ''}
</span>
</h2>
<button className="btn btn-ghost" onClick={loadAudit}>
{t('Refresh')}
</button>
</div>
{/* Cap the rendered rows; the header still shows the full count
and the container scrolls instead of growing endlessly. */}
<div className="tracklist audit-scroll">
{!audit.length ? (
<EmptyRow text={t('No audit entries yet')} />
) : (
audit.slice(0, 200).map((e, i) => (
<div
key={`${e.timestamp}-${i}`}
className="audit-row"
>
<span className="audit-method">
{auditMethodName(e.method)}
</span>
<span className="audit-client muted">
{tf('client #{0}', e.clientId)}
</span>
<span className="audit-time muted">
{new Date(
e.timestamp * 1000
).toLocaleString()}
</span>
</div>
))
)}
</div>
</div>
<EmojiManager />
{announceOpen && (
<AnnounceModal onClose={() => setAnnounceOpen(false)} />
)} )}
{tab === 'emojis' && (
<div className="card">
<h2>{t('Emojis')}</h2>
<p className="muted">
{t('Room emojis moved to VoidWatch and are managed from its administration page.')}
</p>
{s.watchUrl && (
<a className="btn btn-ghost" href={`${s.watchUrl.replace(/\/$/, '')}/admin.html`}>
{t('Open VoidWatch admin ↗')}
</a>
)}
</div>
)}
{tab === 'audit' && (
<div className="card">
<div className="card-head">
<h2>{t('Audit history')} <span className="muted">· {audit.length}</span></h2>
<button className="btn btn-ghost" onClick={loadAudit}>{t('Refresh')}</button>
</div>
<div className="tracklist audit-scroll">
{audit.length ? audit.slice(0, 200).map((entry, index) => (
<div key={`${entry.timestamp}-${index}`} className="audit-row">
<span className="audit-method">{auditMethodName(entry.method)}</span>
<span className="audit-client muted">{tf('client #{0}', entry.clientId)}</span>
<span className="audit-time muted">{new Date(entry.timestamp * 1000).toLocaleString()}</span>
</div>
)) : <EmptyRow text={t('No audit entries yet')} />}
</div>
</div>
)}
{announceOpen && <AnnounceModal onClose={() => setAnnounceOpen(false)} />}
</section> </section>
); );
} }
-789
View File
@@ -1,789 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { toast } from '../lib/app';
import { useStore } from '../lib/store';
import {
attachPlayerMount,
applyExtraControl,
applyLocalVolume,
currentPlayerPositionMs,
isHost,
joinRoom,
leaveRoom,
livePositionMs,
playerBufferedFraction,
refreshRooms,
seekRelative,
send,
setRate,
setSourceChoice,
transferHost,
unmuteAutoplay,
voteSkip,
watchStore,
} from '../lib/watch';
import { Avatar } from '../components/Avatar';
import { PlayerControls } from '../components/PlayerControls';
import { PlayerSettingsMenu } from '../components/PlayerSettingsMenu';
import { EmptyRow } from '../components/TrackRow';
import { WatchSearch } from '../components/WatchSearch';
import { EmojiPicker } from '../components/EmojiPicker';
import { renderChatText } from '../lib/emoji';
import { useControlsAutoHide } from '../lib/useControlsAutoHide';
import {
CloseIcon,
CrownIcon,
PlusIcon,
PowerIcon,
RefreshIcon,
SkipNextIcon,
VolumeMuteIcon,
WatchIcon,
} from '../components/icons';
import { t, tf } from '../i18n';
const REACTION_EMOJI = ['🔥', '😂', '👀', '❤️'];
export function WatchView() {
const w = useStore(watchStore);
const playerRef = useRef<HTMLDivElement>(null);
const playerShellRef = useRef<HTMLDivElement>(null);
const chatLogRef = useRef<HTMLDivElement>(null);
const [url, setUrl] = useState('');
const [chatText, setChatText] = useState('');
const [newRoom, setNewRoom] = useState('');
const [chatPicker, setChatPicker] = useState(false);
const [reactPicker, setReactPicker] = useState(false);
// Re-render every 500ms while mounted so the position readout ticks
// (mirrors the old renderPositions interval).
const [, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((n) => n + 1), 500);
return () => clearInterval(id);
}, []);
// Re-attach when entering/leaving a room: the player div unmounts in the
// lobby (w.room === null) and remounts on join, so the mount must follow it.
useEffect(() => {
attachPlayerMount(playerRef.current);
return () => attachPlayerMount(null);
}, [w.room]);
useEffect(() => {
const log = chatLogRef.current;
if (log) log.scrollTop = log.scrollHeight;
}, [w.chat.length]);
// "Live" = no position authority / no seek: Twitch, and generic embeds
// unless the embed answered the postMessage handshake (server-confirmed
// via the room's `controllable` flag).
const live =
w.source === 'twitch' ||
(w.source === 'iframe' && !w.embedControlled);
const hosting = isHost();
const canControl = w.authenticated && hosting;
const choice = w.sourceChoice;
const hasPlayer = !!(w.videoId || w.url);
const pos = livePositionMs();
// Idle-hide the overlay controls + cursor while a video plays (windowed
// and fullscreen). Called before the early return below to keep hook order.
const controlsHidden = useControlsAutoHide(playerShellRef, {
playing: !w.paused,
enabled: hasPlayer,
});
// Lobby: no room joined by default. Pick an existing room or create one.
if (w.room == null) {
return (
<WatchLobby
rooms={w.rooms}
newRoom={newRoom}
setNewRoom={setNewRoom}
onRefresh={refreshRooms}
/>
);
}
return (
<section className="view" id="view-watch">
<div className="watch-grid">
<div className="col">
<div className="card">
<div className="card-head">
<div className="row-gap">
<button
className={
'btn src-yt' +
(choice === 'youtube' ? ' active' : '')
}
onClick={() => setSourceChoice('youtube')}
>
YouTube
</button>
<button
className={
'btn src-tw' +
(choice === 'twitch' ? ' active' : '')
}
onClick={() => setSourceChoice('twitch')}
>
Twitch
</button>
<button
className={
'btn src-direct' +
(choice === 'direct' ? ' active' : '')
}
onClick={() => setSourceChoice('direct')}
>
{t('Video URL')}
</button>
<button
className={
'btn src-iframe' +
(choice === 'iframe' ? ' active' : '')
}
onClick={() => setSourceChoice('iframe')}
>
{t('Embed')}
</button>
</div>
<div className="row-gap">
<span className="pill pill-room" title={t('Room')}>
<WatchIcon /> {w.room}
</span>
<span
className={
'pill' + (hosting ? ' pill-yellow' : '')
}
>
{!w.authenticated
? t('Guest — sign in to control')
: hosting
? t('You are hosting')
: t('Viewer')}
</span>
<span className="pill pill-green">
{t('Synced')}
</span>
{w.source === 'iframe' && hasPlayer && (
<span
className={
'pill' +
(w.embedControlled
? ' pill-green'
: '')
}
>
{w.embedControlled
? w.embedProtocol
? `${t('Embed synced')} · ${w.embedProtocol}`
: t('Embed synced')
: t('Embed is view-only')}
</span>
)}
<button
className="btn btn-leave"
title={t('Leave this room')}
onClick={() => leaveRoom()}
>
<PowerIcon /> {t('Leave room')}
</button>
</div>
</div>
<form
className="search-row"
onSubmit={(e) => {
e.preventDefault();
const input = url.trim();
if (!input) return;
if (choice === 'twitch') {
send({
type: 'watch.load',
source: 'twitch',
channel: input,
url: input,
});
} else {
send({
type: 'watch.load',
source: choice,
url: input,
});
}
}}
>
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder={
choice === 'twitch'
? t(
'Twitch channel or URL to watch together'
)
: choice === 'direct'
? t(
'Direct video or .m3u8 URL to watch together'
)
: choice === 'iframe'
? t(
'Embed URL (Kodik, etc.) to watch together'
)
: t(
'YouTube URL to watch together'
)
}
autoComplete="off"
disabled={!w.authenticated}
/>
<button className="btn btn-accent" type="submit">
{t('Load')}
</button>
<button
className="btn btn-ghost"
type="button"
title={t('Add to the watch queue')}
disabled={!w.authenticated}
onClick={async () => {
const input = url.trim();
if (!input) return;
const source = w.sourceChoice;
let title = '';
if (source === 'youtube') {
// Best-effort title so the queue shows
// names instead of URLs.
try {
const res = await fetch(
`https://www.youtube.com/oembed?url=${encodeURIComponent(input)}&format=json`
);
if (res.ok) {
title =
(await res.json()).title ||
'';
}
} catch {
/* offline or blocked */
}
}
send({
type: 'watch.queue.add',
source,
url: input,
title,
});
setUrl('');
}}
>
{t('+ Queue')}
</button>
</form>
{/* The shell (player + custom bar) is what goes
fullscreen, so the controls stay available; the bar
overlays the video and idle-hides during playback. */}
<div
className={
'player-shell' +
(w.source === 'youtube' ? ' youtube-native' : '') +
(controlsHidden ? ' controls-hidden' : '')
}
ref={playerShellRef}
>
<div className="player-box">
<div ref={playerRef} id="watchPlayer" />
{w.playerEmpty && (
<div className="player-empty">
{t(w.playerEmpty)}
</div>
)}
{w.mutedAutoplay && (
<button
className="btn btn-accent unmute-btn"
title={t('Tap to unmute')}
onClick={() => unmuteAutoplay()}
>
<VolumeMuteIcon /> {t('Tap to unmute')}
</button>
)}
<div className="reaction-layer">
{w.reactions.map((r) => (
<span
key={r.id}
className="reaction-fly reaction-fly-abs"
style={{
left: `${10 + ((r.id * 37) % 80)}%`,
}}
>
{/^:[a-z0-9_]+:$/.test(r.emoji) ? (
<img
className="emoji-img-lg"
src={`/emoji/${r.emoji.slice(1, -1)}`}
alt={r.emoji}
/>
) : (
r.emoji
)}
</span>
))}
</div>
</div>
<div className="player-overlay">
<PlayerControls
playing={!w.paused}
positionMs={pos}
durationMs={w.durationMs}
live={live}
canControl={canControl}
bufferedPct={playerBufferedFraction() * 100}
volumePct={w.localVolume}
volumeLive
onTogglePlay={() =>
send({
type: w.paused
? 'watch.play'
: 'watch.pause',
positionMs: currentPlayerPositionMs(),
})
}
onSeekMs={(ms) =>
send({
type: 'watch.seek',
positionMs: ms,
})
}
onSeekBy={seekRelative}
onVolume={(pct) => applyLocalVolume(pct)}
onSkip={() =>
send({ type: 'watch.queue.next' })
}
skipDisabled={!w.queue.length}
settings={
<PlayerSettingsMenu
extras={w.extraControls}
rate={w.rate}
rateOptions={
w.source === 'youtube' ||
w.extraControls.some((c) => c.id === 'speed')
? [0.5, 0.75, 1, 1.25, 1.5, 2]
: undefined
}
canControl={canControl}
onExtra={applyExtraControl}
onRate={setRate}
/>
}
onFullscreen={() => {
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
playerShellRef.current
?.requestFullscreen()
.catch(() =>
toast(
t('Fullscreen unavailable')
)
);
}
}}
showLocal={hasPlayer}
extra={
<button
className="btn btn-ghost"
onClick={() => {
send({ type: 'watch.state' });
toast(t('Resynced to room'));
}}
>
{t('Resync')}
</button>
}
/>
</div>
</div>
<div className="reactions">
{REACTION_EMOJI.map((emoji) => (
<button
key={emoji}
className="reaction"
onClick={() =>
send({ type: 'watch.reaction', emoji })
}
>
{emoji}
</button>
))}
<div className="emoji-anchor">
<button
className="reaction"
onClick={() => setReactPicker((o) => !o)}
>
<PlusIcon />
</button>
{reactPicker && (
<EmojiPicker
onClose={() => setReactPicker(false)}
onPick={(token) => {
send({
type: 'watch.reaction',
emoji: token,
});
setReactPicker(false);
}}
/>
)}
</div>
</div>
</div>
<div className="card">
<div className="card-head">
<h3>
{t('Up Next')}{' '}
<span className="muted">
{w.queue.length
? `· ${w.queue.length}`
: ''}
</span>
</h3>
<div className="row-gap">
{hasPlayer && (
<button
className={
'btn btn-ghost voteskip' +
(w.skipVoted ? ' on' : '')
}
onClick={voteSkip}
>
{w.skipVotes > 0
? tf(
'Vote skip {0}/{1}',
w.skipVotes,
w.skipNeeded
)
: t('Vote skip')}
</button>
)}
<button
className="btn btn-ghost"
title={t('Host only')}
disabled={!canControl || !w.queue.length}
onClick={() =>
send({ type: 'watch.queue.next' })
}
>
{t('Play next')} <SkipNextIcon />
</button>
</div>
</div>
<WatchSearch disabled={!w.authenticated} />
<div className="tracklist">
{!w.queue.length ? (
<EmptyRow
text={t(
'Nothing queued — paste a URL and hit “+ Queue”'
)}
/>
) : (
w.queue.map((item, i) => (
<div key={i} className="track-row">
<span className="track-num">
{String(i + 1).padStart(2, '0')}
</span>
<div
className="track-cover"
style={
item.thumbnailUrl
? {
background: `url("${item.thumbnailUrl}") center/cover`,
}
: undefined
}
/>
<div className="track-main">
<div className="track-title">
{item.title ||
item.url ||
item.videoId}
</div>
<div className="track-sub">
{[
item.source === 'twitch'
? 'Twitch'
: 'YouTube',
item.addedBy
? tf(
'added by {0}',
item.addedBy
)
: '',
]
.filter(Boolean)
.join(' · ')}
</div>
</div>
{w.authenticated && (
<div className="track-actions">
<button
className="icon-btn danger"
title={t(
'Remove from queue'
)}
onClick={() =>
send({
type: 'watch.queue.remove',
index: i,
})
}
>
<CloseIcon />
</button>
</div>
)}
</div>
))
)}
</div>
</div>
</div>
<div className="col">
<div className="card">
<div className="card-head">
<h3>
{t('In the room')}{' '}
<span className="muted">
· {w.participantCount}
</span>
</h3>
</div>
<div className="people">
{w.participants.map((p) => {
let status = '—';
let color = '#6a6a78';
if (p.buffering) {
status = t('Buffering…');
color = '#ffcf4a';
} else if (
p.offsetMs != null &&
p.offsetMs !== -1
) {
const off = Math.round(p.offsetMs);
status =
Math.abs(off) < 200
? t('In sync')
: `${off > 0 ? '+' : ''}${off}ms`;
color =
Math.abs(off) < 200
? '#5fe094'
: Math.abs(off) > 800
? '#ff9090'
: '#8a8a98';
}
return (
<div key={p.id} className="person">
<Avatar name={p.name} uid={p.uid} />
<div className="person-main">
<div className="person-name">
{p.name}
{p.id === w.selfId
? ` ${t('(you)')}`
: ''}
</div>
{p.host && (
<div className="person-sub">
{t('Host')}
</div>
)}
</div>
{hosting &&
p.id !== w.selfId &&
!p.host && (
<button
className="icon-btn"
title={t('Make host')}
onClick={() =>
transferHost(p.id)
}
>
<CrownIcon />
</button>
)}
<span
className="person-status"
style={{ color }}
>
{status}
</span>
</div>
);
})}
</div>
</div>
<div className="card chat-card">
<div className="card-head">
<h3>{t('Room chat')}</h3>
</div>
<div className="chat-log" ref={chatLogRef}>
{w.chat.map((m, i) => (
<div key={i} className="chat-msg">
<Avatar name={m.name} size={26} />
<div className="chat-body">
<span className="chat-name">
{m.name}
</span>
<span className="chat-time">
{new Date(
m.at
).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})}
</span>
<div className="chat-text">
{renderChatText(m.text).map(
(part, j) =>
typeof part ===
'string' ? (
<span key={j}>
{part}
</span>
) : (
<img
key={j}
className="emoji-img"
src={`/emoji/${part.emojiName}`}
alt={`:${part.emojiName}:`}
/>
)
)}
</div>
</div>
</div>
))}
</div>
<form
className="chat-row"
onSubmit={(e) => {
e.preventDefault();
const text = chatText.trim();
if (!text) return;
send({ type: 'watch.chat', text });
setChatText('');
}}
>
<div className="emoji-anchor">
<button
type="button"
className="btn btn-ghost emoji-trigger"
onClick={() => setChatPicker((o) => !o)}
>
😊
</button>
{chatPicker && (
<EmojiPicker
onClose={() => setChatPicker(false)}
onPick={(token) => {
setChatText(
(prev) =>
prev +
(token.startsWith(':')
? token
: token)
);
setChatPicker(false);
}}
/>
)}
</div>
<input
value={chatText}
onChange={(e) => setChatText(e.target.value)}
placeholder={t('Say something…')}
autoComplete="off"
maxLength={500}
/>
<button className="btn btn-accent" type="submit">
{t('Send')}
</button>
</form>
</div>
</div>
</div>
</section>
);
}
// The lobby shown when no room is joined (the default). Lists active rooms and
// lets the user join one or create a new room by name.
function WatchLobby(props: {
rooms: ReturnType<typeof watchStore.get>['rooms'];
newRoom: string;
setNewRoom: (v: string) => void;
onRefresh: () => void;
}) {
const { rooms, newRoom, setNewRoom, onRefresh } = props;
useEffect(() => {
onRefresh();
}, [onRefresh]);
return (
<section className="view" id="view-watch">
<div className="card watch-lobby">
<div className="card-head">
<h3>{t('Watch together')}</h3>
<button
className="pill"
title={t('Refresh rooms')}
onClick={() => onRefresh()}
>
<RefreshIcon /> {t('Refresh')}
</button>
</div>
<p className="muted">
{t('Join a room to watch in sync, or create your own.')}
</p>
<div className="rooms-list">
{rooms.length === 0 && (
<span className="muted">
{t('No active rooms yet — create one below.')}
</span>
)}
{rooms.map((r) => (
<button
key={r.name}
className="room-chip"
onClick={() => joinRoom(r.name)}
title={r.nowTitle || undefined}
>
<WatchIcon /> {r.name}
<span className="muted">
{' '}
· {tf('{0} watching', r.participants)}
</span>
{r.nowTitle && (
<span className="room-now muted">
{' '}
· {r.nowTitle}
</span>
)}
</button>
))}
</div>
<form
className="rooms-create"
onSubmit={(e) => {
e.preventDefault();
if (!newRoom.trim()) return;
joinRoom(newRoom);
setNewRoom('');
}}
>
<input
value={newRoom}
onChange={(e) => setNewRoom(e.target.value)}
placeholder={t('New room name…')}
maxLength={48}
/>
<button className="btn btn-accent" type="submit">
{t('Create / join')}
</button>
</form>
</div>
</section>
);
}
+1 -1
View File
@@ -17,9 +17,9 @@ export default defineConfig({
server: { server: {
proxy: { proxy: {
'/config.json': 'http://127.0.0.1:8080', '/config.json': 'http://127.0.0.1:8080',
'/api': 'http://127.0.0.1:8080',
'/avatar': 'http://127.0.0.1:8080', '/avatar': 'http://127.0.0.1:8080',
'/rpc': { target: 'ws://127.0.0.1:8080', ws: true }, '/rpc': { target: 'ws://127.0.0.1:8080', ws: true },
'/ws': { target: 'ws://127.0.0.1:8080', ws: true },
}, },
cors: true cors: true
}, },
+27 -49
View File
@@ -1,12 +1,9 @@
#pragma once #pragma once
#include "echoion/web/WatchSession.hpp"
#include <Void/Async/ThreadPool.hpp> #include <Void/Async/ThreadPool.hpp>
#include <boost/asio.hpp> #include <boost/asio.hpp>
#include <boost/beast.hpp> #include <boost/beast.hpp>
#include <boost/beast/http.hpp> #include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <atomic> #include <atomic>
#include <cstdint> #include <cstdint>
@@ -14,7 +11,6 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <stop_token>
#include <string> #include <string>
#include <thread> #include <thread>
#include <unordered_map> #include <unordered_map>
@@ -24,12 +20,10 @@ namespace Echoion::Web
namespace asio = boost::asio; namespace asio = boost::asio;
namespace beast = boost::beast; namespace beast = boost::beast;
namespace http = beast::http; namespace http = beast::http;
namespace websocket = beast::websocket;
// Serves the static browser UI over HTTP, hosts the independent // Serves the static browser UI over HTTP and tunnels GET /rpc upgrades to
// sync-watch WebSocket at GET /ws, and tunnels GET /rpc upgrades to the // the local RPC server so only the web port ever needs to be exposed. It
// local RPC server so only the web port ever needs to be exposed. It has // has no handle on the music bot itself.
// no handle on the music bot itself.
class HttpServer class HttpServer
{ {
public: public:
@@ -41,6 +35,10 @@ namespace Echoion::Web
// Explicit RPC URL served to the browser; when empty the UI // Explicit RPC URL served to the browser; when empty the UI
// derives ws://<page-host>:<rpcPort>. // derives ws://<page-host>:<rpcPort>.
std::string rpcUrl; std::string rpcUrl;
// External VoidWatch deployment used by the temporary
// /watch redirect and exposed to the browser in
// /config.json.
std::string watchUrl;
uint16_t rpcPort = 8765; uint16_t rpcPort = 8765;
// Server-wide switch for the Now Playing video preview, // Server-wide switch for the Now Playing video preview,
// surfaced to the browser via /config.json. // surfaced to the browser via /config.json.
@@ -54,19 +52,10 @@ namespace Echoion::Web
void stop(); void stop();
[[nodiscard]] bool isRunning() const { return running_; } [[nodiscard]] bool isRunning() const { return running_; }
// Token → identity lookup for the watch feature; installed by
// Core, which owns the credential store. May be set before or
// after start() and survives stop()/start() cycles.
void setIdentityResolver(
WatchSessionManager::IdentityResolver resolver)
{
watch_.setIdentityResolver(std::move(resolver));
}
// A user's avatar image, served at GET /avatar/<uid>. Installed // A user's avatar image, served at GET /avatar/<uid>. Installed
// by Core (which owns the TeamSpeak plugin handle); best-effort — // by Core (which owns the TeamSpeak plugin handle); best-effort —
// nullopt yields a 404 and the UI falls back to initials. Same // nullopt yields a 404 and the UI falls back to initials. It may be
// lifetime rules as the identity resolver. // installed before or after start() and survives restarts.
struct AvatarImage { struct AvatarImage {
std::string contentType; std::string contentType;
std::string bytes; std::string bytes;
@@ -79,15 +68,15 @@ namespace Echoion::Web
avatarProvider_ = std::move(provider); avatarProvider_ = std::move(provider);
} }
// A custom emoji image, served at GET /emoji/<name>. Same shape struct DashboardSnapshot {
// and lifetime rules as the avatar provider; installed by Core std::string body;
// (which owns the emoji database). std::string etag;
using EmojiProvider = std::function<std::optional<AvatarImage>( };
const std::string& name)>; using DashboardProvider = std::function<DashboardSnapshot()>;
void setEmojiProvider(EmojiProvider provider) void setDashboardProvider(DashboardProvider provider)
{ {
std::lock_guard<std::mutex> lock(avatarProviderMutex_); std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
emojiProvider_ = std::move(provider); dashboardProvider_ = std::move(provider);
} }
private: private:
@@ -95,9 +84,8 @@ namespace Echoion::Web
void acceptLoop(); void acceptLoop();
void doAccept(); void doAccept();
void onAccept(asio::ip::tcp::socket socket); void onAccept(asio::ip::tcp::socket socket);
void handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket); void
void handleWatch( handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
// Tunnel a browser WebSocket upgrade at /rpc to the local RPC // Tunnel a browser WebSocket upgrade at /rpc to the local RPC
// server as raw TCP: the original upgrade request is replayed // server as raw TCP: the original upgrade request is replayed
// upstream and bytes are pumped in both directions, so the real // upstream and bytes are pumped in both directions, so the real
@@ -109,10 +97,6 @@ namespace Echoion::Web
// kept open for the next request (HTTP keep-alive). // kept open for the next request (HTTP keep-alive).
bool serveHttp(asio::ip::tcp::socket& socket, bool serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req); const http::request<http::string_body>& req);
bool serveWatchProxy(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req);
void sendToWatcher(uint64_t connId, const std::string& json);
void syncLoop(std::stop_token stopToken);
Config config_; Config config_;
asio::io_context ioContext_; asio::io_context ioContext_;
@@ -125,29 +109,23 @@ namespace Echoion::Web
static constexpr std::size_t POOL_SIZE = 32; static constexpr std::size_t POOL_SIZE = 32;
std::unique_ptr<Void::Concurrency::ThreadPool> pool_; std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
std::unordered_map<
uint64_t,
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
watchers_;
std::mutex watchersMutex_;
std::atomic<uint64_t> nextConnId_{1}; std::atomic<uint64_t> nextConnId_{1};
// Live /rpc bridges (browser, upstream); shut down on stop() so // Live /rpc bridges (browser, upstream); shut down on stop() so
// the blocking pump loops unblock and the pool can join. // the blocking pump loops unblock and the pool can join.
std::unordered_map<uint64_t, std::unordered_map<
std::pair<std::shared_ptr<asio::ip::tcp::socket>, uint64_t,
std::shared_ptr<asio::ip::tcp::socket>>> std::pair<std::shared_ptr<asio::ip::tcp::socket>,
std::shared_ptr<asio::ip::tcp::socket>>>
bridges_; bridges_;
std::mutex bridgesMutex_; std::mutex bridgesMutex_;
WatchSessionManager watch_; // Called from pool threads; guarded so Core can (re)install it at
std::jthread syncThread_; // any time.
// Called from pool threads; guarded so Core can (re)install them
// at any time. Both share one mutex (installed together at start).
AvatarProvider avatarProvider_; AvatarProvider avatarProvider_;
EmojiProvider emojiProvider_;
std::mutex avatarProviderMutex_; std::mutex avatarProviderMutex_;
DashboardProvider dashboardProvider_;
std::mutex dashboardProviderMutex_;
}; };
} // namespace Echoion::Web } // namespace Echoion::Web
-200
View File
@@ -1,200 +0,0 @@
#pragma once
#include <chrono>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <unordered_map>
namespace Echoion::Web
{
// Authoritative state for synchronized video watching. This is entirely
// independent of the music bot's playback pipeline: browsers play the video
// locally and the server is only the timing authority for each room.
//
// The manager owns room state and participant membership. It never writes to
// sockets directly -- HttpServer installs a `sender` callback and the manager
// asks it to deliver JSON text to individual connections. That keeps all
// Boost.Beast/socket concerns in HttpServer and makes this unit trivially
// testable.
//
// Roles: the first *authenticated* participant to join a room is its host;
// only the host may load/play/pause/seek and advance the queue, and every
// control message additionally requires authentication (guests can watch,
// chat and react but never manipulate). The host role migrates to another
// authenticated participant when the host leaves. Twitch rooms are live:
// there is no position authority, seek is refused, and everyone simply
// embeds the same channel.
//
// Rooms with a loaded video survive everyone leaving: playback is paused
// in place and the next authenticated joiner becomes host, so a page
// refresh does not wipe the session. Abandoned rooms are pruned after
// kEmptyRoomTtl.
class WatchSessionManager
{
public:
// Delivers one JSON text frame to a single connection id.
using Sender = std::function<void(uint64_t connId,
const std::string& json)>;
// Authenticated identity behind an RPC token. The resolver is
// installed by Core (it owns the token database); the manager
// itself never sees credentials storage.
struct Identity {
std::string uid;
std::string nickname;
bool isAdmin = false;
};
using IdentityResolver =
std::function<std::optional<Identity>(const std::string& token)>;
// Best-effort title lookup for a queued video, so the watch queue
// shows real names server-side instead of relying on the browser.
// Installed by Core (which owns the YouTube metadata stack); when
// unset or it returns nullopt, the client-supplied title (or the
// Twitch channel name) is used. Called on the message thread, so
// it must be quick / cached.
using MetadataResolver = std::function<std::optional<std::string>(
const std::string& source, const std::string& videoId,
const std::string& url)>;
void setSender(Sender sender) { sender_ = std::move(sender); }
void setIdentityResolver(IdentityResolver resolver)
{
identityResolver_ = std::move(resolver);
}
void setMetadataResolver(MetadataResolver resolver)
{
metadataResolver_ = std::move(resolver);
}
// A watch WebSocket connected / disconnected. onDisconnect removes
// the connection from whatever room it had joined and notifies the
// remaining participants.
void onConnect(uint64_t connId);
void onDisconnect(uint64_t connId);
// Handle one inbound JSON message from a connection. Unknown or
// malformed messages are ignored.
void onMessage(uint64_t connId, const std::string& json);
// Broadcast a periodic sync heartbeat (position + participants) to
// every room. HttpServer drives this on a timer so drifting
// clients can re-align.
void broadcastSync();
private:
struct Participant {
std::string name;
// TeamSpeak unique id when authenticated (empty for guests),
// so the web UI can fetch the persisted avatar at /avatar.
std::string uid;
// Set when the join/rename carried a valid RPC token;
// required for any control message and for hosting.
bool authenticated = false;
// Last client-reported playback position and the room
// authority position at that moment (for drift display).
long long reportedMs = -1;
long long authorityMs = -1;
bool buffering = false;
};
struct ChatMessage {
std::string name;
std::string text;
long long timestampMs = 0;
};
// One queued-up video waiting to be watched after the current one.
struct QueueEntry {
std::string source; // youtube|twitch|direct|iframe
std::string url;
std::string videoId;
std::string title; // resolved server-side, best effort
std::string thumbnailUrl; // derived from source + id
std::string addedBy;
};
struct Room {
std::string source = "youtube"; // youtube|twitch|direct|iframe
std::string url;
std::string videoId; // YouTube id / Twitch channel; empty
// for direct & iframe (url carries it)
// Host-reported (watch.embed.caps): the iframe embed answered
// a postMessage handshake, so the room has real position
// authority (seek allowed, position freezes when emptied).
// Reset on every load until the host re-handshakes.
bool controllable = false;
bool paused = true;
// Host-selected playback rate (YouTube only); 1.0 = normal.
double rate = 1.0;
// Host-selected provider media settings. Local-only settings
// (volume, quality, subtitles) never enter room state.
std::map<std::string, std::string> embedControls;
// Position (ms) captured at `anchor`. While playing, the
// live position is positionMs + (now - anchor).
long long positionMs = 0;
std::chrono::steady_clock::time_point anchor{
std::chrono::steady_clock::now()};
uint64_t host = 0;
std::map<uint64_t, Participant> participants;
std::deque<ChatMessage> chat; // last kChatBacklog kept
std::deque<QueueEntry> queue; // up-next, kQueueMax cap
// Connection ids that voted to skip the current video;
// cleared whenever the video changes or a voter leaves.
std::set<uint64_t> skipVotes;
// When the room last had participants; drives pruning of
// empty-but-persisted rooms.
std::chrono::steady_clock::time_point lastActive{
std::chrono::steady_clock::now()};
};
static constexpr size_t kChatBacklog = 50;
static constexpr size_t kQueueMax = 100;
static constexpr size_t kEmbedControlsMax = 16;
static constexpr std::chrono::hours kEmptyRoomTtl{24};
[[nodiscard]] long long livePosition(const Room& room) const;
void send(uint64_t connId, const std::string& json) const;
void broadcast(const Room& room, const std::string& json) const;
void sendParticipants(const Room& room) const;
void sendSnapshot(uint64_t connId, const Room& room) const;
void sendDenied(uint64_t connId, const std::string& reason) const;
void sendQueue(const Room& room, uint64_t onlyTo = 0) const;
// Broadcast the vote-skip tally (votes / needed) for the room.
void sendSkipState(const Room& room) const;
// Votes needed to skip in a room: majority of participants.
[[nodiscard]] static std::size_t skipThreshold(const Room& room);
// Reply to watch.rooms.list with the lobby of active rooms.
void sendRoomsList(uint64_t connId) const;
// Deterministic thumbnail URL for a queued/loaded video.
[[nodiscard]] static std::string
thumbnailFor(const std::string& source,
const std::string& videoId);
// Point the room at a new video (shared by watch.load and
// queue advancement) and broadcast watch.loaded.
void loadIntoRoom(Room& room, const std::string& source,
const std::string& url,
const std::string& channel, uint64_t byConnId);
// First authenticated participant, or 0 when only guests remain.
[[nodiscard]] static uint64_t pickHost(const Room& room);
void leaveCurrentRoom(uint64_t connId);
mutable std::mutex mutex_;
std::unordered_map<std::string, Room> rooms_;
// connId -> room name it currently belongs to.
std::unordered_map<uint64_t, std::string> connRoom_;
Sender sender_;
IdentityResolver identityResolver_;
MetadataResolver metadataResolver_;
};
} // namespace Echoion::Web
+44 -348
View File
@@ -2,10 +2,9 @@
#include <Void/Data/Json.hpp> #include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
#include <Void/Net/Http.hpp> #include <boost/beast/websocket.hpp>
#include <array> #include <array>
#include <cctype>
#include <chrono> #include <chrono>
#include <filesystem> #include <filesystem>
#include <format> #include <format>
@@ -15,6 +14,8 @@
namespace Echoion::Web namespace Echoion::Web
{ {
namespace websocket = beast::websocket;
namespace namespace
{ {
std::string_view contentType(const std::filesystem::path& path) std::string_view contentType(const std::filesystem::path& path)
@@ -91,105 +92,6 @@ namespace Echoion::Web
return out; return out;
} }
struct ProxyUrl {
std::string url;
std::string scheme;
std::string host;
};
std::optional<ProxyUrl> parseProxyUrl(std::string url)
{
const auto schemeEnd = url.find("://");
if (schemeEnd == std::string::npos) {
return std::nullopt;
}
const std::string scheme = url.substr(0, schemeEnd);
if (scheme != "https" && scheme != "http") {
return std::nullopt;
}
const auto authorityStart = schemeEnd + 3;
const auto authorityEnd = url.find_first_of("/?#", authorityStart);
std::string authority =
url.substr(authorityStart, authorityEnd == std::string::npos
? std::string::npos
: authorityEnd - authorityStart);
if (authority.empty() || authority.find('@') != std::string::npos) {
return std::nullopt;
}
if (const auto colon = authority.rfind(':');
colon != std::string::npos) {
authority.resize(colon);
}
for (char& c : authority) {
c = static_cast<char>(std::tolower(c));
}
const auto domain = [&](std::string_view base) {
return authority == base ||
(authority.size() > base.size() &&
authority.ends_with(base) &&
authority[authority.size() - base.size() - 1] == '.');
};
const bool allowed =
domain("kodik.info") || domain("kodik.cc") ||
domain("kodik.biz") || domain("kodik.online") ||
domain("kodikplayer.com") || domain("alloha.tv") ||
domain("alloha.video") || domain("alloha.online") ||
domain("allarknow.online");
if (!allowed) {
return std::nullopt;
}
return ProxyUrl{std::move(url), scheme, std::move(authority)};
}
bool isPrivateAddress(const asio::ip::address& address)
{
if (address.is_loopback() || address.is_unspecified() ||
address.is_multicast()) {
return true;
}
if (address.is_v4()) {
const auto bytes = address.to_v4().to_bytes();
return bytes[0] == 10 || bytes[0] == 127 ||
(bytes[0] == 169 && bytes[1] == 254) ||
(bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) ||
(bytes[0] == 192 && bytes[1] == 168) || bytes[0] == 0;
}
const auto bytes = address.to_v6().to_bytes();
return (bytes[0] & 0xfe) == 0xfc ||
(bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80);
}
void absolutizeRootReferences(std::string& html,
std::string_view origin)
{
// Kodik uses root-relative URLs both in tag attributes and inline
// JavaScript. A <base> element cannot affect fetch("/...") and was
// observed to be ignored for already-tokenized tags, so rewrite
// every quoted single-slash reference before returning the
// document.
for (std::size_t i = 0; i + 2 < html.size(); ++i) {
if ((html[i] != '\'' && html[i] != '"') || html[i + 1] != '/' ||
html[i + 2] == '/') {
continue;
}
html.insert(i + 1, origin);
i += origin.size();
}
}
constexpr std::string_view kPlayerBridge =
R"JS(<script data-echoion-bridge>
(()=>{if(window.__echoionBridge)return;window.__echoionBridge=1;
const send=(event,answer)=>parent.postMessage({event,answer},'*');
const label=e=>(e.getAttribute('aria-label')||e.name||e.id||e.closest('label')?.textContent||'').toLowerCase();
const kind=e=>{const s=label(e);if(/quality|качест/.test(s))return'qualities';if(/audio|voice|озвуч|перевод/.test(s))return'audiotracks';if(/subtitle|субтит/.test(s))return'subtitles';if(/episode|сер/.test(s))return'episodes';return''};
const scan=()=>document.querySelectorAll('select').forEach(e=>{const k=kind(e);if(!k)return;send(k,[...e.options].map((o,i)=>({value:o.value||String(i),label:o.textContent||o.value})));if(!e.dataset.echoionBound){e.dataset.echoionBound='1';e.addEventListener('change',()=>send(k.replace(/ies$/,'y').replace(/s$/,''),e.value))}});
const video=()=>document.querySelector('video');
addEventListener('message',e=>{const m=e.data||{};if(!m.api)return;const v=video();if(m.api==='play')v?.play();else if(m.api==='pause')v?.pause();else if(m.api==='seek'&&v)v.currentTime=Number(m.set)||0;else if(m.api==='volume'&&v)v.volume=Math.max(0,Math.min(1,Number(m.set)));else if(m.api==='speed'&&v)v.playbackRate=Number(m.set)||1;else{document.querySelectorAll('select').forEach(s=>{const k=kind(s);const id=k==='qualities'?'quality':k==='audiotracks'?'audiotrack':k==='subtitles'?'subtitle':k==='episodes'?'episode':'';if(id===m.api){s.value=String(m.set);s.dispatchEvent(new Event('change',{bubbles:true}))}})}});
const bind=()=>{const v=video();if(!v||v.dataset.echoionBound)return;v.dataset.echoionBound='1';v.addEventListener('play',()=>send('play'));v.addEventListener('pause',()=>send('pause'));v.addEventListener('ended',()=>send('ended'));v.addEventListener('timeupdate',()=>send('time',v.currentTime));send('duration',v.duration)};
new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subtree:true,childList:true});setInterval(()=>{bind();scan()},1500);send('ready');})();
</script>)JS";
// One direction of a raw TCP tunnel. On any error both sockets are // One direction of a raw TCP tunnel. On any error both sockets are
// shut down so the opposite pump unblocks too. // shut down so the opposite pump unblocks too.
void pumpBytes(boost::asio::ip::tcp::socket& from, void pumpBytes(boost::asio::ip::tcp::socket& from,
@@ -237,13 +139,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
pool_ = std::make_unique<Void::Concurrency::ThreadPool>(POOL_SIZE); pool_ = std::make_unique<Void::Concurrency::ThreadPool>(POOL_SIZE);
watch_.setSender([this](uint64_t connId, const std::string& json) {
sendToWatcher(connId, json);
});
serverThread_ = std::thread(&HttpServer::acceptLoop, this); serverThread_ = std::thread(&HttpServer::acceptLoop, this);
syncThread_ =
std::jthread([this](std::stop_token st) { syncLoop(st); });
// A wrong webRoot only surfaces as bare 404s in the browser — // A wrong webRoot only surfaces as bare 404s in the browser —
// call it out at startup instead. // call it out at startup instead.
@@ -285,23 +181,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
} }
ioContext_.stop(); ioContext_.stop();
// Stop the heartbeat first so it can't write to sockets we close.
syncThread_ = std::jthread{};
{
std::lock_guard<std::mutex> lock(watchersMutex_);
for (auto& [id, ws] : watchers_) {
// Leave rooms properly so they pause/persist instead of
// keeping ghost participants across a stop()/start().
watch_.onDisconnect(id);
if (ws->is_open()) {
beast::error_code ec;
ws->close(websocket::close_code::normal, ec);
}
}
watchers_.clear();
}
// Unblock every /rpc bridge pump so the pool workers can return. // Unblock every /rpc bridge pump so the pool workers can return.
{ {
std::lock_guard<std::mutex> lock(bridgesMutex_); std::lock_guard<std::mutex> lock(bridgesMutex_);
@@ -405,22 +284,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
if (websocket::is_upgrade(req)) { if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") { if (req.target() == "/rpc") {
bridgeRpc(socket, req, buffer); bridgeRpc(socket, req, buffer);
return;
} }
if (req.target() != "/ws") {
return; // /ws (watch) and /rpc (bridge) only
}
auto ws =
std::make_shared<websocket::stream<asio::ip::tcp::socket>>(
std::move(*socket));
ws->accept(req, ec);
if (ec) {
Void::Log::debug("HttpServer", "{}",
std::format("Watch handshake failed: {}",
ec.message()));
return;
}
handleWatch(ws);
return; return;
} }
@@ -508,35 +372,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
std::format("RPC bridge {} closed", connId)); std::format("RPC bridge {} closed", connId));
} }
void HttpServer::handleWatch(
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws)
{
const uint64_t connId = nextConnId_++;
{
std::lock_guard<std::mutex> lock(watchersMutex_);
watchers_[connId] = ws;
}
watch_.onConnect(connId);
beast::flat_buffer buffer;
while (running_.load() && ws->is_open()) {
beast::error_code ec;
ws->read(buffer, ec);
if (ec == websocket::error::closed || ec) {
break;
}
std::string message = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
watch_.onMessage(connId, message);
}
watch_.onDisconnect(connId);
{
std::lock_guard<std::mutex> lock(watchersMutex_);
watchers_.erase(connId);
}
}
bool HttpServer::serveHttp(asio::ip::tcp::socket& socket, bool HttpServer::serveHttp(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req) const http::request<http::string_body>& req)
{ {
@@ -545,7 +380,9 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
auto respond = [&](http::status status, std::string_view type, auto respond = [&](http::status status, std::string_view type,
std::string body, std::string_view cacheControl = {}, std::string body, std::string_view cacheControl = {},
std::string_view lastModified = {}) { std::string_view lastModified = {},
std::string_view etag = {},
std::string_view location = {}) {
http::response<http::string_body> res{status, req.version()}; http::response<http::string_body> res{status, req.version()};
res.set(http::field::server, "Echoion"); res.set(http::field::server, "Echoion");
res.set(http::field::content_type, type); res.set(http::field::content_type, type);
@@ -555,6 +392,12 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
if (!lastModified.empty()) { if (!lastModified.empty()) {
res.set(http::field::last_modified, lastModified); res.set(http::field::last_modified, lastModified);
} }
if (!etag.empty()) {
res.set(http::field::etag, etag);
}
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive()); res.keep_alive(req.keep_alive());
// HEAD advertises the real Content-Length but carries no body. // HEAD advertises the real Content-Length but carries no body.
res.content_length( res.content_length(
@@ -589,10 +432,42 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
{{"rpcUrl", Value{rpcUrl}}, {{"rpcUrl", Value{rpcUrl}},
{"rpcPort", {"rpcPort",
Value{static_cast<long long>(config_.rpcPort)}}, Value{static_cast<long long>(config_.rpcPort)}},
{"watchUrl", Value{config_.watchUrl}},
{"nowPlayingVideo", Value{config_.nowPlayingVideo}}}))); {"nowPlayingVideo", Value{config_.nowPlayingVideo}}})));
return !ec && req.keep_alive(); return !ec && req.keep_alive();
} }
if (target == "/api/public/dashboard") {
DashboardProvider provider;
{
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
provider = dashboardProvider_;
}
if (!provider) {
respond(http::status::service_unavailable, "application/json",
R"({"error":"Dashboard snapshot unavailable"})",
"no-cache");
return !ec && req.keep_alive();
}
auto snapshot = provider();
if (auto current = req.find(http::field::if_none_match);
current != req.end() && current->value() == snapshot.etag) {
respond(http::status::not_modified, "application/json", "",
"no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
respond(http::status::ok, "application/json",
std::move(snapshot.body), "no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
if ((target == "/watch" || target == "/watch/") &&
!config_.watchUrl.empty()) {
respond(http::status::temporary_redirect, "text/plain", "",
"no-store", {}, {}, config_.watchUrl);
return !ec && req.keep_alive();
}
// User avatar images, resolved through Core's provider (TeamSpeak // User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its // avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap // initial-letter avatars; short private caching keeps reloads cheap
@@ -630,28 +505,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
return !ec && req.keep_alive(); return !ec && req.keep_alive();
} }
// Custom emoji images, resolved through Core's provider (emoji DB).
constexpr std::string_view kEmojiPrefix = "/emoji/";
if (target.starts_with(kEmojiPrefix)) {
const std::string name =
urlDecode(target.substr(kEmojiPrefix.size()));
EmojiProvider provider;
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
provider = emojiProvider_;
}
if (!name.empty() && provider) {
if (auto image = provider(name)) {
respond(http::status::ok, image->contentType,
std::move(image->bytes), "public, max-age=86400");
return !ec && req.keep_alive();
}
}
respond(http::status::not_found, "text/plain", "Not Found",
"private, max-age=60");
return !ec && req.keep_alive();
}
if (target.empty() || target == "/") { if (target.empty() || target == "/") {
target = "/index.html"; target = "/index.html";
} }
@@ -699,161 +552,4 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
return !ec && req.keep_alive(); return !ec && req.keep_alive();
} }
bool
HttpServer::serveWatchProxy(asio::ip::tcp::socket& socket,
const http::request<http::string_body>& req)
{
beast::error_code ec;
auto fail = [&](http::status status, std::string body) {
http::response<http::string_body> res{status, req.version()};
res.set(http::field::server, "Echoion");
res.set(http::field::content_type, "text/plain; charset=utf-8");
res.set(http::field::cache_control, "no-store");
res.keep_alive(req.keep_alive());
res.body() = std::move(body);
res.prepare_payload();
http::write(socket, res, ec);
return !ec && req.keep_alive();
};
if (req.method() != http::verb::get &&
req.method() != http::verb::head) {
return fail(http::status::method_not_allowed, "Method Not Allowed");
}
const std::string target(req.target());
const auto marker = target.find("url=");
if (marker == std::string::npos) {
return fail(http::status::bad_request, "Missing upstream URL");
}
std::string encoded = target.substr(marker + 4);
if (const auto amp = encoded.find('&'); amp != std::string::npos) {
encoded.resize(amp);
}
auto upstream = parseProxyUrl(urlDecode(encoded));
if (!upstream) {
return fail(http::status::forbidden, "Provider is not allowlisted");
}
// Resolve and inspect every address before connecting. Redirects are
// not followed; the browser must request the validated destination
// anew.
asio::io_context resolverContext;
asio::ip::tcp::resolver resolver(resolverContext);
boost::system::error_code resolveEc;
const auto endpoints = resolver.resolve(
upstream->host, upstream->scheme == "https" ? "443" : "80",
resolveEc);
if (resolveEc || endpoints.empty()) {
return fail(http::status::bad_gateway, "Provider lookup failed");
}
for (const auto& endpoint : endpoints) {
if (isPrivateAddress(endpoint.endpoint().address())) {
return fail(http::status::forbidden, "Private upstream denied");
}
}
Void::Net::HttpClient client;
client.set_verify_tls(true);
client.set_max_redirects(0);
client.set_max_body_size(32ull * 1024 * 1024);
Void::Net::Request upstreamReq;
upstreamReq.method = req.method() == http::verb::head
? Void::Net::Method::Head
: Void::Net::Method::Get;
upstreamReq.url = upstream->url;
upstreamReq.timeout = std::chrono::seconds{15};
if (const auto range = req.find(http::field::range);
range != req.end()) {
upstreamReq.headers.push_back(
{"Range", std::string(range->value())});
}
upstreamReq.headers.push_back({"Access-Control-Allow-Origin", "*"});
auto fetched = client.send(upstreamReq);
if (!fetched) {
return fail(http::status::bad_gateway, "Provider request failed");
}
if (fetched->status >= 300 && fetched->status < 400) {
return fail(http::status::bad_gateway,
"Provider redirect requires allowlist validation");
}
std::string body = std::move(fetched->body);
std::string contentType = fetched->header("Content-Type")
.transform([](std::string_view value) {
return std::string(value);
})
.value_or("application/octet-stream");
if (contentType.starts_with("text/html")) {
const std::string origin =
std::format("{}://{}", upstream->scheme, upstream->host);
absolutizeRootReferences(body, origin);
const std::string base =
std::format("<base href=\"{}\">", upstream->url);
// The base must precede provider CSS/JS tags. Appending it at
// </head> is too late: the HTML parser has already resolved
// /assets/* against Echoion, producing 404s and leaving the player
// unstyled/unbooted.
if (const auto openHead = body.find("<head");
openHead != std::string::npos) {
const auto end = body.find('>', openHead);
body.insert(end == std::string::npos ? openHead : end + 1,
base);
} else {
body.insert(0, base);
}
const auto closeHead = body.find("</head>");
body.insert(closeHead == std::string::npos ? 0 : closeHead,
std::string(kPlayerBridge));
}
http::response<http::string_body> res{
static_cast<http::status>(fetched->status), req.version()};
res.set(http::field::server, "Echoion");
res.set(http::field::content_type, contentType);
res.set(http::field::cache_control, "no-store");
res.set("X-Content-Type-Options", "nosniff");
for (const auto name : {"Accept-Ranges", "Content-Range"}) {
if (auto value = fetched->header(name)) {
res.set(name, *value);
}
}
res.keep_alive(req.keep_alive());
const auto bodySize = body.size();
if (req.method() != http::verb::head) {
res.body() = std::move(body);
}
res.content_length(bodySize);
http::write(socket, res, ec);
return !ec && req.keep_alive();
}
void HttpServer::sendToWatcher(uint64_t connId, const std::string& json)
{
std::lock_guard<std::mutex> lock(watchersMutex_);
auto it = watchers_.find(connId);
if (it == watchers_.end() || !it->second->is_open()) {
return;
}
beast::error_code ec;
it->second->text(true);
it->second->write(asio::buffer(json), ec);
}
void HttpServer::syncLoop(std::stop_token stopToken)
{
using namespace std::chrono_literals;
while (!stopToken.stop_requested() && running_.load()) {
// Sleep in short slices so stop() is prompt.
for (int i = 0;
i < 30 && !stopToken.stop_requested() && running_.load();
++i) {
std::this_thread::sleep_for(100ms);
}
if (stopToken.stop_requested() || !running_.load()) {
break;
}
watch_.broadcastSync();
}
}
} // namespace Echoion::Web } // namespace Echoion::Web
-849
View File
@@ -1,849 +0,0 @@
#include "echoion/web/WatchSession.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <format>
#include <string_view>
namespace Echoion::Web
{
namespace
{
using Void::Json::Value;
long long nowMillis()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
// Extract the YouTube video id from common URL shapes so clients that
// use the iframe player get a bare id. Falls back to the whole string.
std::string videoIdFromUrl(const std::string& url)
{
auto pick = [&](std::string_view marker) -> std::string {
auto pos = url.find(marker);
if (pos == std::string::npos) {
return {};
}
pos += marker.size();
auto end = url.find_first_of("&?#", pos);
return url.substr(pos, end == std::string::npos
? std::string::npos
: end - pos);
};
if (auto id = pick("v="); !id.empty()) {
return id;
}
if (auto id = pick("youtu.be/"); !id.empty()) {
return id;
}
if (auto id = pick("/embed/"); !id.empty()) {
return id;
}
return url;
}
// Twitch channel from a URL or a bare channel name.
std::string twitchChannelFrom(const std::string& input)
{
auto pos = input.find("twitch.tv/");
std::string channel =
pos == std::string::npos
? input
: input.substr(pos + std::string_view("twitch.tv/").size());
if (auto end = channel.find_first_of("/&?#");
end != std::string::npos) {
channel = channel.substr(0, end);
}
return channel;
}
// Canonicalize a client-supplied source to one of the known kinds,
// defaulting anything unrecognized to "youtube".
std::string canonicalSource(const std::string& s)
{
if (s == "twitch" || s == "direct" || s == "iframe") {
return s;
}
return "youtube";
}
// Live sources have no position authority and refuse seeks: Twitch
// streams, and generic embeds (Kodik & co.) unless the host's client
// reported the embed as controllable (watch.embed.caps).
bool isLiveSource(const std::string& s, bool controllable)
{
return s == "twitch" || (s == "iframe" && !controllable);
}
Value embedControlsValue(
const std::map<std::string, std::string>& controls)
{
Value::Object_t object;
for (const auto& [id, value] : controls) {
object.emplace_back(id, Value{value});
}
return Value{std::move(object)};
}
} // namespace
long long WatchSessionManager::livePosition(const Room& room) const
{
if (room.paused) {
return room.positionMs;
}
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - room.anchor)
.count();
return room.positionMs + elapsed;
}
void WatchSessionManager::send(uint64_t connId, const std::string& json) const
{
if (sender_) {
sender_(connId, json);
}
}
void WatchSessionManager::broadcast(const Room& room,
const std::string& json) const
{
for (const auto& [id, participant] : room.participants) {
send(id, json);
}
}
void WatchSessionManager::sendDenied(uint64_t connId,
const std::string& reason) const
{
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.denied"}},
{"reason", Value{reason}}})));
}
void WatchSessionManager::sendParticipants(const Room& room) const
{
Value::Array_t list;
list.reserve(room.participants.size());
for (const auto& [id, p] : room.participants) {
// Drift vs the authority at the time of the client's last report;
// -1 while nothing has been reported yet.
long long offsetMs = -1;
if (p.reportedMs >= 0 && p.authorityMs >= 0) {
offsetMs = p.reportedMs - p.authorityMs;
}
list.emplace_back(Void::Json::object(
{{"id", Value{static_cast<long long>(id)}},
{"name", Value{p.name}},
{"uid", Value{p.uid}},
{"host", Value{id == room.host}},
{"offsetMs", Value{offsetMs}},
{"buffering", Value{p.buffering}}}));
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.participants"}},
{"count", Value{static_cast<long long>(room.participants.size())}},
{"host", Value{static_cast<long long>(room.host)}},
{"participants", Value{std::move(list)}}}));
broadcast(room, msg);
}
void WatchSessionManager::sendQueue(const Room& room, uint64_t onlyTo) const
{
Value::Array_t items;
items.reserve(room.queue.size());
for (const auto& e : room.queue) {
items.emplace_back(Void::Json::object(
{{"source", Value{e.source}},
{"url", Value{e.url}},
{"videoId", Value{e.videoId}},
{"title", Value{e.title}},
{"thumbnailUrl", Value{e.thumbnailUrl}},
{"addedBy", Value{e.addedBy}}}));
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.queue"}},
{"items", Value{std::move(items)}}}));
if (onlyTo != 0) {
send(onlyTo, msg);
} else {
broadcast(room, msg);
}
}
std::string WatchSessionManager::thumbnailFor(const std::string& source,
const std::string& videoId)
{
if (videoId.empty()) {
return {};
}
// Direct/iframe sources carry no deterministic thumbnail.
if (source == "direct" || source == "iframe") {
return {};
}
if (source == "twitch") {
// Twitch's live-preview CDN (undocumented but stable); shows a
// placeholder when the channel is offline.
return std::format(
"https://static-cdn.jtvnw.net/previews-ttv/live_user_{}"
"-320x180.jpg",
videoId);
}
return std::format("https://i.ytimg.com/vi/{}/mqdefault.jpg", videoId);
}
std::size_t WatchSessionManager::skipThreshold(const Room& room)
{
// Majority of current participants (ceil(n/2)); at least one.
const std::size_t n = room.participants.size();
return n == 0 ? 1 : (n / 2) + 1;
}
void WatchSessionManager::sendSkipState(const Room& room) const
{
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.skip.updated"}},
{"votes",
Value{static_cast<long long>(room.skipVotes.size())}},
{"needed",
Value{static_cast<long long>(skipThreshold(room))}}}));
broadcast(room, msg);
}
void WatchSessionManager::sendRoomsList(uint64_t connId) const
{
Value::Array_t list;
for (const auto& [name, room] : rooms_) {
list.emplace_back(Void::Json::object(
{{"name", Value{name}},
{"participants",
Value{static_cast<long long>(room.participants.size())}},
{"source", Value{room.source}},
{"videoId", Value{room.videoId}},
{"nowTitle", Value{room.url}},
{"hasHost", Value{room.host != 0}}}));
}
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.rooms"}},
{"rooms", Value{std::move(list)}}})));
}
uint64_t WatchSessionManager::pickHost(const Room& room)
{
for (const auto& [id, p] : room.participants) {
if (p.authenticated) {
return id;
}
}
return 0;
}
void WatchSessionManager::loadIntoRoom(Room& room, const std::string& source,
const std::string& url,
const std::string& channel,
uint64_t byConnId)
{
room.url = url;
const std::string src = canonicalSource(source);
if (src == "twitch") {
room.source = "twitch";
room.videoId = !channel.empty() ? twitchChannelFrom(channel)
: twitchChannelFrom(url);
room.paused = false; // live — always "playing"
} else if (src == "direct" || src == "iframe") {
// The URL carries the whole media/embed; there is no video id.
// `direct` (HTML5 <video>) is seekable; `iframe` (generic embed)
// is live-like (no position authority).
room.source = src;
room.videoId.clear();
room.paused = false;
} else {
room.source = "youtube";
room.videoId = videoIdFromUrl(url);
// Auto-play on load: the room starts playing immediately rather
// than waiting for someone to press play (the client handles the
// browser autoplay policy by starting muted when needed).
room.paused = false;
}
room.positionMs = 0;
room.anchor = std::chrono::steady_clock::now();
// A new video resets any in-flight skip vote, and any embed capability
// until the host's client re-handshakes with the new embed.
room.skipVotes.clear();
room.controllable = false;
room.embedControls.clear();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"by", Value{static_cast<long long>(byConnId)}}}));
broadcast(room, msg);
sendSkipState(room);
}
void WatchSessionManager::sendSnapshot(uint64_t connId, const Room& room) const
{
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.sync"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"paused", Value{room.paused}},
{"rate", Value{room.rate}},
{"embedControls", embedControlsValue(room.embedControls)},
{"positionMs", Value{livePosition(room)}},
{"serverTimeMs", Value{nowMillis()}},
{"host", Value{static_cast<long long>(room.host)}}}));
send(connId, msg);
}
void WatchSessionManager::onConnect(uint64_t connId)
{
Void::Log::debug("WatchSession", "{}",
std::format("watch connection {} opened", connId));
}
void WatchSessionManager::leaveCurrentRoom(uint64_t connId)
{
auto it = connRoom_.find(connId);
if (it == connRoom_.end()) {
return;
}
auto roomIt = rooms_.find(it->second);
connRoom_.erase(it);
if (roomIt == rooms_.end()) {
return;
}
Room& room = roomIt->second;
room.participants.erase(connId);
room.skipVotes.erase(connId);
if (room.participants.empty()) {
// A room with nothing loaded (no video id and no url) is discarded.
if (room.videoId.empty() && room.url.empty()) {
rooms_.erase(roomIt);
return;
}
// Persist the session: freeze playback where it was so the next
// joiner (who becomes host) resumes in place. Live sources
// (Twitch / generic embeds) have no position to freeze.
room.positionMs = livePosition(room);
if (!isLiveSource(room.source, room.controllable)) {
room.paused = true;
}
room.anchor = std::chrono::steady_clock::now();
room.host = 0;
room.lastActive = std::chrono::steady_clock::now();
return;
}
// Host migration: hand the room to the longest-standing authenticated
// participant; guests never host (host stays vacant until an
// authenticated user joins or signs in).
if (room.host == connId) {
room.host = pickHost(room);
}
sendParticipants(room);
// A departure changes the majority threshold and may complete a
// pending skip; re-broadcast the tally so clients stay accurate.
if (!room.videoId.empty() || !room.url.empty()) {
if (!room.skipVotes.empty() &&
room.skipVotes.size() >= skipThreshold(room)) {
room.skipVotes.clear();
if (!room.queue.empty()) {
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId, 0);
sendQueue(room);
}
} else {
sendSkipState(room);
}
}
}
void WatchSessionManager::onDisconnect(uint64_t connId)
{
std::lock_guard<std::mutex> lock(mutex_);
leaveCurrentRoom(connId);
}
void WatchSessionManager::onMessage(uint64_t connId, const std::string& json)
{
auto parsed = Void::Json::parse(json);
if (!parsed || !parsed->is_object()) {
return;
}
const std::string type = parsed->get_str("type");
if (type.empty()) {
return;
}
std::lock_guard<std::mutex> lock(mutex_);
// A valid RPC token upgrades the participant: server-trusted nickname
// and the right to control playback / host the room.
std::optional<Identity> identity;
if (const std::string token = parsed->get_str("token");
!token.empty() && identityResolver_) {
identity = identityResolver_(token);
}
if (type == "watch.join") {
const std::string roomName = parsed->get_str("room", "main");
std::string name = identity ? identity->nickname
: parsed->get_str("name");
if (name.empty()) {
name = std::format("guest-{}", connId);
}
leaveCurrentRoom(connId);
connRoom_[connId] = roomName;
Room& room = rooms_[roomName];
room.participants[connId] =
Participant{.name = name,
.uid = identity ? identity->uid : std::string{},
.authenticated = identity.has_value()};
if (room.host == 0 && identity) {
room.host = connId;
}
// Ack with the caller's own id so the client can recognize
// itself in participant lists and host announcements.
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.joined"}},
{"selfId", Value{static_cast<long long>(connId)}},
{"authenticated", Value{identity.has_value()}},
{"room", Value{roomName}}})));
sendSnapshot(connId, room);
sendQueue(room, connId);
// Replay the recent chat backlog to the newcomer only.
for (const auto& msg : room.chat) {
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.chat"}},
{"name", Value{msg.name}},
{"text", Value{msg.text}},
{"timestampMs", Value{msg.timestampMs}}})));
}
sendParticipants(room);
sendSkipState(room);
return;
}
// Lobby query: list active rooms. Valid without having joined one.
if (type == "watch.rooms.list") {
sendRoomsList(connId);
return;
}
// Leave the current room and return to the lobby without joining
// another one. leaveCurrentRoom migrates/vacates host and prunes an
// empty room; we then ack and refresh the caller's lobby list.
if (type == "watch.leave") {
leaveCurrentRoom(connId);
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.left"}}})));
sendRoomsList(connId);
return;
}
// All remaining messages act on the caller's current room.
auto roomNameIt = connRoom_.find(connId);
if (roomNameIt == connRoom_.end()) {
return;
}
auto roomIt = rooms_.find(roomNameIt->second);
if (roomIt == rooms_.end()) {
return;
}
Room& room = roomIt->second;
auto selfIt = room.participants.find(connId);
if (selfIt == room.participants.end()) {
return;
}
// Manipulation requires an authenticated participant; playback and
// queue advancement additionally require the host role. Guests only
// watch, chat and react.
const bool isHost = (connId == room.host);
const bool isControl =
(type == "watch.load" || type == "watch.play" ||
type == "watch.pause" || type == "watch.seek" ||
type == "watch.rate" || type == "watch.queue.add" ||
type == "watch.queue.remove" || type == "watch.queue.next" ||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
type == "watch.embed.control");
const bool needsHost =
(type == "watch.load" || type == "watch.play" ||
type == "watch.pause" || type == "watch.seek" ||
type == "watch.rate" || type == "watch.queue.next" ||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
type == "watch.embed.control");
if (isControl && !selfIt->second.authenticated) {
sendDenied(connId, "Sign in to control playback");
return;
}
if (needsHost && !isHost) {
sendDenied(connId, "Only the host controls playback");
return;
}
if (type == "watch.load") {
loadIntoRoom(room, parsed->get_str("source", "youtube"),
parsed->get_str("url"), parsed->get_str("channel"),
connId);
sendSnapshot(connId, room);
} else if (type == "watch.queue.add") {
if (room.queue.size() >= kQueueMax) {
sendDenied(connId, "Watch queue is full");
return;
}
const std::string url = parsed->get_str("url");
if (url.empty()) {
return;
}
QueueEntry entry;
entry.source = canonicalSource(parsed->get_str("source", "youtube"));
entry.url = url;
if (entry.source == "twitch") {
entry.videoId = twitchChannelFrom(url);
} else if (entry.source == "youtube") {
entry.videoId = videoIdFromUrl(url);
} else {
entry.videoId.clear(); // direct/iframe carry the whole url
}
entry.thumbnailUrl = thumbnailFor(entry.source, entry.videoId);
// Title: server-side resolver first (real YouTube titles), then
// the client's best-effort title, then a sensible default (the
// Twitch channel name / the bare video id / the url).
if (metadataResolver_) {
if (auto resolved = metadataResolver_(
entry.source, entry.videoId, entry.url)) {
entry.title = *resolved;
}
}
if (entry.title.empty()) {
entry.title = parsed->get_str("title");
}
if (entry.title.empty()) {
entry.title =
entry.videoId.empty() ? entry.url : entry.videoId;
}
if (entry.title.size() > 200) {
entry.title.resize(200);
}
entry.addedBy = selfIt->second.name;
// Nothing playing yet: start this item immediately instead of
// parking it in the queue.
if (room.videoId.empty() && room.url.empty()) {
loadIntoRoom(room, entry.source, entry.url, entry.videoId,
connId);
return;
}
room.queue.push_back(std::move(entry));
sendQueue(room);
} else if (type == "watch.queue.remove") {
const auto index =
static_cast<long long>(parsed->get_num("index", -1));
if (index < 0 ||
index >= static_cast<long long>(room.queue.size())) {
return;
}
room.queue.erase(room.queue.begin() + index);
sendQueue(room);
} else if (type == "watch.queue.next") {
if (room.queue.empty()) {
// End of playback with nothing queued: clear the current video
// so every client shows the empty placeholder. (The manual
// "Play next" button is disabled when the queue is empty, so
// this is reached only by the auto-advance-on-end path.)
room.videoId.clear();
room.url.clear();
room.paused = true;
room.controllable = false;
room.embedControls.clear();
room.skipVotes.clear();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{std::string{}}},
{"videoId", Value{std::string{}}},
{"controllable", Value{false}},
{"by", Value{static_cast<long long>(connId)}}}));
broadcast(room, msg);
sendSkipState(room);
return;
}
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId, connId);
sendQueue(room);
sendSnapshot(connId, room);
} else if (type == "watch.play") {
room.positionMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: livePosition(room);
room.paused = false;
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.play"}},
{"positionMs", Value{room.positionMs}},
{"serverTimeMs", Value{nowMillis()}}}));
broadcast(room, msg);
} else if (type == "watch.pause") {
room.positionMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: livePosition(room);
room.paused = true;
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.pause"}},
{"positionMs", Value{room.positionMs}}}));
broadcast(room, msg);
} else if (type == "watch.seek") {
if (isLiveSource(room.source, room.controllable)) {
sendDenied(connId, "Live stream — cannot seek");
return;
}
room.positionMs = static_cast<long long>(
parsed->get_num("positionMs"));
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.seek"}},
{"positionMs", Value{room.positionMs}},
{"serverTimeMs", Value{nowMillis()}}}));
broadcast(room, msg);
} else if (type == "watch.rate") {
// Host sets the shared playback rate (YouTube only). Clamp to the
// values the YouTube player accepts.
double rate = parsed->get_num("rate", 1.0);
if (rate < 0.25) {
rate = 0.25;
}
if (rate > 2.0) {
rate = 2.0;
}
room.rate = rate;
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.rate"}}, {"rate", Value{room.rate}}}));
broadcast(room, msg);
} else if (type == "watch.embed.control") {
if (room.source != "iframe") {
return;
}
const std::string id = parsed->get_str("id");
const std::string value = parsed->get_str("value");
if (id.empty() || id.size() > 32 || value.size() > 200 ||
id.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_") !=
std::string::npos) {
return;
}
const bool syncedControl =
id == "audiotrack" || id == "episode" || id == "playlist" ||
id == "playlist-next" || id == "playlist-prev" ||
id == "translation";
if (!syncedControl) {
return;
}
if (!room.embedControls.contains(id) &&
room.embedControls.size() >= kEmbedControlsMax) {
return;
}
room.embedControls[id] = value;
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.embed.control"}},
{"id", Value{id}},
{"value", Value{value}}}));
broadcast(room, msg);
} else if (type == "watch.embed.caps") {
// Host's client reports whether the loaded iframe embed answered
// the postMessage handshake; flips the room between view-only
// live and fully seekable. Meaningless for other sources.
if (room.source != "iframe") {
return;
}
const bool controllable = parsed->get_bool("controllable", false);
if (room.controllable == controllable) {
return;
}
room.controllable = controllable;
// Snapshot everyone immediately so timelines flip without waiting
// for the 3s heartbeat.
for (const auto& [pid, p] : room.participants) {
sendSnapshot(pid, room);
}
} else if (type == "watch.state") {
sendSnapshot(connId, room);
} else if (type == "watch.host.transfer") {
// Host hands control to another authenticated participant.
const auto targetId =
static_cast<uint64_t>(parsed->get_num("targetId", 0));
auto targetIt = room.participants.find(targetId);
if (targetIt == room.participants.end()) {
sendDenied(connId, "That viewer is no longer here");
return;
}
if (!targetIt->second.authenticated) {
sendDenied(connId, "Only signed-in viewers can host");
return;
}
room.host = targetId;
sendParticipants(room);
} else if (type == "watch.skip.vote") {
// Any participant may vote to skip the current video; a majority
// advances the queue (or clears the video when the queue is
// empty). Toggling removes the vote.
if (room.videoId.empty() && room.url.empty()) {
return;
}
if (room.skipVotes.count(connId)) {
room.skipVotes.erase(connId);
} else {
room.skipVotes.insert(connId);
}
if (room.skipVotes.size() >= skipThreshold(room)) {
room.skipVotes.clear();
if (!room.queue.empty()) {
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId,
connId);
sendQueue(room);
} else {
// Nothing queued: clear the current video.
room.videoId.clear();
room.url.clear();
room.paused = true;
const std::string msg =
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{std::string{}}},
{"videoId", Value{std::string{}}},
{"by", Value{static_cast<long long>(connId)}}}));
broadcast(room, msg);
sendSkipState(room);
}
} else {
sendSkipState(room);
}
} else if (type == "watch.rename") {
// In-place rename (e.g. the user authenticated after joining);
// keeps chat history. A valid token upgrades the participant to
// authenticated and lets them claim a vacant host slot.
std::string name = identity ? identity->nickname
: parsed->get_str("name");
if (name.empty() || name.size() > 64) {
return;
}
selfIt->second.name = name;
if (identity) {
selfIt->second.authenticated = true;
selfIt->second.uid = identity->uid;
if (room.host == 0) {
room.host = connId;
}
}
// Re-ack so the client sees its (possibly upgraded) standing.
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.joined"}},
{"selfId", Value{static_cast<long long>(connId)}},
{"authenticated",
Value{selfIt->second.authenticated}},
{"room", Value{roomNameIt->second}}})));
sendParticipants(room);
} else if (type == "watch.report") {
// Client progress report (drift display; no authority change).
auto pIt = room.participants.find(connId);
if (pIt == room.participants.end()) {
return;
}
pIt->second.reportedMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: -1;
pIt->second.authorityMs = livePosition(room);
pIt->second.buffering = parsed->get_bool("buffering", false);
} else if (type == "watch.chat") {
const std::string text = parsed->get_str("text");
if (text.empty() || text.size() > 500) {
return;
}
auto pIt = room.participants.find(connId);
const std::string name = pIt != room.participants.end()
? pIt->second.name
: std::format("guest-{}", connId);
room.chat.push_back(ChatMessage{
.name = name, .text = text, .timestampMs = nowMillis()});
while (room.chat.size() > kChatBacklog) {
room.chat.pop_front();
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.chat"}},
{"name", Value{name}},
{"text", Value{text}},
{"timestampMs", Value{room.chat.back().timestampMs}}}));
broadcast(room, msg);
} else if (type == "watch.reaction") {
// Unicode emoji (a few bytes) or a :custom-emoji: shortcode.
const std::string emoji = parsed->get_str("emoji");
if (emoji.empty() || emoji.size() > 48) {
return;
}
auto pIt = room.participants.find(connId);
const std::string name = pIt != room.participants.end()
? pIt->second.name
: std::format("guest-{}", connId);
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.reaction"}},
{"name", Value{name}},
{"emoji", Value{emoji}}}));
broadcast(room, msg);
}
}
void WatchSessionManager::broadcastSync()
{
std::lock_guard<std::mutex> lock(mutex_);
// Prune persisted-but-abandoned rooms that nobody rejoined.
const auto now = std::chrono::steady_clock::now();
for (auto it = rooms_.begin(); it != rooms_.end();) {
if (it->second.participants.empty() &&
now - it->second.lastActive > kEmptyRoomTtl) {
it = rooms_.erase(it);
} else {
++it;
}
}
for (const auto& [name, room] : rooms_) {
if (room.participants.empty()) {
continue;
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.sync"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"paused", Value{room.paused}},
{"rate", Value{room.rate}},
{"embedControls", embedControlsValue(room.embedControls)},
{"positionMs", Value{livePosition(room)}},
{"serverTimeMs", Value{nowMillis()}},
{"host", Value{static_cast<long long>(room.host)}}}));
broadcast(room, msg);
// Participants ride the same 3s heartbeat so drift/buffering
// badges stay fresh without per-report broadcasts.
sendParticipants(room);
}
}
} // namespace Echoion::Web