making WEB

Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-11 00:47:52 +03:00
commit 9574aa8a23
87 files changed
+14884

No files matched your search

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