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

+115
View File
@@ -0,0 +1,115 @@
cmake_minimum_required(VERSION 4.0.0)
project(EchoionWeb VERSION 1.0.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
file(GLOB_RECURSE WEB_SOURCES CONFIGURE_DEPENDS "src/**.cpp")
add_library(EchoionWeb STATIC ${WEB_SOURCES})
add_library(Echoion::Web ALIAS EchoionWeb)
target_include_directories(EchoionWeb PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
# EchoionCore is configured before this module and creates the header-only
# Boost:: targets from the single system Boost. Fall back to discovering them
# only if this module is ever built without Core.
if(NOT TARGET Boost::beast)
find_package(Boost 1.87 CONFIG QUIET)
foreach(_hdr asio beast system)
if(NOT TARGET Boost::${_hdr})
add_library(_web_boost_${_hdr}_hdr INTERFACE)
add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr)
target_include_directories(_web_boost_${_hdr}_hdr INTERFACE
"${Boost_INCLUDE_DIRS}")
endif()
endforeach()
endif()
find_package(Threads REQUIRED)
target_link_libraries(EchoionWeb
PUBLIC
Echoion::ApiConfig
Void::Data
Void::Log
Void::Async
Void::Net
PRIVATE
Threads::Threads
Boost::beast
Boost::asio
Boost::system
)
if(MSVC)
target_compile_options(EchoionWeb PRIVATE /W4 /WX-)
else()
target_compile_options(EchoionWeb PRIVATE -Wall -Wextra -Wpedantic)
endif()
# ── Browser frontend (Vite + React + TypeScript) ─────────────────────────────
# The UI lives in frontend/ and is built with npm/vite into frontend/web-dist.
# 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
# -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)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist")
if(ECHOION_BUILD_WEB)
find_program(NPM_EXECUTABLE NAMES npm npm.cmd)
if(NOT NPM_EXECUTABLE)
message(FATAL_ERROR
"npm was not found but ECHOION_BUILD_WEB is ON. Install Node.js/npm, "
"or configure with -DECHOION_BUILD_WEB=OFF to skip the web frontend.")
endif()
# Rebuild web-dist whenever any source/config under frontend/ (excluding
# node_modules and the output dir) changes. CONFIGURE_DEPENDS re-globs at
# build time so new files are picked up without re-running CMake.
file(GLOB_RECURSE _web_srcs CONFIGURE_DEPENDS
"${_web_frontend}/src/*"
"${_web_frontend}/public/*"
"${_web_frontend}/index.html"
"${_web_frontend}/package.json"
"${_web_frontend}/package-lock.json"
"${_web_frontend}/tsconfig.json"
"${_web_frontend}/vite.config.ts")
add_custom_command(
OUTPUT "${_web_dist}/index.html"
# `npm ci` when the lockfile is newer than node_modules keeps installs
# reproducible; the stamp check avoids reinstalling on every build.
COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit --no-fund
COMMAND ${NPM_EXECUTABLE} run build
WORKING_DIRECTORY "${_web_frontend}"
DEPENDS ${_web_srcs}
COMMENT "Building Echoion web frontend (vite)"
VERBATIM)
add_custom_target(EchoionWebFrontend ALL
DEPENDS "${_web_dist}/index.html")
add_dependencies(EchoionWeb EchoionWebFrontend)
set(_web_assets "${_web_dist}")
else()
# Frontend build skipped: ship whatever is already in web-dist (a prior
# build or a committed snapshot). Falls back to nothing if absent.
set(_web_assets "${_web_dist}")
endif()
# Ship the built browser assets next to the runtime binary. Remove the target
# first so stale files (e.g. an earlier vanilla-JS build) never linger.
add_custom_command(TARGET EchoionWeb POST_BUILD
COMMAND ${CMAKE_COMMAND} -E rm -rf "${CMAKE_BINARY_DIR}/bin/web"
COMMAND ${CMAKE_COMMAND} -E copy_directory
"${_web_assets}"
"${CMAKE_BINARY_DIR}/bin/web"
COMMENT "Copying EchoionWeb static assets to bin/web"
)
install(DIRECTORY "${_web_dist}/" DESTINATION share/echoion/web)
+3
View File
@@ -0,0 +1,3 @@
node_modules/
web-dist/
*.tsbuildinfo
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Echoion — Music Bot</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#151522">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Echoion">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="stylesheet" href="/fonts.css">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+2320
View File
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "echoion-web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"test": "vitest run",
"i18n:check": "node scripts/i18n-check.mjs"
},
"dependencies": {
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@types/youtube": "^0.1.2",
"@vitejs/plugin-react": "^4.5.0",
"typescript": "^5.8.0",
"vite": "^6.3.0",
"vitest": "^3.1.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<rect width="24" height="24" rx="5" fill="#151522"/>
<rect x="4" y="9" width="3.4" height="10" rx="1.6" fill="#a970ff"/>
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" fill="#ff8080"/>
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" fill="#ffd977"/>
</svg>

After

Width:  |  Height:  |  Size: 335 B

+480
View File
@@ -0,0 +1,480 @@
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-1.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-2.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-3.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-4.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-5.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'JetBrains Mono';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/JetBrainsMono-6.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-7.woff2") format('woff2');
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-8.woff2") format('woff2');
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-9.woff2") format('woff2');
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-10.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-11.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Manrope';
font-style: normal;
font-weight: 800;
font-display: swap;
src: url("/fonts/Manrope-12.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-13.woff2") format('woff2');
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-14.woff2") format('woff2');
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Space Grotesk';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/SpaceGrotesk-15.woff2") format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Full-bleed background for the maskable safe area; bars inset ~20%. -->
<rect width="512" height="512" fill="#151522"/>
<rect x="150" y="232" width="52" height="150" rx="24" fill="#a970ff"/>
<rect x="238" y="160" width="52" height="222" rx="24" fill="#ff8080"/>
<rect x="326" y="278" width="52" height="104" rx="24" fill="#ffd977"/>
</svg>

After

Width:  |  Height:  |  Size: 412 B

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#151522"/>
<rect x="96" y="200" width="72" height="212" rx="34" fill="#a970ff"/>
<rect x="220" y="100" width="72" height="312" rx="34" fill="#ff8080"/>
<rect x="344" y="264" width="72" height="148" rx="34" fill="#ffd977"/>
</svg>

After

Width:  |  Height:  |  Size: 343 B

+25
View File
@@ -0,0 +1,25 @@
{
"name": "Echoion Music Bot",
"short_name": "Echoion",
"description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "any",
"background_color": "#0d0d1f",
"theme_color": "#151522",
"icons": [
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-maskable.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "maskable"
}
]
}
+83
View File
@@ -0,0 +1,83 @@
// Minimal, dependency-free service worker: makes the panel installable and
// keeps the app shell available offline. It deliberately does NOT touch the
// live surfaces — /rpc and /ws (WebSockets aren't interceptable anyway),
// /config.json, /avatar/*, /emoji/* all fall through to the network so the UI
// never shows stale identity/config.
// Bump when the player shell changes materially so installed/PWA clients do
// not retain an index that references a removed hashed bundle.
const CACHE = 'echoion-shell-v2';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
)
.then(() => self.clients.claim())
);
});
// Only same-origin GETs are cacheable; everything else passes through.
function isStaticAsset(url) {
return (
url.pathname.startsWith('/assets/') ||
url.pathname === '/manifest.webmanifest' ||
url.pathname.startsWith('/icon') ||
url.pathname.startsWith('/fonts') ||
url.pathname.endsWith('.css') ||
url.pathname.endsWith('.woff2') ||
url.pathname.endsWith('.svg')
);
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// Never intercept the live control/config/media surfaces.
if (
url.pathname === '/config.json' ||
url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/ws') ||
url.pathname.startsWith('/avatar') ||
url.pathname.startsWith('/emoji')
) {
return;
}
// SPA navigations: network-first, fall back to the cached shell offline.
if (req.mode === 'navigate') {
event.respondWith(
fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req)))
);
return;
}
// Hashed static assets: cache-first, populate on first hit.
if (isStaticAsset(url)) {
event.respondWith(
caches.match(req).then(
(hit) =>
hit ||
fetch(req).then((resp) => {
if (resp.ok) {
const copy = resp.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
}
return resp;
})
)
);
}
});
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env node
// Diffs the Russian catalog (src/i18n/ru.ts) against every t('…') / tf('…')
// literal in src/**/*.ts{,x}, both ways:
// - missing: used in code but absent from ru.ts (falls back to English)
// - 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:
// - watch.ts state strings rendered via t(w.playerEmpty)
// - SHORTCUTS labels (lib/shortcuts.ts) rendered via t(sc.label)
// - 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
// list below suppresses the ones we know about.
//
// Usage: npm run i18n:check (exits 1 when keys are missing)
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const srcDir = join(root, 'src');
const ruFile = join(srcDir, 'i18n', 'ru.ts');
// Keys reached through variables (see header); keep in sync by hand.
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
'connected',
'disconnected',
'error',
// SHORTCUTS labels (lib/shortcuts.ts)
'Play / pause',
'Seek 5s',
'Volume',
'Skip / vote skip',
'Focus search',
'This help',
// HEADS view titles/subtitles (App.tsx)
'Now Playing',
'What Echoion is streaming to the channel',
'Queue',
'Reorder and manage upcoming tracks',
'Search',
'Find tracks across YouTube and Yandex Music',
'Library',
'Your favorites and saved playlists',
'History & Stats',
'Playback history and server insights',
'Watch Together',
'Synced viewing room — everyone in step',
'Server & Admin',
'Manage subscribers and broadcast',
'RPC / API',
'Connect to Echoion programmatically',
// Sidebar NAV labels rendered via t(item.label) — same strings as HEADS
// titles, listed above.
]);
const unescape = (s) => s.replace(/\\(.)/g, '$1');
function walk(dir, out = []) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
if (statSync(p).isDirectory()) walk(p, out);
else if (/\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name)) {
out.push(p);
}
}
return out;
}
// Catalog keys: top-level `'key': '…'` entries of the ru object literal.
const ruKeys = new Set();
for (const m of readFileSync(ruFile, 'utf8').matchAll(
/^\s*'((?:[^'\\]|\\.)*)':/gm
)) {
ruKeys.add(unescape(m[1]));
}
// Used keys: every t('…') / tf('…', …) string literal.
const used = new Set();
for (const file of walk(srcDir)) {
if (file === ruFile) continue;
const text = readFileSync(file, 'utf8');
for (const m of text.matchAll(/\btf?\(\s*'((?:[^'\\]|\\.)*)'/g)) {
used.add(unescape(m[1]));
}
}
const missing = [...used].filter((k) => !ruKeys.has(k)).sort();
const orphaned = [...ruKeys]
.filter((k) => !used.has(k) && !KNOWN_DYNAMIC.has(k))
.sort();
if (missing.length) {
console.log(`Missing from ru.ts (${missing.length}):`);
for (const k of missing) console.log(`\t'${k.replace(/'/g, "\\'")}':`);
}
if (orphaned.length) {
console.log(`\nIn ru.ts but never used as a literal (${orphaned.length}):`);
for (const k of orphaned) console.log(`\t'${k.replace(/'/g, "\\'")}'`);
console.log('(may be dynamic keys — verify before deleting)');
}
if (!missing.length && !orphaned.length) console.log('i18n: OK');
process.exit(missing.length ? 1 : 0);
+121
View File
@@ -0,0 +1,121 @@
import { useEffect } from 'react';
import { appStore, boot, getStoredToken, toast } from './lib/app';
import { initWatch } from './lib/watch';
import { initRouter } from './lib/router';
import { initShortcuts } from './lib/shortcuts';
import { initMediaSession } from './lib/mediaSession';
import { useStore } from './lib/store';
import { useLanguage, t } from './i18n';
import { HelpIcon, MenuIcon } from './components/icons';
import { Sidebar } from './components/Sidebar';
import { MiniPlayer } from './components/MiniPlayer';
import { DialogHost } from './components/DialogHost';
import { ShortcutsHelp } from './components/ShortcutsHelp';
import { NowView } from './views/NowView';
import { QueueView } from './views/QueueView';
import { SearchView } from './views/SearchView';
import { LibraryView } from './views/LibraryView';
import { StatsView } from './views/StatsView';
import { WatchView } from './views/WatchView';
import { ServerView } from './views/ServerView';
import { RpcView } from './views/RpcView';
const HEADS: Record<string, [string, string]> = {
now: ['Now Playing', 'What Echoion is streaming to the channel'],
queue: ['Queue', 'Reorder and manage upcoming tracks'],
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
};
export function App() {
const s = useStore(appStore);
useLanguage(); // re-render everything on language switch
useEffect(() => {
boot();
initWatch({
getName: () =>
(appStore.get().identity &&
appStore.get().identity!.nickname) ||
null,
getToken: getStoredToken,
toast,
});
initRouter();
initShortcuts();
initMediaSession();
}, []);
const [title, sub] = HEADS[s.view] || HEADS.now;
return (
<div id="app">
<Sidebar />
{s.sidebarOpen && (
<div
className="drawer-backdrop"
onClick={() => appStore.set({ sidebarOpen: false })}
/>
)}
<main className="main">
<header className="header">
<div className="header-title">
<button
className="icon-btn hamburger"
title={t('Menu')}
aria-label={t('Menu')}
onClick={() =>
appStore.set({ sidebarOpen: !s.sidebarOpen })
}
>
<MenuIcon />
</button>
<div>
<h1>{t(title)}</h1>
<div className="header-sub">{t(sub)}</div>
</div>
</div>
<div className="header-right">
<span className="pill">
<span className="dot dot-green" />
{s.onlineCount}&nbsp;{t('listening')}
</span>
<button
className="icon-btn"
title={t('Keyboard shortcuts')}
aria-label={t('Keyboard shortcuts')}
onClick={() =>
appStore.set({ shortcutsOpen: true })
}
>
<HelpIcon />
</button>
</div>
</header>
{s.view === 'now' && <NowView />}
{s.view === 'queue' && <QueueView />}
{s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{/* 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 === 'rpc' && <RpcView />}
<MiniPlayer />
</main>
{s.toast && <div className="toast">{s.toast}</div>}
<DialogHost />
<ShortcutsHelp />
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
import { useState } from 'react';
import { safeCall, toast } from '../lib/app';
import { renderTsMarkup } from '../lib/tsMarkup';
import { Modal } from './Modal';
import { t } from '../i18n';
// Announce composer with a live TS6-markdown/BBCode preview (item 14).
// Replaces the old prompt(). A small toolbar wraps the selection in common
// formatting tags; the preview renders exactly what subscribers will see.
const TOOLBAR: Array<{ label: string; before: string; after: string }> = [
{ label: 'B', before: '**', after: '**' },
{ label: 'I', before: '*', after: '*' },
{ label: 'U', before: '[u]', after: '[/u]' },
{ label: 'S', before: '~~', after: '~~' },
{ label: '</>', before: '`', after: '`' },
{ label: '🔗', before: '[', after: '](https://)' },
{ label: 'H', before: '# ', after: '' },
{ label: '❝', before: '> ', after: '' },
];
export function AnnounceModal({ onClose }: { onClose: () => void }) {
const [text, setText] = useState('');
const [sending, setSending] = useState(false);
let ref: HTMLTextAreaElement | null = null;
const wrap = (before: string, after: string) => {
const el = ref;
if (!el) return;
const start = el.selectionStart;
const end = el.selectionEnd;
const selected = text.slice(start, end);
const next =
text.slice(0, start) + before + selected + after + text.slice(end);
setText(next);
// Restore focus with the caret after the inserted opening tag.
queueMicrotask(() => {
el.focus();
const pos = start + before.length + selected.length;
el.setSelectionRange(pos, pos);
});
};
return (
<Modal
title={t('Compose announcement')}
onClose={onClose}
wide
footer={
<>
<button className="btn btn-ghost" onClick={onClose}>
{t('Cancel')}
</button>
<button
className="btn btn-accent"
disabled={!text.trim() || sending}
onClick={async () => {
setSending(true);
const res = await safeCall<{ message?: string }>(
'Announce',
{ text: text.trim() }
);
setSending(false);
if (res) {
toast(res.message || t('Announcement sent'));
onClose();
}
}}
>
{t('Send announcement')}
</button>
</>
}
>
<div className="announce-toolbar">
{TOOLBAR.map((b) => (
<button
key={b.label}
className="btn btn-ghost"
type="button"
onClick={() => wrap(b.before, b.after)}
>
{b.label}
</button>
))}
</div>
<div className="announce-grid">
<textarea
ref={(el) => {
ref = el;
}}
className="announce-input"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={t('Announcement to all subscribers:')}
rows={10}
/>
<div className="announce-preview">
<div className="announce-preview-label">
{t('Preview')}
</div>
<div className="ts-markup">
{text.trim() ? (
renderTsMarkup(text)
) : (
<span className="muted">
{t('Nothing to preview yet')}
</span>
)}
</div>
</div>
</div>
</Modal>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { useEffect, useRef, useState } from 'react';
import { avatarColor } from '../lib/format';
// User avatar: tries the TeamSpeak avatar served at /avatar/<uid>, falling
// back to the initial-letter-on-gradient avatar when the image is missing.
// `uid` is the stable TeamSpeak unique id.
//
// The server fetches avatars from TeamSpeak lazily (it must first sync the
// client's avatar hash, then download the file), so the first few requests can
// 404 while that completes. We retry a handful of times with a growing delay,
// bypassing the browser's negative cache with a ?v=N buster, before giving up
// and showing initials.
const RETRY_DELAYS_MS = [2500, 4000, 6000, 9000];
export function Avatar(props: {
name: string;
uid?: string | null;
size?: number;
className?: string;
}) {
const { name, uid, size, className } = props;
const [attempt, setAttempt] = useState(0);
const [failed, setFailed] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Reset retry state whenever the target uid changes.
useEffect(() => {
setAttempt(0);
setFailed(false);
return () => {
if (timer.current) clearTimeout(timer.current);
};
}, [uid]);
const style: React.CSSProperties = size
? { width: `${size}px`, height: `${size}px` }
: {};
if (uid && !failed) {
const src =
`/avatar/${encodeURIComponent(uid)}` +
(attempt > 0 ? `?v=${attempt}` : '');
return (
<img
className={'avatar avatar-img' + (className ? ` ${className}` : '')}
style={style}
src={src}
alt={name}
onError={() => {
if (attempt < RETRY_DELAYS_MS.length) {
const delay = RETRY_DELAYS_MS[attempt];
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(
() => setAttempt((a) => a + 1),
delay
);
} else {
setFailed(true);
}
}}
/>
);
}
return (
<span
className={'avatar' + (className ? ` ${className}` : '')}
style={{ ...style, background: avatarColor(name || '?') }}
>
{(name || '?').charAt(0).toUpperCase()}
</span>
);
}
+82
View File
@@ -0,0 +1,82 @@
import { useRef, useState } from 'react';
// Pointer-drag on a bar: the fill tracks the pointer while dragging and
// onCommit fires once on release (a plain click is a zero-length drag).
// Port of app.js makeDraggableBar.
//
// When `formatValue` is given, a tooltip bubble follows the pointer on hover
// and drag showing the value at that position (item 14) — e.g. a seek time or
// a volume percentage.
export function Bar(props: {
pct: number; // 0..100, authoritative fill when not dragging
bufferPct?: number; // 0..100, second fill layer behind the progress
slim?: boolean;
className?: string;
onCommit?: (fraction: number) => void;
onDragStart?: () => boolean; // return false to refuse the drag
live?: boolean; // live drag feedback: onCommit also fires on move
formatValue?: (fraction: number) => string; // tooltip text at a fraction
}) {
const el = useRef<HTMLDivElement>(null);
const [dragPct, setDragPct] = useState<number | null>(null);
// Pointer position (0..100) for the tooltip; null when the pointer is away.
const [hoverPct, setHoverPct] = useState<number | null>(null);
const fraction = (e: React.PointerEvent) => {
const r = el.current!.getBoundingClientRect();
return Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
};
const tipPct = dragPct ?? hoverPct;
const showTip = props.formatValue && tipPct != null;
return (
<div
ref={el}
className={
'bar' +
(props.slim ? ' bar-slim' : '') +
(props.className ? ` ${props.className}` : '')
}
onPointerDown={(e) => {
if (props.onDragStart && !props.onDragStart()) return;
e.currentTarget.setPointerCapture(e.pointerId);
const f = fraction(e);
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerMove={(e) => {
const f = fraction(e);
setHoverPct(f * 100);
if (dragPct == null) return;
setDragPct(f * 100);
if (props.live) props.onCommit?.(f);
}}
onPointerLeave={() => setHoverPct(null)}
onPointerUp={(e) => {
if (dragPct == null) return;
setDragPct(null);
if (!props.live) props.onCommit?.(fraction(e));
}}
>
{props.bufferPct != null && (
<div
className="bar-buffer"
style={{ width: `${Math.min(100, props.bufferPct)}%` }}
/>
)}
<div
className="bar-fill"
style={{ width: `${dragPct ?? props.pct}%` }}
/>
{showTip && (
<div
className="bar-tip"
style={{ left: `${tipPct}%` }}
>
{props.formatValue!((tipPct as number) / 100)}
</div>
)}
</div>
);
}
+94
View File
@@ -0,0 +1,94 @@
import { useEffect, useRef, useState } from 'react';
import { Modal } from './Modal';
import { useStore } from '../lib/store';
import { dialogStore, resolveConfirm, resolvePrompt } from '../lib/dialog';
import { t } from '../i18n';
// Renders the active custom dialog (confirm/prompt). Mounted once at the app
// root; see lib/dialog.ts for the confirmDialog/promptDialog helpers.
export function DialogHost() {
const { current } = useStore(dialogStore);
const [text, setText] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
// Seed the prompt field with its initial value and focus it each time a
// new prompt opens.
useEffect(() => {
if (current && current.kind === 'prompt') {
setText(current.initial || '');
// Focus after the modal mounts.
setTimeout(() => inputRef.current?.focus(), 0);
}
}, [current]);
if (!current) return null;
if (current.kind === 'confirm') {
return (
<Modal
title={current.title}
onClose={() => resolveConfirm(false)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolveConfirm(false)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className={
'btn ' +
(current.danger ? 'btn-danger' : 'btn-accent')
}
onClick={() => resolveConfirm(true)}
>
{current.confirmLabel || t('Confirm')}
</button>
</>
}
>
<p>{current.message}</p>
</Modal>
);
}
return (
<Modal
title={current.title}
onClose={() => resolvePrompt(null)}
footer={
<>
<button
className="btn btn-ghost"
onClick={() => resolvePrompt(null)}
>
{current.cancelLabel || t('Cancel')}
</button>
<button
className="btn btn-accent"
onClick={() => resolvePrompt(text.trim() || null)}
>
{current.confirmLabel || t('OK')}
</button>
</>
}
>
<form
onSubmit={(e) => {
e.preventDefault();
resolvePrompt(text.trim() || null);
}}
>
{current.message && <p>{current.message}</p>}
<input
ref={inputRef}
value={text}
onChange={(e) => setText(e.target.value)}
placeholder={current.placeholder}
autoComplete="off"
/>
</form>
</Modal>
);
}
+112
View File
@@ -0,0 +1,112 @@
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
@@ -0,0 +1,113 @@
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>
);
}
+108
View File
@@ -0,0 +1,108 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import type { LyricsResult } from '../lib/types';
import { t } from '../i18n';
// Lyrics for the current track (via the bot's GetLyrics → lrclib). When the
// provider returns time-synced lines we highlight the active one against the
// shared playback clock (appStore.positionMs) and keep it scrolled into view;
// otherwise we show plain scrollable text. Collapsed by default so we only
// fetch when the listener asks for it.
export function LyricsPanel() {
const s = useStore(appStore);
const [open, setOpen] = useState(false);
const [lyrics, setLyrics] = useState<LyricsResult | null>(null);
const [loading, setLoading] = useState(false);
const activeRef = useRef<HTMLDivElement>(null);
const track = s.current;
// Refetch when the track identity changes (url is stable per track).
const key = track ? track.url || track.title || '' : '';
useEffect(() => {
if (!open || !key) {
return;
}
let cancelled = false;
setLoading(true);
setLyrics(null);
safeCall<LyricsResult>('GetLyrics').then((res) => {
if (!cancelled) {
setLyrics(res);
setLoading(false);
}
});
return () => {
cancelled = true;
};
}, [key, open]);
const synced = lyrics?.synced ?? [];
// Index of the last line whose timestamp has passed.
const activeIdx = useMemo(() => {
if (!synced.length) return -1;
let idx = -1;
for (let i = 0; i < synced.length; i++) {
if (synced[i].ms <= s.positionMs) idx = i;
else break;
}
return idx;
}, [synced, s.positionMs]);
useEffect(() => {
activeRef.current?.scrollIntoView({ block: 'nearest' });
}, [activeIdx]);
return (
<div className="card">
<div className="card-head">
<h3>{t('Lyrics')}</h3>
<button
className="link"
onClick={() => setOpen((v) => !v)}
disabled={!track}
>
{open ? t('Hide') : t('Show')}
</button>
</div>
{open && (
<div className="lyrics-body">
{!track ? (
<div className="lyrics-empty">
{t('Nothing playing')}
</div>
) : loading ? (
<div className="lyrics-empty">{t('Loading…')}</div>
) : !lyrics || !lyrics.found ? (
<div className="lyrics-empty">
{t('No lyrics found')}
</div>
) : synced.length ? (
<div className="lyrics-synced">
{synced.map((line, i) => (
<div
key={i}
ref={i === activeIdx ? activeRef : null}
className={
'lyrics-line' +
(i === activeIdx ? ' active' : '')
}
>
{line.text || '♪'}
</div>
))}
</div>
) : (
<pre className="lyrics-plain">{lyrics.plain}</pre>
)}
{lyrics && lyrics.found && lyrics.source && (
<div className="lyrics-source muted">
{t('Lyrics via')} {lyrics.source}
</div>
)}
</div>
)}
</div>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { appStore, safeCall } from '../lib/app';
import { useStore } from '../lib/store';
import { Bar } from './Bar';
import { coverStyle, fmtMs } from '../lib/format';
import { PauseIcon, PlayIcon, SkipNextIcon } from './icons';
import { t } from '../i18n';
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
// Mini player mirrors the current track on views other than Now Playing.
export function MiniPlayer() {
const s = useStore(appStore);
if (s.view === 'now' || !s.current) return null;
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
const canForceSkip = !!(
s.identity &&
(s.identity.isAdmin || s.identity.isDj)
);
const durationMs = s.durationMs || s.current.duration || 0;
const pct =
durationMs > 0 ? Math.min(100, (s.positionMs / durationMs) * 100) : 0;
return (
<div className="miniplayer">
<div
className="mini-cover"
style={{ background: coverStyle(s.current) }}
/>
<div className="mini-info">
<div className="mini-title">{s.current.title}</div>
<div className="mini-artist">{s.current.artist || ''}</div>
</div>
<button
className="ctrl"
title={t('Play/Pause')}
onClick={togglePlay}
>
{playing ? <PauseIcon /> : <PlayIcon />}
</button>
{canForceSkip && (
<button
className="ctrl"
title={t('Force skip')}
onClick={() => safeCall('Skip', { count: 1 })}
>
<SkipNextIcon />
</button>
)}
<Bar
slim
className="mini-bar"
pct={pct}
formatValue={(f) =>
durationMs ? fmtMs(Math.round(f * durationMs)) : ''
}
onDragStart={() => durationMs > 0}
onCommit={(f) =>
safeCall('Seek', {
position: Math.round(f * durationMs),
})
}
/>
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import type { ReactNode } from 'react';
import { CloseIcon } from './icons';
export function Modal(props: {
title: string;
onClose: () => void;
children: ReactNode;
footer?: ReactNode;
wide?: boolean;
}) {
return (
<div className="modal-backdrop" onClick={props.onClose}>
<div
className={'modal' + (props.wide ? ' modal-wide' : '')}
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<h2>{props.title}</h2>
<button className="icon-btn" onClick={props.onClose}>
<CloseIcon />
</button>
</div>
<div className="modal-body">{props.children}</div>
{props.footer && (
<div className="modal-foot">{props.footer}</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
describe('NowPlayingVideo drift correction', () => {
it('never seeks while unstarted, cued, or buffering', () => {
for (const state of [-1, 3, 5]) {
expect(shouldCorrectVideoDrift(state, 0, 30, 10_000)).toBe(false);
}
});
it('waits for cooldown and ignores small playing drift', () => {
expect(shouldCorrectVideoDrift(1, 0, 30, 1000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 28, 30, 10_000)).toBe(false);
expect(shouldCorrectVideoDrift(1, 10, 30, 10_000)).toBe(true);
});
});
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useRef } from 'react';
import { appStore } from '../lib/app';
import {
loadYouTubeApi,
YOUTUBE_EMBED_HOST,
youtubeEmbedVars,
} from '../lib/youtube';
import { shouldCorrectVideoDrift } from '../lib/nowPlayingVideoSync';
// The muted YouTube video of the current track, shown in Now Playing when the
// user enables it (item 11). The bot's audio is the source of truth, so the
// video is always muted and only follows the server position — it resyncs
// with a hard seek when it drifts past the threshold, and pauses/plays to
// match. Purely a local visual aid; it sends nothing to the server.
const SEEK_LEAD_SECONDS = 0.75;
export function NowPlayingVideo({ videoId }: { videoId: string }) {
const mountRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<YT.Player | null>(null);
const currentVideo = useRef<string>('');
const pendingVideo = useRef(videoId);
const lastSeekAt = useRef(0);
const playIntent = useRef<boolean | null>(null);
useEffect(() => {
let cancelled = false;
loadYouTubeApi().then(() => {
if (cancelled || !mountRef.current) return;
const el = document.createElement('div');
mountRef.current.appendChild(el);
playerRef.current = new YT.Player(el, {
width: '100%',
height: '100%',
videoId,
host: YOUTUBE_EMBED_HOST,
playerVars: youtubeEmbedVars({ mute: 1 }),
events: {
onReady: () => {
const p = playerRef.current;
if (!p) return;
const requested = pendingVideo.current;
const startSeconds = appStore.get().positionMs / 1000;
if (requested !== videoId) {
p.loadVideoById({ videoId: requested, startSeconds });
} else if (startSeconds > 0) {
p.seekTo(startSeconds, true);
}
p.mute();
currentVideo.current = requested;
lastSeekAt.current = performance.now();
playIntent.current = null;
},
},
});
});
return () => {
cancelled = true;
playerRef.current?.destroy();
playerRef.current = null;
if (mountRef.current) mountRef.current.innerHTML = '';
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Load a new video id in place without recreating the player.
useEffect(() => {
pendingVideo.current = videoId;
const p = playerRef.current;
if (!p || !p.loadVideoById || currentVideo.current === videoId) return;
p.loadVideoById({
videoId,
startSeconds: appStore.get().positionMs / 1000,
});
p.mute();
currentVideo.current = videoId;
lastSeekAt.current = performance.now();
playIntent.current = null;
}, [videoId]);
// Follow the server position: resync on drift, match play/pause state.
useEffect(() => {
const id = setInterval(() => {
const p = playerRef.current;
if (!p || !p.getCurrentTime || !p.seekTo) return;
const s = appStore.get();
const targetSec = s.positionMs / 1000;
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
try {
const st = p.getPlayerState();
const now = performance.now();
// Seeking while CUED/BUFFERING repeatedly restarts YouTube's
// buffer. Drift is meaningful only once the playback clock moves.
if (shouldCorrectVideoDrift(
st,
p.getCurrentTime(),
targetSec,
now - lastSeekAt.current
)) {
p.seekTo(targetSec + SEEK_LEAD_SECONDS, true);
lastSeekAt.current = now;
}
if (
playing &&
playIntent.current !== true &&
(st === YT.PlayerState.CUED ||
st === YT.PlayerState.PAUSED ||
st === YT.PlayerState.ENDED)
) {
p.playVideo();
playIntent.current = true;
}
else if (
!playing &&
playIntent.current !== false &&
(st === YT.PlayerState.PLAYING || st === YT.PlayerState.BUFFERING)
) {
p.pauseVideo();
playIntent.current = false;
}
p.mute(); // guard against unmute on state changes
} catch {
/* player not ready yet */
}
}, 1000);
return () => clearInterval(id);
}, []);
return <div className="np-video" ref={mountRef} />;
}
+31
View File
@@ -0,0 +1,31 @@
import type { ReactNode } from 'react';
import { Avatar } from './Avatar';
export function PersonRow(props: {
name: string;
uid?: string | null;
sub?: string;
status?: string;
statusColor?: string;
children?: ReactNode;
}) {
const { name, uid, sub, status, statusColor, children } = props;
return (
<div className="person">
<Avatar name={name} uid={uid} />
<div className="person-main">
<div className="person-name">{name}</div>
{sub && <div className="person-sub">{sub}</div>}
</div>
{status && (
<span
className="person-status"
style={statusColor ? { color: statusColor } : undefined}
>
{status}
</span>
)}
{children}
</div>
);
}
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { PlayerControls } from './PlayerControls';
const noop = () => {};
function render(over: Partial<Parameters<typeof PlayerControls>[0]> = {}) {
return renderToStaticMarkup(
<PlayerControls
playing={false}
positionMs={30_000}
durationMs={120_000}
canControl
volumePct={50}
onTogglePlay={noop}
onSeekMs={noop}
onSeekBy={noop}
onVolume={noop}
{...over}
/>
);
}
describe('PlayerControls', () => {
it('shows transport, times and volume when controllable', () => {
const html = render();
expect(html).toContain('0:30');
expect(html).toContain('2:00');
expect(html).toContain('Back 10 seconds');
expect(html).toContain('Forward 10 seconds');
expect(html).not.toContain('disabled');
});
it('disables transport when canControl is false', () => {
const html = render({ canControl: false });
// Play/pause + the two ±10s buttons are disabled…
expect(html.match(/disabled/g)?.length).toBe(3);
// …but the volume bar (local) is still rendered.
expect(html).toContain('50%');
});
it('hides seek buttons and shows LIVE for live sources', () => {
const html = render({ live: true });
expect(html).not.toContain('Back 10 seconds');
expect(html).toContain('LIVE');
});
it('renders skip only when onSkip is given', () => {
expect(render()).not.toContain('Play next');
expect(render({ onSkip: noop })).toContain('Play next');
});
it('hides the local row when showLocal is false', () => {
expect(render({ showLocal: false })).not.toContain('Vol');
});
it('renders the unified settings slot in the local row', () => {
expect(render({ settings: <button>Settings gear</button> })).toContain(
'Settings gear'
);
});
});
+130
View File
@@ -0,0 +1,130 @@
import type { ReactNode } from 'react';
import { Bar } from './Bar';
import { fmtMs } from '../lib/format';
import {
ForwardIcon,
FullscreenIcon,
PauseIcon,
PlayIcon,
RewindIcon,
SkipNextIcon,
} from './icons';
import { t } from '../i18n';
// The one custom player control bar, shared by Watch Together (room /ws
// protocol) and Now Playing (bot RPC). Purely presentational: the two sync
// channels differ only in the callbacks the views pass in. Embedded players
// (YouTube/Twitch/HTML5) always run with native controls hidden; this bar is
// the only playback UI.
export function PlayerControls(props: {
playing: boolean;
positionMs: number;
durationMs: number; // 0 = unknown
live?: boolean; // no seekable timeline (Twitch / generic embeds)
canControl: boolean; // transport disabled when false; volume stays local
bufferedPct?: number; // 0..100 second fill on the seek bar
volumePct: number; // 0..100
volumeLive?: boolean; // apply volume while dragging (local volume)
onTogglePlay: () => void;
onSeekMs: (ms: number) => void;
onSeekBy?: (deltaSec: number) => void; // renders ±10s when present
onVolume: (pct: number) => void;
onSkip?: () => void; // renders next-track button when present
skipDisabled?: boolean;
onFullscreen?: () => void;
settings?: ReactNode;
showLocal?: boolean; // hide the volume/quality row (default shown)
extra?: ReactNode; // view-specific buttons after the seek bar
extraLocal?: ReactNode; // view-specific controls in the volume row
}) {
const { live, durationMs, positionMs, canControl } = props;
const progressPct = live
? 100
: durationMs > 0
? Math.min(100, (positionMs / durationMs) * 100)
: 0;
return (
<div className="player-controls">
<div className="watch-controls">
<button
className="ctrl ctrl-main"
title={t('Play/Pause')}
disabled={!canControl}
onClick={props.onTogglePlay}
>
{props.playing ? <PauseIcon /> : <PlayIcon />}
</button>
{!live && props.onSeekBy && (
<>
<button
className="ctrl"
title={t('Back 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(-10)}
>
<RewindIcon />
</button>
<button
className="ctrl"
title={t('Forward 10 seconds')}
disabled={!canControl}
onClick={() => props.onSeekBy!(10)}
>
<ForwardIcon />
</button>
</>
)}
{props.onSkip && (
<button
className="ctrl"
title={t('Play next')}
disabled={!canControl || props.skipDisabled}
onClick={props.onSkip}
>
<SkipNextIcon />
</button>
)}
<span className="mono">{live ? '—' : fmtMs(positionMs)}</span>
<Bar
pct={progressPct}
bufferPct={live ? undefined : props.bufferedPct}
formatValue={(f) =>
live || !durationMs
? t('LIVE')
: fmtMs(Math.round(f * durationMs))
}
onDragStart={() => !live && durationMs > 0}
onCommit={(f) => props.onSeekMs(Math.round(f * durationMs))}
/>
<span className="mono">
{live ? t('LIVE') : fmtMs(durationMs)}
</span>
{props.extra}
</div>
{(props.showLocal ?? true) && (
<div className="watch-controls watch-local">
<span className="muted">{t('Vol')}</span>
<Bar
slim
live={props.volumeLive}
pct={props.volumePct}
formatValue={(f) => `${Math.round(f * 100)}%`}
onCommit={(f) => props.onVolume(Math.round(f * 100))}
/>
<span className="mono">{Math.round(props.volumePct)}%</span>
{props.settings}
{props.onFullscreen && (
<button
className="ctrl"
title={t('Fullscreen')}
onClick={props.onFullscreen}
>
<FullscreenIcon />
</button>
)}
{props.extraLocal}
</div>
)}
</div>
);
}
@@ -0,0 +1,99 @@
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>
);
}
+34
View File
@@ -0,0 +1,34 @@
import { appStore } from '../lib/app';
import { useStore } from '../lib/store';
import { SHORTCUTS } from '../lib/shortcuts';
import { t } from '../i18n';
// Cheat-sheet overlay for keyboard shortcuts, toggled with "?".
export function ShortcutsHelp() {
const s = useStore(appStore);
if (!s.shortcutsOpen) return null;
return (
<div
className="modal-backdrop"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
<div className="modal shortcuts-modal" onClick={(e) => e.stopPropagation()}>
<h2>{t('Keyboard shortcuts')}</h2>
<div className="shortcuts-list">
{SHORTCUTS.map((sc) => (
<div key={sc.keys} className="shortcut-row">
<kbd>{sc.keys}</kbd>
<span>{t(sc.label)}</span>
</div>
))}
</div>
<button
className="btn btn-ghost"
onClick={() => appStore.set({ shortcutsOpen: false })}
>
{t('Close')}
</button>
</div>
</div>
);
}
+178
View File
@@ -0,0 +1,178 @@
import { useState, type ReactNode } from 'react';
import {
appStore,
changeLanguage,
connectWithToken,
getStoredToken,
logout,
requestToken,
showView,
type ViewName,
} from '../lib/app';
import { useStore } from '../lib/store';
import { promptDialog } from '../lib/dialog';
import { Avatar } from './Avatar';
import {
CodeIcon,
GearIcon,
HeartIcon,
PlayIcon,
QueueIcon,
SearchIcon,
StatsIcon,
WatchIcon,
} from './icons';
import { t, useLanguage } from '../i18n';
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'now', icon: <PlayIcon />, label: 'Now Playing' },
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
];
export function Sidebar() {
const s = useStore(appStore);
const language = useLanguage();
const [token, setToken] = useState(getStoredToken() || '');
const isAdmin = !!(s.identity && s.identity.isAdmin);
const playing = !!(
s.status &&
s.status.isPlaying &&
!s.status.isPaused
);
const name = s.identity
? s.identity.nickname || s.identity.uid || t('user')
: '';
return (
<aside className={'sidebar' + (s.sidebarOpen ? ' open' : '')}>
<div className="brand">
<div className="brand-icon">
<svg viewBox="0 0 24 24" width="22" height="22" fill="#fff">
<rect x="4" y="9" width="3.4" height="10" rx="1.6" />
<rect x="10.3" y="4" width="3.4" height="15" rx="1.6" />
<rect x="16.6" y="12" width="3.4" height="7" rx="1.6" />
</svg>
</div>
<div>
<div className="brand-name">Echoion</div>
<div className="brand-sub">{t('MUSIC BOT · TS3')}</div>
</div>
</div>
<nav className="nav">
{NAV.filter(
(item) => item.view !== 'server' || isAdmin
).map((item) => (
<button
key={item.view}
className={
'nav-item' + (s.view === item.view ? ' active' : '')
}
onClick={() => showView(item.view)}
>
<span className="nav-ico">{item.icon}</span>
{t(item.label)}
{item.view === 'now' && playing && (
<span className="live-dot" />
)}
{item.view === 'queue' && s.queue.length > 0 && (
<span className="nav-badge">{s.queue.length}</span>
)}
</button>
))}
</nav>
<div className="sidebar-foot">
<div className="conn-row">
<span
className={
'conn-dot' +
(s.connection === 'connected'
? ' on'
: s.connection === 'error'
? ' err'
: '')
}
/>
<span>{t(s.connection)}</span>
<select
className="lang-select"
value={language}
title={t('Language')}
onChange={(e) =>
changeLanguage(e.target.value as 'en' | 'ru')
}
>
<option value="en">EN</option>
<option value="ru">RU</option>
</select>
</div>
{!s.identity ? (
<div>
<input
type="password"
placeholder={t('RPC token')}
autoComplete="off"
value={token}
onChange={(e) => setToken(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
connectWithToken(token);
}
}}
/>
<button
className="btn btn-accent"
onClick={() => connectWithToken(token)}
>
{t('Connect')}
</button>
<button
className="btn btn-ghost"
title={t('Send my token via TeamSpeak PM')}
onClick={async () => {
const nickname = await promptDialog({
title: t('Get token by nickname'),
message: t(
'Your TeamSpeak nickname (must be subscribed):'
),
placeholder: t('Nickname'),
confirmLabel: t('Send'),
});
if (nickname) requestToken(nickname);
}}
>
{t('Get token by nickname…')}
</button>
</div>
) : (
<div className="whoami">
<Avatar name={name} uid={s.identity.uid} />
<span>{name}</span>
{isAdmin && (
<span className="admin-chip">{t('ADMIN')}</span>
)}
{!isAdmin && s.identity.isDj && (
<span className="admin-chip">{t('DJ')}</span>
)}
<button
className="btn btn-ghost"
onClick={() => {
logout();
setToken('');
}}
>
{t('Logout')}
</button>
</div>
)}
</div>
</aside>
);
}
+79
View File
@@ -0,0 +1,79 @@
import type { ReactNode } from 'react';
import type { Track } from '../lib/types';
import { coverStyle, fmtMs, sourceInfo } from '../lib/format';
import { t } from '../i18n';
export interface TrackAction {
icon: ReactNode;
title: string;
cls?: string;
onClick: () => void;
}
export function TrackRow(props: {
track: Track;
num?: number;
playing?: boolean;
sub?: string;
actions?: Array<TrackAction | null | false>;
rowProps?: React.HTMLAttributes<HTMLDivElement> & { draggable?: boolean };
children?: ReactNode;
}) {
const { track, num, playing, sub, rowProps, children } = props;
const actions = (props.actions || []).filter(Boolean) as TrackAction[];
const src = sourceInfo(track);
return (
<div
{...rowProps}
className={
'track-row' +
(playing ? ' playing' : '') +
(rowProps?.className ? ` ${rowProps.className}` : '')
}
>
{num != null && (
<span className="track-num">
{String(num).padStart(2, '0')}
</span>
)}
<div
className="track-cover"
style={{ background: coverStyle(track) }}
/>
<div className="track-main">
<div className="track-title">
{track.title || t('(untitled)')}
</div>
<div className="track-sub">
{[track.artist, sub].filter(Boolean).join(' · ')}
</div>
</div>
{src && <span className={src.cls}>{src.label}</span>}
{!!track.duration && (
<span className="track-dur">{fmtMs(track.duration)}</span>
)}
{actions.length > 0 && (
<div className="track-actions">
{actions.map((a, i) => (
<button
key={i}
className={'icon-btn' + (a.cls ? ` ${a.cls}` : '')}
title={a.title}
onClick={(e) => {
e.stopPropagation();
a.onClick();
}}
>
{a.icon}
</button>
))}
</div>
)}
{children}
</div>
);
}
export function EmptyRow({ text }: { text: string }) {
return <div className="empty">{text}</div>;
}
+145
View File
@@ -0,0 +1,145 @@
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>
);
}
+91
View File
@@ -0,0 +1,91 @@
import type { SVGProps } from 'react';
// Inline SVG icon set replacing the raw unicode glyphs (✕ ▶ ⏸ ⚙ …), which
// rendered inconsistently across platforms and fonts. Sized in em so icons
// scale with the button font-size; color follows currentColor.
type IconProps = SVGProps<SVGSVGElement>;
function makeIcon(d: string) {
return function Icon(props: IconProps) {
return (
<svg
viewBox="0 0 24 24"
width="1em"
height="1em"
fill="currentColor"
aria-hidden="true"
focusable="false"
{...props}
>
<path d={d} />
</svg>
);
};
}
export const PlayIcon = makeIcon('M8 5v14l11-7z');
export const PauseIcon = makeIcon('M6 19h4V5H6v14zm8-14v14h4V5h-4z');
export const SkipNextIcon = makeIcon('M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z');
export const SkipPrevIcon = makeIcon('M6 6h2v12H6zm3.5 6l8.5 6V6l-8.5 6z');
export const RewindIcon = makeIcon(
'M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z'
);
export const ForwardIcon = makeIcon(
'M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z'
);
export const ShuffleIcon = makeIcon(
'M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z'
);
export const RepeatIcon = makeIcon(
'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z'
);
export const HeartIcon = makeIcon(
'M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z'
);
export const CloseIcon = makeIcon(
'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'
);
export const SearchIcon = makeIcon(
'M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z'
);
export const QueueIcon = makeIcon(
'M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zm14-10v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z'
);
export const StatsIcon = makeIcon(
'M5 9.2h3V19H5V9.2zM10.6 5h2.8v14h-2.8V5zm5.6 8H19v6h-2.8v-6z'
);
export const WatchIcon = makeIcon(
'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12zM9.5 8.5l7 3.5-7 3.5v-7z'
);
export const GearIcon = makeIcon(
'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
);
export const CodeIcon = makeIcon(
'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z'
);
export const FullscreenIcon = makeIcon(
'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z'
);
export const PowerIcon = makeIcon(
'M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z'
);
export const CrownIcon = makeIcon(
'M5 16L3 6l5.5 4L12 4l3.5 6L21 6l-2 10H5zm14 3c0 .55-.45 1-1 1H6c-.55 0-1-.45-1-1v-1h14v1z'
);
export const RefreshIcon = makeIcon(
'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z'
);
export const PlusIcon = makeIcon('M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z');
export const VolumeIcon = makeIcon(
'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z'
);
export const VolumeMuteIcon = makeIcon(
'M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z'
);
export const HelpIcon = makeIcon(
'M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z'
);
export const MenuIcon = makeIcon('M3 6h18v2H3V6zm0 5h18v2H3v-2zm0 5h18v2H3v-2z');
export const ExternalLinkIcon = makeIcon(
'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'
);
+58
View File
@@ -0,0 +1,58 @@
// Web UI localization, mirroring the bot's approach (EchoionCore i18n):
// English source strings are the keys; a missing entry falls back to the
// English original. Language resolution order matches the bot's
// CommandManager::resolveLanguage: the authenticated user's server-side
// preference (kv "lang:<uid>", shared with !lang) → local override →
// browser language → English.
import { Store, useStore } from '../lib/store';
import { ru } from './ru';
export type Language = 'en' | 'ru';
const LS_KEY = 'echoion.lang';
function initialLanguage(): Language {
// Not a browser (node test runner): no stored preference, use English.
if (typeof localStorage === 'undefined') return 'en';
const stored = localStorage.getItem(LS_KEY);
if (stored === 'en' || stored === 'ru') return stored;
return (navigator.language || '').toLowerCase().startsWith('ru')
? 'ru'
: 'en';
}
export const languageStore = new Store<{ language: Language }>({
language: initialLanguage(),
});
export function getLanguage(): Language {
return languageStore.get().language;
}
// `persist` distinguishes a user choice (saved locally, pushed to the
// server by the caller) from applying the server-side preference.
export function setLanguage(language: Language, persist = true) {
if (persist) localStorage.setItem(LS_KEY, language);
languageStore.set({ language });
document.documentElement.lang = language;
}
export function t(english: string): string {
if (getLanguage() === 'ru') return ru[english] ?? english;
return english;
}
// Translate a template, then substitute {0}, {1}, … arguments.
export function tf(english: string, ...args: Array<string | number>): string {
const template = t(english);
return template.replace(/\{(\d+)\}/g, (m, i) => {
const v = args[Number(i)];
return v === undefined ? m : String(v);
});
}
// Components subscribe so a language switch re-renders everything.
export function useLanguage(): Language {
return useStore(languageStore).language;
}
+302
View File
@@ -0,0 +1,302 @@
// Russian catalog for the web UI. Same philosophy as the bot's compiled-in
// RussianCatalog.inc: English source strings are the keys; a missing entry
// falls back to English. Placeholders are {0}, {1}, … (see tf()).
export const ru: Record<string, string> = {
// Sidebar / navigation
'Now Playing': 'Сейчас играет',
'Queue': 'Очередь',
'Search': 'Поиск',
'Library': 'Библиотека',
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Server & Admin': 'Сервер и админ',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
'Connect': 'Подключиться',
'Get token by nickname…': 'Получить токен по нику…',
'Send my token via TeamSpeak PM': 'Прислать мой токен личным сообщением в TeamSpeak',
'RPC token': 'RPC-токен',
'Logout': 'Выйти',
'ADMIN': 'АДМИН',
'DJ': 'DJ',
'connected': 'подключено',
'disconnected': 'отключено',
'error': 'ошибка',
'listening': 'слушают',
// View headers
'What Echoion is streaming to the channel': 'Что Echoion стримит в канал',
'Reorder and manage upcoming tracks': 'Управляйте порядком предстоящих треков',
'Find tracks across YouTube and Yandex Music': 'Ищите треки на YouTube и в Яндекс Музыке',
'Your favorites and saved playlists': 'Ваше избранное и сохранённые плейлисты',
'Playback history and server insights': 'История воспроизведения и статистика сервера',
'Synced viewing room — everyone in step': 'Синхронный просмотр — все в ногу',
'Manage subscribers and broadcast': 'Управление подписчиками и объявления',
'Connect to Echoion programmatically': 'Подключение к Echoion из кода',
// Now playing
'Nothing playing': 'Ничего не играет',
'Up Next': 'Далее',
'Open queue →': 'Открыть очередь →',
'Listening now': 'Сейчас слушают',
'Queue is empty': 'Очередь пуста',
'Vol': 'Гром.',
'Radio': 'Радио',
'Vote skip': 'Голос за пропуск',
'Vote skip {0}/{1}': 'Пропуск {0}/{1}',
'Shuffle': 'Перемешать',
'Restart track': 'Сначала',
'Play/Pause': 'Играть/Пауза',
'Repeat': 'Повтор',
'Favorite': 'В избранное',
'Vote to skip': 'Голосовать за пропуск',
'Force skip': 'Принудительный пропуск',
'Radio mode is admin-only — ask an admin or use !autoplay':
'Режим радио доступен только админам — попросите админа или используйте !autoplay',
'Radio mode on': 'Режим радио включён',
'Radio mode off': 'Режим радио выключен',
'Vote passed — track skipped': 'Голосование прошло — трек пропущен',
'Added to favorites': 'Добавлено в избранное',
'Removed from favorites': 'Удалено из избранного',
'Playing now': 'Играет сейчас',
'Lyrics': 'Текст песни',
'Show': 'Показать',
'Hide': 'Скрыть',
'Loading…': 'Загрузка…',
'No lyrics found': 'Текст не найден',
'Lyrics via': 'Текст из',
// Queue view
'Queue is empty — add something from Search': 'Очередь пуста — добавьте что-нибудь из Поиска',
'Shuffle queue': 'Перемешать очередь',
'Clear': 'Очистить',
'Clear the whole queue?': 'Очистить всю очередь?',
'Queue cleared': 'Очередь очищена',
'Play now': 'Играть сейчас',
'Remove': 'Удалить',
'{0} tracks': '{0} треков',
// Search
'Search YouTube and Yandex Music… or paste a URL': 'Ищите на YouTube и в Яндекс Музыке… или вставьте ссылку',
'All': 'Все',
'No results yet — search for something': 'Пока нет результатов — поищите что-нибудь',
'Searching “{0}”…': 'Ищем «{0}»…',
'Add to queue': 'Добавить в очередь',
'Added “{0}” to queue': '«{0}» добавлен в очередь',
'Save to favorites': 'Сохранить в избранное',
'Saved to favorites': 'Сохранено в избранное',
// Library
'Your favorites': 'Ваше избранное',
'Playlists': 'Плейлисты',
'Save queue as playlist': 'Сохранить очередь как плейлист',
'Authenticate to use favorites': 'Войдите, чтобы пользоваться избранным',
'No favorites yet — ♥ a track anywhere': 'Пока нет избранного — нажмите ♥ на любом треке',
'No playlists saved yet': 'Плейлистов пока нет',
'Playlist name (saves the current queue):': 'Название плейлиста (сохранит текущую очередь):',
'Playlist “{0}” saved': 'Плейлист «{0}» сохранён',
'Loading playlist “{0}”…': 'Загружаем плейлист «{0}»…',
'Saved from web UI': 'Сохранено из веб-интерфейса',
'Delete': 'Удалить',
'Delete playlist': 'Удалить плейлист',
'Delete playlist “{0}”? This cannot be undone.':
'Удалить плейлист «{0}»? Это нельзя отменить.',
'Playlist “{0}” deleted': 'Плейлист «{0}» удалён',
'Close': 'Закрыть',
'This playlist is empty': 'Плейлист пуст',
// Stats
'Recently played': 'Недавно игравшие',
'Top requesters': 'Топ заказчиков',
'Source split': 'Источники',
'Nothing played yet': 'Пока ничего не игралось',
'No requests logged yet': 'Запросов пока нет',
'Queue again': 'Заказать снова',
'Tracks played today': 'Треков за сегодня',
'Listening hours': 'Часов прослушивания',
'Queue additions': 'Добавлений в очередь',
'Skips': 'Пропусков',
'{0} all-time': '{0} за всё время',
'today': 'сегодня',
'{0}% skip rate': '{0}% пропусков',
'{0} requests': '{0} запросов',
// Watch together
'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': 'Загрузить',
'+ 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': 'Следующее',
'(you)': '(вы)',
'Buffering…': 'Буферизация…',
'In sync': 'Синхронно',
'Nothing queued — paste a URL and hit “+ Queue”': 'Очередь пуста — вставьте ссылку и нажмите «+ В очередь»',
'Remove from queue': 'Убрать из очереди',
'added by {0}': 'добавил {0}',
'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
'Subscribers': 'Подписчики',
'Announce…': 'Объявление…',
'Reload config': 'Перезагрузить конфиг',
'Restart web UI': 'Перезапустить веб-интерфейс',
'Stop and start the web server without touching the bot':
'Остановить и запустить веб-сервер, не трогая бота',
'Unsub all': 'Отписать всех',
'No subscribers': 'Нет подписчиков',
'Nobody online right now': 'Сейчас никого нет в сети',
'Online': 'В сети',
'Offline': 'Не в сети',
'Unsub': 'Отписать',
'Unsubscribe {0}?': 'Отписать {0}?',
'Unsubscribed {0}': '{0} отписан',
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
'Announcement sent': 'Объявление отправлено',
'Configuration reloaded': 'Конфигурация перезагружена',
'Restart the web interface? Everyone disconnects briefly.':
'Перезапустить веб-интерфейс? Все ненадолго отключатся.',
'Web interface restarting — this page will reconnect':
'Веб-интерфейс перезапускается — страница переподключится',
'Remove ALL subscriptions? This cannot be undone.':
'Удалить ВСЕ подписки? Это нельзя отменить.',
'All subscriptions removed': 'Все подписки удалены',
'Listening': 'Слушает',
'Audit log': 'Журнал аудита',
'Refresh': 'Обновить',
'No audit entries yet': 'Записей аудита пока нет',
'client #{0}': 'клиент №{0}',
// RPC view
'Connect programmatically': 'Программное подключение',
'Copy snippet': 'Скопировать пример',
'Snippet copied': 'Пример скопирован',
'Copy': 'Копировать',
'{0} copied': '{0} — скопировано',
'(authenticate first)': '(сначала войдите)',
// Auth / connection
'Signed in as {0}': 'Вы вошли как {0}',
'Welcome, {0}!': 'Добро пожаловать, {0}!',
'subscriber': 'подписчик',
'friend': 'друг',
'user': 'пользователь',
'Connection failed': 'Не удалось подключиться',
'Reconnected': 'Переподключено',
'Logged out': 'Вы вышли',
'Your TeamSpeak nickname (must be subscribed):': 'Ваш ник в TeamSpeak (нужна подписка):',
'Token sent via TeamSpeak PM': 'Токен отправлен личным сообщением в TeamSpeak',
'Request failed': 'Запрос не удался',
'Language': 'Язык',
'(untitled)': '(без названия)',
// Main-UI feature additions (items 9, 11, 14, 15, 18)
'Open original link': 'Открыть оригинальную ссылку',
'Watch video': 'Смотреть видео',
'Hide video': 'Скрыть видео',
'Compose announcement': 'Составить объявление',
'Send announcement': 'Отправить объявление',
'Cancel': 'Отмена',
'Preview': 'Предпросмотр',
'Nothing to preview yet': 'Пока нечего показать',
// Keyboard shortcuts
'Keyboard shortcuts': 'Горячие клавиши',
'Play / pause': 'Играть / пауза',
'Seek 5s': 'Перемотка 5с',
'Volume': 'Громкость',
'Skip / vote skip': 'Пропустить / голос за пропуск',
'Focus search': 'Перейти к поиску',
'This help': 'Эта справка',
// Mobile / unified player / cleanup update
'Menu': 'Меню',
'Back 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': 'Очистить очередь',
'Watch queue is full': 'Очередь просмотра заполнена',
'Watch queue is empty': 'Очередь просмотра пуста',
'Confirm': 'Подтвердить',
'OK': 'ОК',
'Save': 'Сохранить',
'Restart': 'Перезапустить',
'Remove all': 'Удалить все',
'Unsubscribe': 'Отписаться',
'Get token by nickname': 'Получить токен по нику',
'Nickname': 'Ник',
'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист',
// 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': 'Изменять может только ведущий',
};
+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();
})();
}
+65
View File
@@ -0,0 +1,65 @@
// Maps the numeric RpcMethod enum value carried by audit-log entries to a
// human name. This mirrors the declaration order of `enum class RpcMethod`
// in EchoionApi/include/echoion/api/rpc/RpcTypes.hpp, which is explicitly
// append-only ("numeric values are server-internal and only need to stay
// self-consistent") — so index == enum value. When you append a method to
// that enum, append it here too.
const RPC_METHOD_BY_INDEX: readonly string[] = [
'Play', // 0
'Pause',
'Resume',
'Stop',
'Skip',
'Seek',
'SetVolume',
'QueueTrack',
'RemoveFromQueue',
'ClearQueue',
'GetQueue', // 10
'MoveInQueue',
'GetCurrentTrack',
'GetTrackInfo',
'SearchTracks',
'LoadPlaylist',
'SavePlaylist',
'GetPlaylists',
'DeletePlaylist',
'GetConfig',
'SetConfig', // 20
'ReloadConfig',
'GetStatus',
'HotReload',
'Shutdown',
'Authenticate',
'Logout',
'GetAuditLog',
'ManageUsers',
'GetServerInfo',
'RequestLoginToken', // 30
'ValidateLoginToken',
'ToggleShuffle',
'ToggleRepeat',
'ShuffleQueue',
'GetPlaylist',
'GetHistory',
'GetStats',
'GetFavorites',
'AddFavorite',
'RemoveFavorite', // 40
'VoteSkip',
'Announce',
'GetAggregateStats',
'AuthenticateByAddress',
'RestartWebInterface',
'ToggleAutoplay',
'GetUserPrefs',
'SetUserPrefs',
'GetCustomEmojis',
'AddCustomEmoji', // 50
'RemoveCustomEmoji',
'GetLyrics',
];
export function auditMethodName(method: number): string {
return RPC_METHOD_BY_INDEX[method] ?? `Method #${method}`;
}
+84
View File
@@ -0,0 +1,84 @@
// Imperative custom dialogs (item 10) replacing the browser's native
// confirm()/prompt(), which can't be styled and look out of place. A single
// <DialogHost/> mounted at the app root renders the active request; the
// confirmDialog/promptDialog helpers return a promise that resolves when the
// user answers, so call sites read like `if (await confirmDialog(...))`.
import { Store } from './store';
export interface ConfirmRequest {
kind: 'confirm';
title: string;
message: string;
confirmLabel?: string;
cancelLabel?: string;
danger?: boolean;
resolve: (ok: boolean) => void;
}
export interface PromptRequest {
kind: 'prompt';
title: string;
message?: string;
placeholder?: string;
initial?: string;
confirmLabel?: string;
cancelLabel?: string;
resolve: (value: string | null) => void;
}
export type DialogRequest = ConfirmRequest | PromptRequest;
interface DialogState {
current: DialogRequest | null;
}
export const dialogStore = new Store<DialogState>({ current: null });
// Resolve the active dialog and clear it. Guards against double-resolve (e.g.
// clicking confirm and the backdrop in quick succession).
function settle(value: boolean | string | null) {
const req = dialogStore.get().current;
if (!req) return;
dialogStore.set({ current: null });
if (req.kind === 'confirm') {
req.resolve(value === true);
} else {
req.resolve(typeof value === 'string' ? value : null);
}
}
export function resolveConfirm(ok: boolean) {
settle(ok);
}
export function resolvePrompt(value: string | null) {
settle(value);
}
export function confirmDialog(
opts: Omit<ConfirmRequest, 'kind' | 'resolve'>
): Promise<boolean> {
// A pending dialog is cancelled if a new one opens (shouldn't overlap).
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<boolean>((resolve) => {
dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } });
});
}
export function promptDialog(
opts: Omit<PromptRequest, 'kind' | 'resolve'>
): Promise<string | null> {
const pending = dialogStore.get().current;
if (pending) {
if (pending.kind === 'confirm') pending.resolve(false);
else pending.resolve(null);
}
return new Promise<string | null>((resolve) => {
dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } });
});
}
+254
View File
@@ -0,0 +1,254 @@
import { describe, expect, it } from 'vitest';
import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols';
const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!;
const kodik = byName('kodik');
const playerjs = byName('playerjs');
const alloha = byName('alloha');
const vimeo = byName('vimeo');
const playerjsSpec = byName('player.js');
const rutube = byName('rutube');
const dailymotion = byName('dailymotion');
const vk = byName('vk');
describe('kodik parse', () => {
it('parses JSON-string time updates', () => {
expect(
kodik.parse(
JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 })
)
).toEqual({ kind: 'time', seconds: 42.5 });
});
it('parses duration and play/pause/ended state', () => {
expect(
kodik.parse({ key: 'kodik_player_duration_update', value: 1440 })
).toEqual({ kind: 'duration', seconds: 1440 });
expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' });
expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({
kind: 'pause',
});
expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({
kind: 'ended',
});
});
it('rejects everything else', () => {
expect(kodik.parse('garbage')).toBeNull();
expect(kodik.parse('{"broken json')).toBeNull();
expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull();
expect(kodik.parse(null)).toBeNull();
expect(kodik.parse(42)).toBeNull();
});
it('is hostname-pinned and seeks by reloading with start_from', () => {
expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe(
true
);
expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true);
expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false);
// start_from is set (overwritten) while signed params are preserved.
const seeked = kodik.reloadSeek!(
'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5',
42.9
);
expect(seeked).toContain('start_from=42');
expect(seeked).toContain('d_sign=abc');
expect(seeked).not.toContain('start_from=5');
});
});
describe('playerjs.com parse', () => {
it('parses object and JSON-string events', () => {
expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({
kind: 'time',
seconds: 12,
});
expect(
playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 }))
).toEqual({ kind: 'duration', seconds: 600 });
expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' });
});
it('does not lock on player.js-spec or unknown shapes', () => {
expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull();
expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull();
expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull();
});
it('normalizes quality, voiceover and subtitle capabilities', () => {
expect(
playerjs.parse({
event: 'qualities',
answer: [{ id: '720', name: '720p' }, '1080p'],
})
).toMatchObject({
kind: 'extraList',
control: { id: 'quality', scope: 'local' },
});
expect(
playerjs.parse({
event: 'audiotracks',
answer: { ru: 'Russian', en: 'English' },
})
).toMatchObject({
kind: 'extraList',
control: { id: 'audiotrack', scope: 'synced' },
});
expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({
kind: 'extraCurrent',
id: 'subtitle',
value: '1',
});
});
});
describe('alloha detection', () => {
it('pins known Alloha player hosts', () => {
expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true);
expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true);
expect(alloha.matchUrl!('https://example.com/player')).toBe(false);
});
});
describe('vimeo parse', () => {
it('parses timeupdate with bundled duration and the getDuration reply', () => {
expect(
vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } })
).toEqual({ kind: 'time', seconds: 10, duration: 200 });
expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({
kind: 'duration',
seconds: 200,
});
expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' });
});
it('does not lock on a playerjs.com message (has `answer`) or garbage', () => {
expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vimeo.parse('garbage')).toBeNull();
expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull();
});
it('matchUrl selects vimeo hosts only', () => {
expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true);
expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true);
expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false);
});
it('prepareUrl hides native chrome', () => {
const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123');
expect(p).toContain('controls=0');
expect(p).toContain('title=0');
});
});
describe('player.js (embedly spec) parse', () => {
it('parses context-tagged events', () => {
expect(
playerjsSpec.parse({
context: 'player.js',
event: 'timeupdate',
value: { seconds: 5, duration: 100 },
})
).toEqual({ kind: 'time', seconds: 5, duration: 100 });
expect(
playerjsSpec.parse({ context: 'player.js', event: 'pause' })
).toEqual({ kind: 'pause' });
expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual(
{ kind: 'hello' }
);
});
it('rejects messages without the player.js context', () => {
expect(playerjsSpec.parse({ event: 'play' })).toBeNull();
expect(playerjsSpec.parse('garbage')).toBeNull();
});
});
describe('rutube parse + matchUrl', () => {
it('parses player:* events', () => {
expect(
rutube.parse(
JSON.stringify({ type: 'player:currentTime', data: { time: 30 } })
)
).toEqual({ kind: 'time', seconds: 30 });
expect(
rutube.parse({ type: 'player:changeState', data: { state: 'playing' } })
).toEqual({ kind: 'play' });
expect(
rutube.parse({ type: 'player:durationChange', data: { duration: 90 } })
).toEqual({ kind: 'duration', seconds: 90 });
});
it('ignores foreign messages', () => {
expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull();
expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull();
expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true);
expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false);
});
});
describe('dailymotion parse + prepareUrl', () => {
it('parses classic querystring events', () => {
expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual(
{ kind: 'time', seconds: 12, duration: 240 }
);
expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' });
expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' });
expect(dailymotion.parse({ event: 'play' })).toBeNull();
});
it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => {
expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x'))
.toBe(true);
expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true);
const prepared = dailymotion.prepareUrl!(
'https://www.dailymotion.com/embed/video/x?foo=1'
);
expect(prepared).toContain('api=postMessage');
expect(prepared).toContain('controls=0');
expect(prepared).toContain('foo=1');
// idempotent
expect(dailymotion.prepareUrl!(prepared)).toBe(prepared);
});
});
describe('vk parse + prepareUrl', () => {
it('parses player_api events', () => {
expect(
vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 })
).toEqual({ kind: 'time', seconds: 8, duration: 60 });
expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({
kind: 'play',
});
expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({
kind: 'pause',
});
});
it('ignores foreign messages and injects js_api=1', () => {
expect(vk.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true);
expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true);
expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain(
'js_api=1'
);
});
});
describe('registry order + prepareEmbedUrl', () => {
it('generic (content-detected) set is player.js then playerjs', () => {
expect(
EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name)
).toEqual(['player.js', 'playerjs']);
});
it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => {
expect(
prepareEmbedUrl('https://www.dailymotion.com/embed/video/x')
).toContain('api=postMessage');
expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe(
'https://kodik.info/seria/1/hash/720p'
);
});
});
+972
View File
@@ -0,0 +1,972 @@
// Adapters for postMessage-controllable embed players in the Watch view.
//
// A generic iframe can only be driven if the player inside exposes a
// postMessage API — everything else stays view-only by browser design.
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
// commands {key:'kodik_player_api', value:{method}}.
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
// params (prepareUrl) and their command/event shapes are community-
// documented — flagged VERIFY, one-line fixes if a live embed differs.
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
// {event, answer} events.
// Shapes marked VERIFY are community-documented, not official; dev builds
// console.debug every unrecognized frame message to reverse-engineer them.
//
// Detection: for a hostname-matched player only that protocol is probed;
// otherwise the generic set is probed until one `parse` recognizes a message
// and locks the adapter. On timeout the embed is uncontrollable and the
// caller keeps today's host-driven view-only behavior.
export interface EmbedAdapter {
protocol: string;
// True for players (Kodik) driven by reloading the iframe rather than
// postMessage commands: the caller should avoid drift-reconcile churn and
// not expect pause to work.
reloadBased: boolean;
play(): void;
pause(): void;
seekMs(ms: number): void;
setVolume(v01: number): void; // 0..1
positionMs(): number;
durationMs(): number;
paused(): boolean;
extras(): PlayerExtraControl[];
setExtra(id: string, value: string): void;
destroy(): void;
}
export interface ExtraControlOption {
value: string;
label: string;
}
export interface PlayerExtraControl {
id: string;
label: string;
kind: 'select' | 'button';
options: ExtraControlOption[];
current: string | null;
scope: 'local' | 'synced';
}
// Fired only for events NOT caused by our own commands (see suppression
// below) — i.e. gestures made inside the embed UI, which the host must relay
// to the room.
export interface EmbedCallbacks {
onPlay(positionMs: number): void;
onPause(positionMs: number): void;
onSeek(positionMs: number): void;
onDurationChange(durationMs: number): void;
onEnded(): void;
onExtraControls(controls: PlayerExtraControl[]): void;
}
export type EmbedEvent =
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
// VK) that bundle it into their timeupdate payload.
| { kind: 'time'; seconds: number; duration?: number }
| { kind: 'duration'; seconds: number }
| { kind: 'play' }
| { kind: 'pause' }
| { kind: 'ended' }
| { kind: 'extraList'; control: PlayerExtraControl }
| { kind: 'extraCurrent'; id: string; value: string }
// Recognized the protocol but the event carries no state we track; enough
// to lock detection.
| { kind: 'hello' };
export interface ProtocolDef {
name: string;
// Hostname-based selection: when a URL matches, only this protocol is
// probed (skips content-based detection). Left undefined for generic
// protocols detected purely by the messages they emit (kodik, player.js).
matchUrl?(url: string): boolean;
// Inject opt-in query params the player needs before the iframe loads
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
prepareUrl?(url: string): string;
// Some players (Kodik) expose no postMessage command API — the only way to
// seek is to reload the iframe at a start offset. When present, the adapter
// seeks by setting frame.src to this URL instead of posting a command.
reloadSeek?(currentSrc: string, seconds: number): string;
probe(win: Window): void;
parse(data: unknown): EmbedEvent | null;
play(win: Window): void;
pause(win: Window): void;
seek(win: Window, seconds: number): void;
volume(win: Window, v01: number): void;
probeExtras?(win: Window): void;
setExtra?(win: Window, id: string, value: string): void;
staticExtras?(url: string): PlayerExtraControl[];
}
// Embeds are served from many mirror domains (esp. Kodik), so the target
// origin can't be pinned; we never trust incoming data beyond parsing known
// shapes into numbers.
function post(win: Window, msg: unknown) {
try {
win.postMessage(msg, '*');
} catch {
/* frame navigating/gone */
}
}
const asNumber = (v: unknown): number =>
typeof v === 'number' ? v : Number(v);
// Embed URLs are absolute, so no base is needed; guard `location` so the
// helpers also work under the node test runner.
const baseHref = (): string | undefined =>
typeof location !== 'undefined' ? location.href : undefined;
function hostOf(url: string): string {
try {
return new URL(url, baseHref()).hostname.toLowerCase();
} catch {
return '';
}
}
function isHostOrSubdomain(host: string, domain: string): boolean {
return host === domain || host.endsWith(`.${domain}`);
}
function withParams(url: string, params: Record<string, string>): string {
try {
const u = new URL(url, baseHref());
for (const [k, v] of Object.entries(params)) {
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
}
return u.toString();
} catch {
return url;
}
}
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
// d_sign/ref_sign params).
function setParam(url: string, key: string, value: string): string {
try {
const u = new URL(url, baseHref());
u.searchParams.set(key, value);
return u.toString();
} catch {
return url;
}
}
// Normalize an object-or-JSON-string payload into a plain object, or null.
function asObj(data: unknown): Record<string, unknown> | null {
let obj: unknown = data;
if (typeof data === 'string') {
const s = data.trim();
if (!s.startsWith('{') && !s.startsWith('[')) return null;
try {
obj = JSON.parse(s);
} catch {
return null;
}
}
return obj && typeof obj === 'object'
? (obj as Record<string, unknown>)
: null;
}
function toOptions(value: unknown): ExtraControlOption[] {
const entries = Array.isArray(value)
? value.map((item, index) => [String(index), item] as const)
: value && typeof value === 'object'
? Object.entries(value as Record<string, unknown>)
: [];
return entries.flatMap(([fallback, item]) => {
if (item && typeof item === 'object') {
const option = item as Record<string, unknown>;
const raw = option.value ?? option.id ?? option.index ?? fallback;
const label = option.label ?? option.name ?? option.title ?? raw;
return [{ value: String(raw), label: String(label) }];
}
return item == null
? []
: [{ value: fallback, label: String(item) }];
});
}
function extraControl(
id: string,
label: string,
scope: PlayerExtraControl['scope'],
options: ExtraControlOption[],
current: string | null = null
): PlayerExtraControl {
return { id, label, scope, options, current, kind: 'select' };
}
const kodik: ProtocolDef = {
name: 'kodik',
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
// locks as `kodik` and never falls back to view-only.
matchUrl: (url) => {
const host = hostOf(url);
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
.some((domain) => isHostOrSubdomain(host, domain));
},
// Kodik has NO postMessage command API — the only way to seek is to reload
// the iframe at a start offset (preserving its signed params). start_from
// auto-resumes playback from that second.
reloadSeek: (src, seconds) =>
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
probe(win) {
// Community-documented; harmless if ignored by the player.
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.includes('kodik_player')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as { key?: unknown; value?: unknown } | null;
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
return null;
}
const n = asNumber(m.value);
switch (m.key) {
case 'kodik_player_time_update':
case 'kodik_player_current_time':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'kodik_player_duration_update':
case 'kodik_player_duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'kodik_player_play':
return { kind: 'play' };
case 'kodik_player_pause':
return { kind: 'pause' };
case 'kodik_player_video_ended':
return { kind: 'ended' };
default:
// Unmapped kodik_player_* event — still unambiguously Kodik.
return { kind: 'hello' };
}
},
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
seek: (win, seconds) =>
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
volume: (win, v01) =>
post(win, {
key: 'kodik_player_api',
value: { method: 'change_volume', volume: v01 },
}),
};
const playerjs: ProtocolDef = {
name: 'playerjs',
probe(win) {
post(win, { api: 'duration' });
post(win, { api: 'time' });
},
probeExtras(win) {
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
post(win, { api });
}
},
staticExtras() {
return [
extraControl(
'speed',
'Speed',
'synced',
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
value: String(speed),
label: `${speed}×`,
})),
'1'
),
];
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.startsWith('{')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as
| { event?: unknown; answer?: unknown; context?: unknown }
| null;
if (!m || typeof m.event !== 'string') return null;
// A {context:'player.js'} message belongs to the embedly spec adapter,
// not this one.
if (m.context === 'player.js') return null;
const n = asNumber(m.answer);
// Only lock on events Playerjs actually emits — a bare {event:...}
// could belong to some other player's protocol.
switch (m.event) {
case 'qualities':
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.answer)
),
};
case 'audiotracks':
return {
kind: 'extraList',
control: extraControl(
'audiotrack',
'Voiceover',
'synced',
toOptions(m.answer)
),
};
case 'subtitles':
return {
kind: 'extraList',
control: extraControl(
'subtitle',
'Subtitles',
'local',
[
{ value: '-1', label: 'Off' },
...toOptions(m.answer),
]
),
};
case 'episodes':
return {
kind: 'extraList',
control: extraControl(
'episode',
'Episode',
'synced',
toOptions(m.answer)
),
};
case 'quality':
case 'audiotrack':
case 'subtitle':
case 'speed':
case 'episode':
return {
kind: 'extraCurrent',
id: m.event,
value: String(m.answer ?? ''),
};
case 'time':
case 'updatetime':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'end':
case 'ended':
return { kind: 'ended' };
case 'init':
case 'inited':
case 'ready':
case 'volume':
return { kind: 'hello' };
default:
return null;
}
},
play: (win) => post(win, { api: 'play' }),
pause: (win) => post(win, { api: 'pause' }),
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
setExtra: (win, id, value) => {
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
return;
}
post(win, { api: id, set: value });
},
};
const alloha: ProtocolDef = {
...playerjs,
name: 'alloha',
matchUrl: (url) =>
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
(domain) => isHostOrSubdomain(hostOf(url), domain)
),
};
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
// from playerjs.com by carrying `data`, not `answer`.
const vimeo: ProtocolDef = {
name: 'vimeo',
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
prepareUrl: (url) =>
withParams(url, {
controls: '0',
title: '0',
byline: '0',
portrait: '0',
}),
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
}
post(win, JSON.stringify({ method: 'getDuration' }));
},
probeExtras(win) {
post(win, JSON.stringify({ method: 'getQualities' }));
},
parse(data) {
const m = asObj(data);
if (!m) return null;
if (m.method === 'getDuration') {
const n = asNumber(m.value);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
if (m.method === 'getQualities') {
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.value)
),
};
}
if (typeof m.event !== 'string') return null;
if ('answer' in m) return null; // that's a playerjs.com message
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(d.seconds);
const dur = asNumber(d.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
case 'finish':
return { kind: 'ended' };
case 'ready':
case 'loaded':
return { kind: 'hello' };
default:
return null; // bare {event} without vimeo markers → not ours
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) =>
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
setExtra: (w, id, value) => {
if (id === 'quality') {
post(w, JSON.stringify({ method: 'setQuality', value }));
}
},
};
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
const PJS = { context: 'player.js', version: '0.0.11' } as const;
const playerjsSpec: ProtocolDef = {
name: 'player.js',
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, {
...PJS,
method: 'addEventListener',
listener: `ec_${ev}`,
value: ev,
});
}
},
parse(data) {
const m = asObj(data);
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
return null;
}
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(v.seconds);
const dur = asNumber(v.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // any context:'player.js' event is ours
}
},
play: (w) => post(w, { ...PJS, method: 'play' }),
pause: (w) => post(w, { ...PJS, method: 'pause' }),
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
};
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
const rutube: ProtocolDef = {
name: 'rutube',
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
probe(win) {
// Rutube emits events only after an explicit subscribe. VERIFY payload.
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
},
parse(data) {
const m = asObj(data);
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
return null;
}
const d = (m.data ?? {}) as {
time?: unknown;
duration?: unknown;
state?: unknown;
};
switch (m.type) {
case 'player:currentTime': {
const n = asNumber(d.time);
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
}
case 'player:durationChange': {
const n = asNumber(d.duration);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
case 'player:changeState': {
const st = String(d.state);
if (st === 'playing') return { kind: 'play' };
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
if (st === 'ended') return { kind: 'ended' };
return { kind: 'hello' };
}
default:
return { kind: 'hello' }; // player:* is unambiguously Rutube
}
},
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
seek: (w, s) =>
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
volume: (w, v) =>
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
};
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
const dailymotion: ProtocolDef = {
name: 'dailymotion',
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
// (our overlay bar drives playback instead).
prepareUrl: (url) =>
withParams(url, {
api: 'postMessage',
controls: '0',
'ui-start-screen-info': 'false',
'ui-logo': 'false',
}),
probe() {
/* classic embed auto-emits once api=postMessage is set */
},
parse(data) {
if (typeof data !== 'string' || !data.includes('event=')) return null;
const p = new URLSearchParams(data);
const ev = p.get('event');
if (!ev) return null;
const sec = Number(p.get('time'));
const dur = Number(p.get('duration'));
switch (ev) {
case 'timeupdate':
case 'progress':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'durationchange':
return isFinite(dur) && dur > 0
? { kind: 'duration', seconds: dur }
: { kind: 'hello' };
case 'play':
case 'playing':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'video_end':
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' };
}
},
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
volume: (w, v) =>
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
};
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
const vk: ProtocolDef = {
name: 'vk',
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
prepareUrl: (url) => withParams(url, { js_api: '1' }),
probe(win) {
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
},
parse(data) {
const m = asObj(data);
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
return null;
}
const sec = asNumber(m.time ?? m.position);
const dur = asNumber(m.duration);
switch (m.event) {
case 'timeupdate':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'started':
case 'resumed':
return { kind: 'play' };
case 'paused':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
};
// Hostname-selected protocols first (they're picked by URL, never by content);
// then the generic set probed by the messages they emit — kodik first (its
// keys are unambiguous), the embedly spec before the looser playerjs.com.
// Exported for the parse unit tests.
export const EMBED_PROTOCOLS: ProtocolDef[] = [
kodik,
alloha,
vimeo,
rutube,
dailymotion,
vk,
playerjsSpec,
playerjs,
];
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
export function prepareEmbedUrl(url: string): string {
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
// Signed players such as Kodik depend on their own origin for scripts,
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
// Echoion controls them only through their postMessage surface.
return p?.prepareUrl ? p.prepareUrl(url) : url;
}
const PROBE_INTERVAL_MS = 750;
// Commands are echoed back as events by the player; ignore relay callbacks
// for this long after each command we send.
const SUPPRESS_MS = 800;
// A time event this far off the extrapolated position counts as a user seek.
const SEEK_JUMP_SEC = 2.5;
// Minimum gap between reload-based (Kodik) iframe reloads.
const RELOAD_DEBOUNCE_MS = 4000;
export function detectEmbedAdapter(
frame: HTMLIFrameElement,
cb: EmbedCallbacks,
timeoutMs = 5000
): Promise<EmbedAdapter | null> {
return new Promise((resolve) => {
let locked: ProtocolDef | null = null;
// A hostname-matched player is probed alone; otherwise probe the
// generic (content-detected) set. frame.src is the prepared URL.
const matched =
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
const probeSet = matched
? [matched]
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
// Normalized player state. Embeds push time updates rather than expose
// getters, so position is the last event extrapolated by wall clock.
let lastTimeSec = 0;
let lastTimeAt = performance.now();
let durationSec = 0;
let playing = false;
let suppressUntil = 0;
const extraControls = new Map<string, PlayerExtraControl>();
const positionMs = () =>
Math.floor(
(lastTimeSec +
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
1000
);
const suppressed = () => performance.now() < suppressUntil;
const applyEvent = (ev: EmbedEvent) => {
switch (ev.kind) {
case 'time': {
const jumped =
Math.abs(ev.seconds - positionMs() / 1000) >
SEEK_JUMP_SEC;
// Advancing time implies playing even when the protocol
// never sends an explicit play event.
const advancing = ev.seconds > lastTimeSec + 0.05;
lastTimeSec = ev.seconds;
lastTimeAt = performance.now();
// Some protocols bundle duration into the time event.
if (
ev.duration != null &&
Math.abs(ev.duration - durationSec) > 0.5
) {
durationSec = ev.duration;
cb.onDurationChange(Math.floor(ev.duration * 1000));
}
if (jumped && !suppressed()) {
cb.onSeek(Math.floor(ev.seconds * 1000));
}
if (!playing && advancing) {
playing = true;
if (!suppressed()) cb.onPlay(positionMs());
}
break;
}
case 'duration':
if (Math.abs(ev.seconds - durationSec) > 0.5) {
durationSec = ev.seconds;
cb.onDurationChange(Math.floor(ev.seconds * 1000));
}
break;
case 'play':
if (!playing) {
playing = true;
lastTimeAt = performance.now();
if (!suppressed()) cb.onPlay(positionMs());
}
break;
case 'pause':
if (playing) {
lastTimeSec = positionMs() / 1000;
playing = false;
if (!suppressed()) cb.onPause(positionMs());
}
break;
case 'ended':
playing = false;
cb.onEnded();
break;
case 'extraList':
if (ev.control.options.length > 0) {
extraControls.set(ev.control.id, ev.control);
cb.onExtraControls([...extraControls.values()]);
}
break;
case 'extraCurrent': {
const control = extraControls.get(ev.id);
if (control && control.current !== ev.value) {
extraControls.set(ev.id, { ...control, current: ev.value });
cb.onExtraControls([...extraControls.values()]);
}
break;
}
case 'hello':
break;
}
};
// contentWindow is read live on every use: it changes when the frame
// navigates, while ev.source comparison below stays valid because the
// browsing context object is stable for the life of the element.
const win = () => frame.contentWindow;
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
for (const control of p.staticExtras?.(frame.src) ?? []) {
extraControls.set(control.id, control);
}
if (extraControls.size > 0) {
cb.onExtraControls([...extraControls.values()]);
}
const probeExtras = () => {
const current = win();
if (current) p.probeExtras?.(current);
};
probeExtras();
const extraProbeTimers = [1500, 3000].map((delay) =>
window.setTimeout(probeExtras, delay)
);
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
// debounced so drift-reconcile can't spam reloads (each reload
// re-buffers and may replay an ad).
let lastReloadAt = 0;
const reloadTo = (sec: number) => {
const now = performance.now();
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
lastReloadAt = now;
suppressUntil = now + SUPPRESS_MS;
lastTimeSec = Math.max(0, sec);
lastTimeAt = now;
playing = true; // start_from auto-resumes
frame.src = p.reloadSeek!(frame.src, sec);
};
return {
protocol: p.name,
reloadBased: !!p.reloadSeek,
play() {
// Commands update state optimistically so positionMs()/paused()
// reflect intent immediately — otherwise the 3s sync heartbeat
// would fight the slow embed acknowledgement.
suppressUntil = performance.now() + SUPPRESS_MS;
playing = true;
lastTimeAt = performance.now();
if (p.reloadSeek) {
// No play command — resume by reloading at the current spot.
reloadTo(lastTimeSec);
return;
}
const w = win();
if (w) p.play(w);
},
pause() {
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = positionMs() / 1000;
playing = false;
// Reload-based players (Kodik) have no pause — best-effort no-op.
if (p.reloadSeek) return;
const w = win();
if (w) p.pause(w);
},
seekMs(ms: number) {
if (p.reloadSeek) {
reloadTo(ms / 1000);
return;
}
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = ms / 1000;
lastTimeAt = performance.now();
const w = win();
if (w) p.seek(w, ms / 1000);
},
setVolume(v01: number) {
const w = win();
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
},
extras: () => [...extraControls.values()],
setExtra(id, value) {
const control = extraControls.get(id);
if (!control || !p.setExtra) return;
suppressUntil = performance.now() + 1500;
extraControls.set(id, { ...control, current: value });
cb.onExtraControls([...extraControls.values()]);
const current = win();
if (current) p.setExtra(current, id, value);
},
positionMs,
durationMs: () => Math.floor(durationSec * 1000),
paused: () => !playing,
destroy() {
window.removeEventListener('message', handler);
clearInterval(probeTimer);
clearTimeout(giveUp);
for (const timer of extraProbeTimers) clearTimeout(timer);
},
};
};
const handler = (ev: MessageEvent) => {
if (ev.source !== frame.contentWindow) return;
if (locked) {
const e = locked.parse(ev.data);
if (e) applyEvent(e);
else if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
return;
}
for (const p of probeSet) {
const e = p.parse(ev.data);
if (e) {
locked = p;
clearInterval(probeTimer);
clearTimeout(giveUp);
applyEvent(e);
resolve(makeAdapter(p));
return;
}
}
if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
};
window.addEventListener('message', handler);
const sendProbes = () => {
const w = win();
if (!w || locked) return;
for (const p of probeSet) p.probe(w);
};
// The inner player may boot slowly; keep probing until lock or timeout.
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
frame.addEventListener('load', sendProbes);
sendProbes();
const giveUp = setTimeout(() => {
if (locked) return;
window.removeEventListener('message', handler);
clearInterval(probeTimer);
resolve(null);
}, timeoutMs);
});
}
+96
View File
@@ -0,0 +1,96 @@
// Emoji support for watch chat and reactions (item 16). A curated Unicode set
// across categories (dependency-free — no multi-MB emoji-data bundle), plus
// admin-managed custom image emojis served at /emoji/<name> and referenced by
// :name: shortcodes. Recently-used emoji are remembered locally.
import { Store } from './store';
import { rpc } from './rpc';
export interface CustomEmoji {
name: string;
mime: string;
}
export const emojiStore = new Store<{
custom: CustomEmoji[];
recent: string[]; // unicode chars or :shortcode:
}>({
custom: [],
recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'),
});
export async function loadCustomEmojis() {
try {
const res = await rpc.call<{ emojis?: CustomEmoji[] }>(
'GetCustomEmojis'
);
emojiStore.set({ custom: (res && res.emojis) || [] });
} catch {
/* not connected / not authed — leave empty */
}
}
export function rememberEmoji(token: string) {
const recent = [
token,
...emojiStore.get().recent.filter((r) => r !== token),
].slice(0, 24);
emojiStore.set({ recent });
localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent));
}
// Curated categories of common Unicode emoji.
export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [
{
label: 'Smileys',
emoji: [
'😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰',
'😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞',
'😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶',
'😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒',
],
},
{
label: 'Gestures',
emoji: [
'👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌',
'👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝',
],
},
{
label: 'Hearts',
emoji: [
'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️',
'💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥',
],
},
{
label: 'Fun',
emoji: [
'🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸',
'⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️',
],
},
];
// Render a chat message: plain text with :name: custom-emoji shortcodes
// replaced by <img> tags. Returns React nodes (text is auto-escaped by React).
export function renderChatText(text: string): (string | EmojiToken)[] {
const out: (string | EmojiToken)[] = [];
const re = /:([a-z0-9_]{1,32}):/g;
const custom = new Set(emojiStore.get().custom.map((c) => c.name));
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (!custom.has(m[1])) continue;
if (m.index > last) out.push(text.slice(last, m.index));
out.push({ emojiName: m[1] });
last = m.index + m[0].length;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
export interface EmojiToken {
emojiName: string;
}
+64
View File
@@ -0,0 +1,64 @@
// Presentation helpers shared across views — ported from web/app.js.
import type { Track } from './types';
export function fmtMs(ms: number | undefined | null): string {
const s = Math.max(0, Math.floor((ms || 0) / 1000));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
export function cover(seed: number): string {
const h = (seed * 47) % 360;
const h2 = (h + 40) % 360;
return `linear-gradient(135deg, hsl(${h} 55% 42%), hsl(${h2} 60% 26%))`;
}
export function seedOf(t: Track | null | undefined): number {
const s = (t && (t.id || t.title)) || '?';
let n = 0;
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
return n;
}
// Prefer source-provided artwork; otherwise derive the YouTube thumbnail from
// the video id (covers tracks stored before thumbnails were persisted).
export function thumbFor(t: Track | null | undefined): string | null {
if (!t) return null;
if (t.thumbnailUrl) return t.thumbnailUrl;
const m = (t.url || '').match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return `https://i.ytimg.com/vi/${m[1]}/mqdefault.jpg`;
if (t.source === 1 && /^[\w-]{11}$/.test(t.id || '')) {
return `https://i.ytimg.com/vi/${t.id}/mqdefault.jpg`;
}
return null;
}
// TrackSource enum: 1 = YouTube, 6 = Yandex (see EchoionApi TrackTypes.hpp).
export function sourceInfo(
t: Track | null | undefined
): { label: string; cls: string } | null {
const url = (t && t.url) || '';
if ((t && t.source === 6) || url.includes('yandex')) {
return { label: 'YANDEX', cls: 'src-badge yandex' };
}
if ((t && t.source === 1) || url.includes('youtu')) {
return { label: 'YOUTUBE', cls: 'src-badge' };
}
return null;
}
export function avatarColor(name: string | undefined | null): string {
let n = 0;
const s = name || '';
for (let i = 0; i < s.length; i++) n = (n * 31 + s.charCodeAt(i)) & 0xffff;
const h = n % 360;
return `linear-gradient(135deg, hsl(${h} 60% 55%), hsl(${(h + 45) % 360} 55% 40%))`;
}
export function coverStyle(t: Track | null | undefined): string {
const thumb = thumbFor(t);
if (thumb) return `url("${thumb}") center/cover`;
if (t) return cover(seedOf(t));
return 'linear-gradient(135deg, #2a1a4a, #0d0d1f)';
}
+31
View File
@@ -0,0 +1,31 @@
// "Open original link" (item 18): a per-row external-link button that opens
// the track's real source page in a new tab. Prefers the canonical original
// URL (the long, expanded source page) over the shortened faumaray.ru link,
// so users land on the real source rather than a redirector. Never the
// CDN/stream URL (the DTO doesn't expose it).
import type { TrackAction } from '../components/TrackRow';
import type { Track } from './types';
import { ExternalLinkIcon } from '../components/icons';
import { t } from '../i18n';
export function originalLinkUrl(track: Track): string | null {
return track.url || track.shortenedUrl || null;
}
export function openOriginal(track: Track) {
const url = originalLinkUrl(track);
if (url) window.open(url, '_blank', 'noopener');
}
// A TrackRow action for the link, or null when the track has no openable URL.
// Rendered as a dedicated icon button (not a whole-row click, which would
// fight drag-and-drop and the other row actions).
export function originalLinkAction(track: Track): TrackAction | null {
if (!originalLinkUrl(track)) return null;
return {
icon: <ExternalLinkIcon />,
title: t('Open original link'),
onClick: () => openOriginal(track),
};
}
+85
View File
@@ -0,0 +1,85 @@
// Bridges playback state to the OS via the Media Session API, so hardware
// media keys and the lockscreen/notification controls (phone especially)
// drive the bot. Metadata + position follow appStore; the action handlers
// map straight onto the RPC calls the UI already uses.
import { appStore, safeCall } from './app';
import { thumbFor } from './format';
function skip() {
const id = appStore.get().identity;
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initMediaSession() {
if (!('mediaSession' in navigator)) return;
const ms = navigator.mediaSession;
ms.setActionHandler('play', () => void safeCall('Resume'));
ms.setActionHandler('pause', () => void safeCall('Pause'));
ms.setActionHandler('previoustrack', () =>
void safeCall('Seek', { position: 0 })
);
ms.setActionHandler('nexttrack', () => skip());
ms.setActionHandler('seekto', (d) => {
if (typeof d.seekTime === 'number') {
safeCall('Seek', { position: Math.round(d.seekTime * 1000) });
}
});
ms.setActionHandler('seekbackward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
safeCall('Seek', { position: Math.max(0, s.positionMs - by) });
});
ms.setActionHandler('seekforward', (d) => {
const by = (d.seekOffset || 10) * 1000;
const s = appStore.get();
const dur = s.durationMs || s.positionMs + by;
safeCall('Seek', { position: Math.min(dur, s.positionMs + by) });
});
let lastKey = '';
appStore.subscribe(() => {
const s = appStore.get();
const track = s.current;
const st = s.status;
ms.playbackState = !track
? 'none'
: st && st.isPlaying && !st.isPaused
? 'playing'
: 'paused';
// Rebuild metadata only when the track changes.
const key = track ? track.url || track.title || '' : '';
if (track && key !== lastKey) {
lastKey = key;
const artwork = thumbFor(track);
ms.metadata = new MediaMetadata({
title: track.title || 'Echoion',
artist: track.artist || '',
album: 'Echoion',
artwork: artwork
? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }]
: [],
});
} else if (!track) {
lastKey = '';
ms.metadata = null;
}
// Keep the scrubber in sync where supported.
if (typeof ms.setPositionState === 'function' && s.durationMs > 0) {
try {
ms.setPositionState({
duration: s.durationMs / 1000,
position: Math.min(s.positionMs, s.durationMs) / 1000,
playbackRate: 1,
});
} catch {
/* invalid position state (e.g. position > duration) — ignore */
}
}
});
}
+15
View File
@@ -0,0 +1,15 @@
const DRIFT_THRESHOLD_SECONDS = 3;
const SEEK_COOLDOWN_MS = 5000;
export function shouldCorrectVideoDrift(
playerState: number,
currentSeconds: number,
targetSeconds: number,
millisSinceSeek: number
): boolean {
return (
playerState === 1 &&
millisSinceSeek >= SEEK_COOLDOWN_MS &&
Math.abs(currentSeconds - targetSeconds) > DRIFT_THRESHOLD_SECONDS
);
}
+50
View File
@@ -0,0 +1,50 @@
// Tiny hash router: keeps the active view in the URL so views are
// bookmarkable and the browser back/forward buttons work. No dependency —
// the app has a single flat set of views. The Watch view owns its own
// `#watch/<room>` hash (see watch.ts joinRoom/leaveRoom); this router only
// reads the room from it to auto-join a deep-linked room.
import { appStore, type ViewName } from './app';
import { joinRoom, watchStore } from './watch';
const VIEWS: readonly ViewName[] = [
'now',
'queue',
'search',
'library',
'stats',
'watch',
'server',
'rpc',
];
// The view named by the current hash, defaulting to `now`. Handles both
// `#queue` and the watch form `#watch/<room>`.
export function viewFromHash(): ViewName {
const raw = location.hash.replace(/^#\/?/, '');
const base = raw.split(/[/?]/)[0];
return (VIEWS as readonly string[]).includes(base)
? (base as ViewName)
: 'now';
}
function roomFromHash(): string | null {
const m = location.hash.match(/^#watch\/([\w-]{1,48})/);
return m ? m[1] : null;
}
export function initRouter() {
// Initial view comes from the hash (refresh / shared link).
appStore.set({ view: viewFromHash() });
window.addEventListener('hashchange', () => {
const view = viewFromHash();
appStore.set({ view });
// Auto-join a room that appears in the hash (pasted link, or
// back/forward onto a different room). Leaving is always explicit.
if (view === 'watch') {
const room = roomFromHash();
if (room && room !== watchStore.get().room) joinRoom(room);
}
});
}
+142
View File
@@ -0,0 +1,142 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { RpcClient } from './rpc';
// A minimal fake WebSocket that records sent frames and lets the test push
// server frames back. Installed as the global before each RpcClient is made.
class FakeWebSocket {
static OPEN = 1;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.OPEN;
sent: string[] = [];
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
onmessage: ((ev: { data: string }) => void) | null = null;
constructor(public url: string) {
FakeWebSocket.instances.push(this);
queueMicrotask(() => this.onopen && this.onopen());
}
send(data: string) {
this.sent.push(data);
}
close() {
this.readyState = 3;
this.onclose && this.onclose();
}
receive(obj: unknown) {
this.onmessage && this.onmessage({ data: JSON.stringify(obj) });
}
}
function installFakes() {
FakeWebSocket.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);
// /config.json → same-origin /rpc bridge.
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ json: async () => ({ rpcUrl: '/rpc' }) }))
);
vi.stubGlobal('location', {
protocol: 'http:',
host: 'bot.local',
hostname: 'bot.local',
});
}
afterEach(() => vi.unstubAllGlobals());
describe('RpcClient wire contract', () => {
it('encodes method as the enum name and params as a JSON string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.call('Seek', { position: 4200 });
expect(ws.sent).toHaveLength(1);
const frame = JSON.parse(ws.sent[0]);
expect(frame.method).toBe('Seek');
// params must be a JSON-encoded *string*, not a nested object.
expect(typeof frame.params).toBe('string');
expect(JSON.parse(frame.params)).toEqual({ position: 4200 });
expect(frame.id).toBe(1);
});
it('attaches the auth token once set', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
rpc.token = 'tok-abc';
rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
expect(frame.authToken).toBe('tok-abc');
});
it('resolves a call by requestId and JSON-decodes the result string', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('GetStatus');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: true,
result: JSON.stringify({ isPlaying: true, volume: 0.5 }),
});
await expect(p).resolves.toEqual({ isPlaying: true, volume: 0.5 });
});
it('rejects with the decoded error payload', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const p = rpc.call('Skip');
const frame = JSON.parse(ws.sent[0]);
ws.receive({
requestId: frame.id,
success: false,
error: JSON.stringify({ code: 7, message: 'DJ required' }),
});
await expect(p).rejects.toMatchObject({
code: 7,
message: 'DJ required',
});
});
it('dispatches notifications with the data string decoded', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: unknown[] = [];
rpc.on('playback.position', (d) => seen.push(d));
ws.receive({
event: 'playback.position',
data: JSON.stringify({ position: 1000, duration: 200000 }),
});
expect(seen).toEqual([{ position: 1000, duration: 200000 }]);
});
it('fires the wildcard listener with event name and data', async () => {
installFakes();
const rpc = new RpcClient();
await rpc.connect();
const ws = FakeWebSocket.instances[0];
const seen: Array<[unknown, unknown]> = [];
rpc.on('*', (event, data) => seen.push([event, data]));
ws.receive({
event: 'queue.updated',
data: JSON.stringify({ size: 3 }),
});
expect(seen).toEqual([['queue.updated', { size: 3 }]]);
});
});
+242
View File
@@ -0,0 +1,242 @@
// Browser RPC client for the Echoion RPC server — TypeScript port of the
// original web/rpc.js. The web UI is a desktop-style client: it connects
// straight to the RPC WebSocket and speaks the exact same JSON protocol the
// Qt desktop client uses.
//
// Wire contract (must match the server — do not "clean up"):
// - request.method is the RpcMethod enum *name* (e.g. "Play").
// - request.params is a JSON-encoded *string*, not a nested object.
// - responses are correlated by requestId; result/error are JSON strings.
// - notifications carry { event, data } where data is a JSON string.
export type RpcConnectionState = 'connected' | 'disconnected' | 'error';
export interface RpcError {
code?: number;
message: string;
source?: string;
}
// Method names mirroring EchoionApi RpcTypes.hpp; the wire carries the name.
export type RpcMethodName =
| 'Authenticate'
| 'AuthenticateByAddress'
| 'Logout'
| 'Play'
| 'Pause'
| 'Resume'
| 'Stop'
| 'Skip'
| 'Seek'
| 'SetVolume'
| 'ToggleShuffle'
| 'ToggleRepeat'
| 'ToggleAutoplay'
| 'ShuffleQueue'
| 'QueueTrack'
| 'RemoveFromQueue'
| 'ClearQueue'
| 'GetQueue'
| 'MoveInQueue'
| 'SearchTracks'
| 'GetCurrentTrack'
| 'GetStatus'
| 'GetServerInfo'
| 'GetPlaylist'
| 'GetPlaylists'
| 'SavePlaylist'
| 'LoadPlaylist'
| 'DeletePlaylist'
| 'GetHistory'
| 'GetStats'
| 'GetLyrics'
| 'GetFavorites'
| 'AddFavorite'
| 'RemoveFavorite'
| 'VoteSkip'
| 'Announce'
| 'GetAggregateStats'
| 'ReloadConfig'
| 'RestartWebInterface'
| 'ManageUsers'
| 'GetAuditLog'
| 'GetUserPrefs'
| 'SetUserPrefs'
| 'GetCustomEmojis'
| 'AddCustomEmoji'
| 'RemoveCustomEmoji';
type Pending = {
resolve: (value: unknown) => void;
reject: (err: RpcError) => void;
};
export class RpcClient {
private ws: WebSocket | null = null;
private nextId = 1;
private pending = new Map<number, Pending>();
private listeners = new Map<string, Array<(...args: unknown[]) => void>>();
token: string | null = null;
onState: (s: RpcConnectionState) => void = () => {};
// Fired after an automatic reconnect succeeds so the app can
// re-authenticate and refresh its state.
onReconnected: () => void = () => {};
private wantReconnect = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelay = 2000;
async connect(): Promise<void> {
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
try {
cfg = await fetch('/config.json').then((r) => r.json());
} catch {
/* fall back to derived URL below */
}
// A path-only rpcUrl (default "/rpc") means the same-origin bridge on
// the web server; absolute URLs and the bare-port fallback still work.
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
let url: string;
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
url = `${wsProto}://${location.host}${cfg.rpcUrl}`;
} else if (cfg.rpcUrl && cfg.rpcUrl.length) {
url = cfg.rpcUrl;
} else {
url = `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
}
return new Promise((resolve, reject) => {
this.ws = new WebSocket(url);
this.ws.onopen = () => {
this.wantReconnect = true;
this.reconnectDelay = 2000;
this.onState('connected');
resolve();
};
this.ws.onclose = () => {
this.onState('disconnected');
this.failAll('Connection closed');
this.scheduleReconnect();
};
this.ws.onerror = () => {
this.onState('error');
reject(new Error('WebSocket error'));
};
this.ws.onmessage = (ev) => this.onMessage(String(ev.data));
});
}
// Reconnect with backoff after an unexpected close. Only armed once a
// connection has succeeded; an explicit disconnect() disarms it.
private scheduleReconnect() {
if (!this.wantReconnect || this.reconnectTimer) return;
const delay = this.reconnectDelay;
this.reconnectDelay = Math.min(this.reconnectDelay * 2, 15000);
this.reconnectTimer = setTimeout(async () => {
this.reconnectTimer = null;
try {
await this.connect();
this.onReconnected();
} catch {
this.scheduleReconnect();
}
}, delay);
}
disconnect() {
this.wantReconnect = false;
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
get connected(): boolean {
return !!this.ws && this.ws.readyState === WebSocket.OPEN;
}
private decode(s: unknown): unknown {
if (s == null) return null;
if (typeof s !== 'string') return s;
try {
return JSON.parse(s);
} catch {
return s;
}
}
private onMessage(raw: string) {
let msg: Record<string, unknown>;
try {
msg = JSON.parse(raw);
} catch {
return;
}
if ('requestId' in msg) {
const p = this.pending.get(msg.requestId as number);
if (!p) return;
this.pending.delete(msg.requestId as number);
if (msg.success) {
p.resolve(this.decode(msg.result));
} else {
p.reject(
(this.decode(msg.error) as RpcError) || {
message: 'RPC error',
}
);
}
} else if ('event' in msg) {
const data = this.decode(msg.data);
const event = msg.event as string;
(this.listeners.get(event) || []).forEach((cb) => cb(data));
(this.listeners.get('*') || []).forEach((cb) => cb(event, data));
}
}
private failAll(message: string) {
for (const [, p] of this.pending) p.reject({ message });
this.pending.clear();
}
call<T = unknown>(
method: RpcMethodName,
params: Record<string, unknown> = {}
): Promise<T> {
return new Promise((resolve, reject) => {
if (!this.connected || !this.ws) {
reject({ message: 'Not connected' });
return;
}
const id = this.nextId++;
const req: Record<string, unknown> = {
id,
method,
params: JSON.stringify(params),
};
if (this.token) req.authToken = this.token;
this.pending.set(id, {
resolve: resolve as (v: unknown) => void,
reject,
});
this.ws.send(JSON.stringify(req));
});
}
on(event: string, cb: (...args: unknown[]) => void) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event)!.push(cb);
}
authenticate(token: string) {
this.token = token;
return this.call('Authenticate', { token });
}
requestToken(nickname: string) {
return this.call('Authenticate', { nickname });
}
}
// Singleton shared by the whole app (mirrors the vanilla `const rpc`).
export const rpc = new RpcClient();
+111
View File
@@ -0,0 +1,111 @@
// Global keyboard shortcuts for desktop control. Ignored while typing in a
// field, and while any modifier is held (so browser/OS chords still work).
import { appStore, safeCall, showView } from './app';
// List shown in the "?" cheat-sheet overlay. English source strings; the
// overlay translates the labels.
export const SHORTCUTS: Array<{ keys: string; label: string }> = [
{ keys: 'Space', label: 'Play / pause' },
{ keys: '← / →', label: 'Seek 5s' },
{ keys: '↑ / ↓', label: 'Volume' },
{ keys: 'N', label: 'Skip / vote skip' },
{ keys: '/', label: 'Focus search' },
{ keys: '?', label: 'This help' },
];
function isTyping(): boolean {
const el = document.activeElement as HTMLElement | null;
if (!el) return false;
const tag = el.tagName;
return (
tag === 'INPUT' ||
tag === 'TEXTAREA' ||
tag === 'SELECT' ||
el.isContentEditable
);
}
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
function seekBy(deltaSec: number) {
const s = appStore.get();
const dur = s.durationMs || 0;
if (!dur) return;
const pos = Math.max(0, Math.min(dur, s.positionMs + deltaSec * 1000));
safeCall('Seek', { position: Math.round(pos) });
}
function volumeBy(deltaPct: number) {
const st = appStore.get().status || {};
const cur = Math.round((st.volume ?? 0.5) * 100);
const next = Math.max(0, Math.min(100, cur + deltaPct));
safeCall('SetVolume', { volume: next / 100 });
}
function skip() {
const id = appStore.get().identity;
// Mirror the Now view: DJ/admin force-skip, everyone else votes.
if (id && (id.isAdmin || id.isDj)) safeCall('Skip', { count: 1 });
else safeCall('VoteSkip');
}
export function initShortcuts() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (isTyping()) {
if (e.key === 'Escape') {
(document.activeElement as HTMLElement | null)?.blur();
}
return;
}
switch (e.key) {
case ' ':
e.preventDefault();
void togglePlay();
break;
case 'ArrowLeft':
seekBy(-5);
break;
case 'ArrowRight':
seekBy(5);
break;
case 'ArrowUp':
e.preventDefault();
volumeBy(5);
break;
case 'ArrowDown':
e.preventDefault();
volumeBy(-5);
break;
case 'n':
case 'N':
skip();
break;
case '/':
e.preventDefault();
showView('search');
setTimeout(() => {
document
.querySelector<HTMLInputElement>('#view-search input')
?.focus();
}, 50);
break;
case '?':
appStore.set({ shortcutsOpen: !appStore.get().shortcutsOpen });
break;
case 'Escape': {
const s = appStore.get();
if (s.shortcutsOpen) appStore.set({ shortcutsOpen: false });
else if (s.sidebarOpen) appStore.set({ sidebarOpen: false });
break;
}
default:
break;
}
});
}
+32
View File
@@ -0,0 +1,32 @@
// Minimal external store + useSyncExternalStore hook. One immutable snapshot
// for the whole app state (the vanilla UI re-rendered everything on any
// refresh anyway, so per-field granularity buys nothing at this scale).
import { useSyncExternalStore } from 'react';
export class Store<T> {
private state: T;
private listeners = new Set<() => void>();
constructor(initial: T) {
this.state = initial;
}
get(): T {
return this.state;
}
set(partial: Partial<T>) {
this.state = { ...this.state, ...partial };
this.listeners.forEach((l) => l());
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
}
export function useStore<T>(store: Store<T>): T {
return useSyncExternalStore(store.subscribe, () => store.get());
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { renderTsMarkup } from './tsMarkup';
const html = (src: string) => renderToStaticMarkup(<>{renderTsMarkup(src)}</>);
describe('renderTsMarkup', () => {
it('renders markdown bold/italic/code', () => {
expect(html('**bold** and *italic* and `code`')).toBe(
'<p><strong>bold</strong> and <em>italic</em> and <code>code</code></p>'
);
});
it('renders BBCode bold/underline/color', () => {
expect(html('[b]x[/b] [u]y[/u] [color=#f00]z[/color]')).toBe(
'<p><strong>x</strong> <u>y</u> <span style="color:#f00">z</span></p>'
);
});
it('renders markdown and BBCode links with safe attributes', () => {
expect(html('[site](https://example.com)')).toBe(
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">site</a></p>'
);
expect(html('[url]https://example.com[/url]')).toBe(
'<p><a href="https://example.com" target="_blank" rel="noopener noreferrer">https://example.com</a></p>'
);
});
it('escapes raw HTML (no injection)', () => {
// React escapes text nodes; the <img> is rendered as literal text.
const out = html('<img src=x onerror=alert(1)>');
expect(out).not.toContain('<img');
expect(out).toContain('&lt;img');
});
it('renders headers and blockquotes', () => {
expect(html('# Title')).toBe('<h3>Title</h3>');
expect(html('> quoted')).toBe(
'<blockquote><p>quoted</p></blockquote>'
);
});
it('renders the TS6 collapsible details container', () => {
const out = html(':::details Info\nbody\n:::');
expect(out).toContain('<details open="">');
expect(out).toContain('<summary>Info</summary>');
expect(out).toContain('<p>body</p>');
});
});
+176
View File
@@ -0,0 +1,176 @@
// Renders the TeamSpeak-6 markdown + BBCode subset the bot's replies use so
// the announce composer (item 14) can preview exactly what subscribers see.
// Security: text is escaped first (React escapes by default since we return
// elements, never dangerouslySetInnerHTML), so untrusted markup can't inject
// HTML — only the recognized tags below produce formatting.
import type { ReactNode } from 'react';
// Inline pass: **bold**, *italic* / _italic_, ~~strike~~, `code`, [text](url),
// and the BBCode equivalents [b] [i] [u] [s] [url] [color=…]. Applied to one
// line's worth of text.
function renderInline(text: string, keyBase: string): ReactNode[] {
// Ordered so the first matching rule wins at each position.
const rules: Array<{
re: RegExp;
render: (m: RegExpExecArray, key: string) => ReactNode;
}> = [
{
re: /\*\*([^*]+)\*\*/,
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
},
{
re: /\[b\]([\s\S]*?)\[\/b\]/i,
render: (m, k) => <strong key={k}>{renderInline(m[1], k)}</strong>,
},
{
re: /(?:\*([^*]+)\*|_([^_]+)_)/,
render: (m, k) => (
<em key={k}>{renderInline(m[1] ?? m[2], k)}</em>
),
},
{
re: /\[i\]([\s\S]*?)\[\/i\]/i,
render: (m, k) => <em key={k}>{renderInline(m[1], k)}</em>,
},
{
re: /\[u\]([\s\S]*?)\[\/u\]/i,
render: (m, k) => <u key={k}>{renderInline(m[1], k)}</u>,
},
{
re: /(?:~~([^~]+)~~|\[s\]([\s\S]*?)\[\/s\])/i,
render: (m, k) => <s key={k}>{renderInline(m[1] ?? m[2], k)}</s>,
},
{
re: /`([^`]+)`/,
render: (m, k) => <code key={k}>{m[1]}</code>,
},
{
re: /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/,
render: (m, k) => (
<a key={k} href={m[2]} target="_blank" rel="noopener noreferrer">
{m[1]}
</a>
),
},
{
re: /\[url\]([\s\S]*?)\[\/url\]/i,
render: (m, k) => (
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
{m[1]}
</a>
),
},
{
re: /\[url=([^\]]+)\]([\s\S]*?)\[\/url\]/i,
render: (m, k) => (
<a key={k} href={m[1]} target="_blank" rel="noopener noreferrer">
{renderInline(m[2], k)}
</a>
),
},
{
re: /\[color=([#\w]+)\]([\s\S]*?)\[\/color\]/i,
render: (m, k) => (
<span key={k} style={{ color: m[1] }}>
{renderInline(m[2], k)}
</span>
),
},
];
// Find the earliest match across all rules, emit the text before it, the
// rendered node, then recurse on the remainder.
let best: { index: number; length: number; node: ReactNode } | null = null;
let counter = 0;
for (const rule of rules) {
const m = rule.re.exec(text);
if (m && (best === null || m.index < best.index)) {
best = {
index: m.index,
length: m[0].length,
node: rule.render(m, `${keyBase}-${counter++}`),
};
}
}
if (!best) return [text];
const before = text.slice(0, best.index);
const after = text.slice(best.index + best.length);
return [
...(before ? [before] : []),
best.node,
...renderInline(after, `${keyBase}-r`),
];
}
// Block pass: headers (#, ##, ###), blockquotes (>), and the TS6 collapsible
// container (:::details Title … :::). Everything else is a paragraph line.
export function renderTsMarkup(source: string): ReactNode {
const lines = source.split('\n');
const blocks: ReactNode[] = [];
let i = 0;
let key = 0;
while (i < lines.length) {
const line = lines[i];
const details = /^:::details\s+(.*)$/.exec(line.trim());
if (details) {
const inner: string[] = [];
i++;
while (i < lines.length && lines[i].trim() !== ':::') {
inner.push(lines[i]);
i++;
}
i++; // skip closing :::
blocks.push(
<details key={key++} open>
<summary>{renderInline(details[1], `s${key}`)}</summary>
{renderTsMarkup(inner.join('\n'))}
</details>
);
continue;
}
const header = /^(#{1,3})\s+(.*)$/.exec(line);
if (header) {
const level = header[1].length;
const content = renderInline(header[2], `h${key}`);
blocks.push(
level === 1 ? (
<h3 key={key++}>{content}</h3>
) : level === 2 ? (
<h4 key={key++}>{content}</h4>
) : (
<h5 key={key++}>{content}</h5>
)
);
i++;
continue;
}
if (/^>\s?/.test(line)) {
const quote: string[] = [];
while (i < lines.length && /^>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^>\s?/, ''));
i++;
}
blocks.push(
<blockquote key={key++}>
{renderTsMarkup(quote.join('\n'))}
</blockquote>
);
continue;
}
if (line.trim() === '') {
i++;
continue;
}
blocks.push(<p key={key++}>{renderInline(line, `p${key}`)}</p>);
i++;
}
return <>{blocks}</>;
}
+107
View File
@@ -0,0 +1,107 @@
// Shapes of the RPC payloads the UI consumes (subset of the server DTOs;
// fields the UI does not read are omitted).
export interface Track {
id?: string;
title?: string;
artist?: string;
url?: string; // originalUrl (play-by-url)
shortenedUrl?: string; // faumaray.ru short link, preferred for opening
thumbnailUrl?: string;
duration?: number; // ms
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
}
export interface QueueEntry {
queueId: number;
track: Track;
isPlaying?: boolean;
addedBy?: string;
}
export interface Status {
isPlaying?: boolean;
isPaused?: boolean;
shuffle?: boolean;
repeat?: boolean;
autoplay?: boolean;
volume?: number;
skipVotes?: number;
skipVotesNeeded?: number;
skipVoted?: boolean;
}
export interface Identity {
uid?: string;
nickname?: string;
isAdmin?: boolean;
isDj?: boolean;
token?: string;
message?: string;
}
export interface ServerInfo {
version?: string;
uptimeSeconds?: number;
onlineSubscribers?: number;
onlineSubscriberNames?: string[];
// Parallel to onlineSubscriberNames (same order): TeamSpeak uids so the
// "Listening now" card can fetch each listener's avatar.
onlineSubscriberUids?: string[];
}
export interface AggregateStats {
tracksToday: number;
playsTotal: number;
listeningMsToday: number;
queueAdditionsToday: number;
skipsToday: number;
skipsTotal: number;
topRequesters: Array<{ uid?: string; nickname: string; count: number }>;
youtubeCount: number;
yandexCount: number;
otherCount: number;
}
export interface Subscriber {
uid: string;
nickname?: string;
online?: boolean;
}
export interface Playlist {
id: string;
name: string;
trackCount: number;
}
// GetPlaylist response — a playlist's full track list (Dto::PlaylistContents).
export interface PlaylistContents {
id: string;
name: string;
description?: string;
tracks: Track[];
}
// GetAuditLog response entry (Dto::AuditEntryDto). `method` is the numeric
// RpcMethod enum value; map it to a name with lib/auditMethods.
export interface AuditEntry {
clientId: number;
method: number;
timestamp: number; // unix seconds
}
// GetLyrics response (Dto::LyricsResponse).
export interface LyricsLine {
ms: number; // offset from track start
text: string;
}
export interface LyricsResult {
found: boolean;
plain: string;
synced: LyricsLine[];
source?: string;
title?: string;
artist?: string;
}
+53
View File
@@ -0,0 +1,53 @@
import { useEffect, useState, type RefObject } from 'react';
// Auto-hides the Watch player's overlay controls (and the mouse cursor) after
// `idleMs` of no input while a video is PLAYING, and reveals them instantly on
// any input — like a regular video player, in both windowed and fullscreen.
// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is
// open) is left to CSS (:hover / :focus-within); this hook only owns the idle
// timeout and the "always visible while paused" rule. Returns the hidden flag.
export function useControlsAutoHide(
shellRef: RefObject<HTMLElement | null>,
opts: { playing: boolean; enabled?: boolean; idleMs?: number }
): boolean {
const { playing, enabled = true, idleMs = 3000 } = opts;
const [hidden, setHidden] = useState(false);
useEffect(() => {
const shell = shellRef.current;
// Paused, disabled, or no element: always show, no timer.
if (!shell || !enabled || !playing) {
setHidden(false);
return;
}
let timer: number | undefined;
const arm = () => {
if (timer) window.clearTimeout(timer);
timer = window.setTimeout(() => setHidden(true), idleMs);
};
const reveal = () => {
setHidden(false); // React bails when already false → no churn
arm();
};
const events = [
'mousemove',
'pointerdown',
'touchstart',
'keydown',
'focusin',
] as const;
for (const e of events) {
shell.addEventListener(e, reveal, { passive: true });
}
// Entering/leaving fullscreen counts as activity.
document.addEventListener('fullscreenchange', reveal);
arm();
return () => {
if (timer) window.clearTimeout(timer);
for (const e of events) shell.removeEventListener(e, reveal);
document.removeEventListener('fullscreenchange', reveal);
};
}, [shellRef, playing, enabled, idleMs]);
return hidden;
}
File diff suppressed because it is too large. Load diff
+75
View File
@@ -0,0 +1,75 @@
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
// Playing video preview use it; the script is injected once and callers await
// the same readiness promise.
//
// Console-error triage for the YouTube embeds (as seen in production behind
// the reverse proxy):
// - "Failed to execute 'postMessage' … target origin ('https://www.youtube.com')
// does not match the recipient window's origin" — the IFrame API guesses the
// embedder when no explicit origin is passed; fixed by youtubeEmbedVars().
// - "__Secure-YEC has been rejected … SameSite" — YouTube setting its own
// third-party cookie inside the iframe; the youtube-nocookie.com host
// reduces this noise but cannot eliminate it.
// - "Attempt to postMessage on disconnected port" — fires when an iframe is
// torn down mid-message (source switch, room leave); harmless.
// Privacy-enhanced embed host (see cookie note above). Pass as the
// (undeclared in @types/youtube) top-level `host` option of YT.Player.
export const YOUTUBE_EMBED_HOST = 'https://www.youtube-nocookie.com';
// playerVars every embed must pass: native controls stay hidden (the custom
// bar / sync logic owns playback), and enablejsapi + origin keep the API's
// postMessage channel bound to this page's real origin.
export function youtubeEmbedVars(
extra?: Record<string, string | number>
): YT.PlayerVars {
return {
rel: 0,
modestbranding: 1,
controls: 0,
disablekb: 1,
iv_load_policy: 3,
enablejsapi: 1,
origin: location.origin,
widget_referrer: location.origin,
...extra,
} as YT.PlayerVars;
}
let promise: Promise<void> | null = null;
export function loadYouTubeApi(): Promise<void> {
if (promise) return promise;
promise = new Promise((resolve) => {
const w = window as unknown as {
YT?: typeof YT;
onYouTubeIframeAPIReady?: () => void;
};
if (w.YT && w.YT.Player) {
resolve();
return;
}
const prev = w.onYouTubeIframeAPIReady;
w.onYouTubeIframeAPIReady = () => {
prev?.();
resolve();
};
if (!document.querySelector('script[data-yt-iframe-api]')) {
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
tag.dataset.ytIframeApi = '1';
document.head.appendChild(tag);
}
});
return promise;
}
// Extract an 11-char YouTube video id from a watch/share/embed URL or a bare
// id, or null when the URL is not YouTube.
export function youtubeIdFromUrl(url: string | undefined | null): string | null {
if (!url) return null;
const m = url.match(/(?:v=|youtu\.be\/|\/embed\/)([\w-]{11})/);
if (m) return m[1];
if (/^[\w-]{11}$/.test(url)) return url;
return null;
}
+22
View File
@@ -0,0 +1,22 @@
import { createRoot } from 'react-dom/client';
import { App } from './App';
import './styles/style.css';
// Human-readable fingerprint for deployment/debugging. Vite's filename hash
// can legitimately match an older backup when the emitted code becomes
// byte-identical after a revert, so expose an explicit release identity too.
export const WEB_BUILD_ID = '2026.07.10-player-fix.3';
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
createRoot(document.getElementById('root')!).render(<App />);
// Register the PWA service worker in production (installable + offline shell).
// Skipped on the vite dev server so hot-reload isn't shadowed by the cache.
if ('serviceWorker' in navigator && import.meta.env.PROD) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').catch(() => {
/* SW is a progressive enhancement — ignore failures */
});
});
}
+786
View File
@@ -0,0 +1,786 @@
/* Echoion web UI — dark violet design (see Echoion.html mockup). */
:root {
--bg: #0a0a0e;
--panel: rgba(255, 255, 255, 0.03);
--panel-2: rgba(255, 255, 255, 0.05);
--line: rgba(255, 255, 255, 0.07);
--text: #f3f3f6;
--text-2: #e8e8ee;
--muted: #9a9aa8;
--muted-2: #8a8a98;
--faint: #6a6a78;
--accent: #7c5cff;
--accent-soft: rgba(124, 92, 255, 0.16);
--accent-text: #b5a3ff;
--accent-2: #8f72ff;
--green: #3fd07a;
--green-text: #5fe094;
--red: #ff5c5c;
--red-text: #ff8080;
--yellow: #ffcf4a;
--yellow-text: #ffd977;
--pink: #ff6b9d;
--radius: 14px;
--font-head: 'Space Grotesk', sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, monospace;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 14px;
min-height: 100vh;
}
button { font-family: inherit; color: inherit; }
input {
font-family: inherit;
color: var(--text);
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--line);
border-radius: 10px;
padding: 10px 14px;
outline: none;
font-size: 13.5px;
}
input:focus { border-color: rgba(124, 92, 255, 0.45); }
.mono { font-family: var(--font-mono); font-size: 12.5px; }
.muted { color: var(--muted-2); font-weight: 500; }
h1, h2, h3 { font-family: var(--font-head); }
h2 { font-size: 17px; font-weight: 600; }
h3 { font-size: 15px; font-weight: 600; }
#app { display: flex; min-height: 100vh; }
/* ── Sidebar ──────────────────────────────────────────────────────────── */
.sidebar {
width: 236px;
flex: none;
display: flex;
flex-direction: column;
gap: 18px;
padding: 22px 14px;
border-right: 1px solid var(--line);
position: sticky;
top: 0;
height: 100vh;
}
.brand { display: flex; align-items: center; gap: 12px; padding: 0 6px; }
.brand-icon {
width: 42px; height: 42px; border-radius: 13px;
background: linear-gradient(135deg, #7c5cff, #5b3fd6);
display: flex; align-items: center; justify-content: center;
box-shadow: 0 4px 18px rgba(124, 92, 255, 0.35);
}
.brand-name { font-family: var(--font-head); font-size: 19px; font-weight: 700; letter-spacing: -0.02em; }
.brand-sub { font-size: 10px; font-weight: 600; letter-spacing: 2.4px; color: var(--faint); }
.nav { display: flex; flex-direction: column; gap: 3px; flex: 1; }
.nav-item {
display: flex; align-items: center; gap: 12px;
padding: 10px 12px;
border: none; border-radius: 10px;
background: transparent; color: var(--muted);
font-weight: 600; font-size: 13.5px;
cursor: pointer; width: 100%;
transition: background 0.12s;
text-align: left;
}
.nav-item:hover { background: rgba(255, 255, 255, 0.04); }
.nav-item.active {
background: var(--accent-soft);
color: #fff;
box-shadow: inset 3px 0 0 var(--accent);
}
.nav-ico {
width: 18px; color: inherit; opacity: 0.9;
display: inline-flex; align-items: center; justify-content: center;
font-size: 15px; flex: none;
}
.nav-badge {
margin-left: auto;
font-family: var(--font-mono); font-size: 11px; font-weight: 700;
color: var(--accent-text); background: var(--accent-soft);
padding: 2px 8px; border-radius: 8px;
}
.live-dot, .dot {
width: 8px; height: 8px; border-radius: 50%;
display: inline-block; flex: none;
}
.live-dot { margin-left: auto; background: var(--red); animation: ech-pulse 1.6s infinite; }
.dot-green { background: var(--green); }
@keyframes ech-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
.sidebar-foot { display: flex; flex-direction: column; gap: 10px; font-size: 12.5px; }
.conn-row { display: flex; align-items: center; gap: 8px; color: var(--muted-2); padding: 0 6px; }
.conn-dot { width: 8px; height: 8px; border-radius: 50%; background: #5a5a68; }
.conn-dot.on { background: var(--green); }
.conn-dot.err { background: var(--red); }
#authBox { display: flex; flex-direction: column; gap: 8px; }
#authBox input { width: 100%; }
.whoami { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 0 6px; }
.admin-chip {
font-size: 10px; font-weight: 700; letter-spacing: 0.04em;
color: var(--yellow-text); background: rgba(255, 207, 74, 0.12);
padding: 2px 7px; border-radius: 6px;
}
/* ── Main / header ────────────────────────────────────────────────────── */
.main { flex: 1; padding: 26px 30px 90px; min-width: 0; }
.header { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 22px; }
.header h1 { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; }
.header-sub { color: var(--muted-2); font-size: 13px; margin-top: 3px; }
.header-right { display: flex; gap: 10px; align-items: center; }
.pill {
display: inline-flex; align-items: center; gap: 7px;
padding: 7px 13px; border-radius: 10px;
background: var(--panel-2); font-size: 12.5px; font-weight: 600;
color: var(--text-2);
}
.pill-green { background: rgba(63, 208, 122, 0.12); color: var(--green-text); }
.pill-yellow { background: rgba(255, 207, 74, 0.12); color: var(--yellow-text); }
/* ── Cards / lists ────────────────────────────────────────────────────── */
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 18px;
margin-bottom: 18px;
}
.card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; gap: 10px; }
.row-gap { display: flex; gap: 8px; align-items: center; }
.col { display: flex; flex-direction: column; min-width: 0; }
.link { background: none; border: none; color: var(--accent-text); cursor: pointer; font-weight: 600; font-size: 12.5px; }
/* Keyboard focus ring for every interactive control; pointer clicks don't
show it. */
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button:focus:not(:focus-visible),
select:focus:not(:focus-visible) { outline: none; }
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
and never shrink in flex rows. */
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg {
vertical-align: -0.125em; flex: none;
}
.btn {
padding: 9px 16px;
border-radius: 10px;
border: 1px solid transparent;
cursor: pointer;
font-weight: 600; font-size: 13px;
background: rgba(255, 255, 255, 0.05);
color: var(--text-2);
}
.btn:hover { background: rgba(255, 255, 255, 0.08); }
.btn-accent { background: var(--accent); color: #fff; }
.btn-accent:hover { background: #8b6dff; }
.btn-ghost { background: transparent; border-color: var(--line); color: var(--muted); }
.btn-ghost:hover { color: var(--text-2); background: rgba(255, 255, 255, 0.04); }
.btn-danger-ghost { background: transparent; border-color: rgba(255, 92, 92, 0.3); color: var(--red-text); }
.btn-danger-ghost:hover { background: rgba(255, 92, 92, 0.1); }
/* Leave-room button: prominent but not alarming; pushed to the right of the
room header so it reads as the primary in-room action. */
.btn-leave {
margin-left: auto;
display: inline-flex; align-items: center; gap: 6px;
background: rgba(255, 92, 92, 0.12);
border-color: rgba(255, 92, 92, 0.35);
color: var(--red-text);
font-weight: 700;
}
.btn-leave:hover {
background: rgba(255, 92, 92, 0.22);
border-color: rgba(255, 92, 92, 0.6);
}
.src-badge {
font-size: 10px; font-weight: 700; letter-spacing: 0.03em;
padding: 3px 8px; border-radius: 6px; flex: none;
color: var(--red-text); background: rgba(255, 107, 107, 0.14);
align-self: flex-start;
}
.src-badge.yandex { color: var(--yellow-text); background: rgba(255, 207, 74, 0.14); }
.tracklist { display: flex; flex-direction: column; }
.track-row {
display: flex; align-items: center; gap: 14px;
padding: 10px 6px;
border-bottom: 1px solid rgba(255, 255, 255, 0.035);
}
.track-row:last-child { border-bottom: none; }
.track-row.playing { background: var(--accent-soft); border-radius: 10px; }
.track-row.dragging { opacity: 0.4; }
.track-num { font-family: var(--font-mono); font-size: 12px; color: var(--faint); width: 22px; flex: none; }
.track-cover { width: 40px; height: 40px; border-radius: 9px; flex: none; }
.track-main { flex: 1; min-width: 0; }
.track-title { font-weight: 600; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.track-sub { color: var(--muted-2); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }
.track-dur { font-family: var(--font-mono); font-size: 12px; color: var(--muted-2); flex: none; }
.track-actions { display: flex; gap: 4px; flex: none; }
.icon-btn {
background: none; border: none; cursor: pointer;
color: var(--muted-2); font-size: 14px;
width: 30px; height: 30px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.icon-btn:hover { background: rgba(255, 255, 255, 0.07); color: var(--text); }
.icon-btn.danger:hover { color: var(--red-text); }
.icon-btn.fav-on { color: var(--pink); }
.drag-handle { cursor: grab; color: var(--faint); }
.empty { padding: 24px; text-align: center; color: var(--faint); }
/* ── Now Playing ──────────────────────────────────────────────────────── */
.now-grid { display: grid; grid-template-columns: 1.25fr 1fr; gap: 18px; align-items: start; }
.np-card { display: flex; flex-direction: column; gap: 18px; }
.np-cover {
width: 100%; aspect-ratio: 1.9;
border-radius: 12px;
background: linear-gradient(135deg, #2a1a4a, #0d0d1f);
background-size: cover; background-position: center;
}
.np-info { display: flex; flex-direction: column; gap: 9px; }
.np-title { font-family: var(--font-head); font-size: 22px; font-weight: 700; letter-spacing: -0.01em; }
.np-artist { color: var(--muted); font-size: 14px; }
.np-added { color: var(--faint); font-size: 12px; }
.progress-row { display: flex; align-items: center; gap: 12px; margin-top: 8px; }
.bar {
flex: 1; height: 7px; border-radius: 5px;
background: rgba(255, 255, 255, 0.08);
cursor: pointer; position: relative;
}
.bar-slim { height: 5px; }
.bar-fill { position: relative; height: 100%; width: 0; border-radius: 5px; background: linear-gradient(90deg, #7c5cff, #a68dff); }
/* Locally buffered range, painted behind the progress fill. */
.bar-buffer {
position: absolute; left: 0; top: 0; height: 100%;
border-radius: 5px; background: rgba(255, 255, 255, 0.14);
}
/* Value tooltip that follows the pointer while hovering/dragging a bar. */
.bar-tip {
position: absolute; bottom: 100%; margin-bottom: 8px;
transform: translateX(-50%); pointer-events: none; white-space: nowrap;
background: #1b1b26; color: #f0f0f5; border: 1px solid rgba(255,255,255,0.12);
padding: 2px 7px; border-radius: 6px; font-size: 12px;
font-variant-numeric: tabular-nums; z-index: 5;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
}
.transport { display: flex; align-items: center; gap: 10px; margin-top: 6px; flex-wrap: wrap; }
.ctrl {
width: 40px; height: 40px;
border: none; border-radius: 11px;
cursor: pointer;
display: flex; align-items: center; justify-content: center;
background: rgba(255, 255, 255, 0.04); color: var(--muted-2);
font-size: 15px;
}
.ctrl:hover { background: rgba(255, 255, 255, 0.08); color: var(--text); }
.ctrl.on { background: rgba(124, 92, 255, 0.2); color: var(--accent-text); }
.ctrl.fav-on { color: var(--pink); }
.ctrl-main {
width: 52px; height: 52px; border-radius: 15px;
background: var(--accent); color: #fff; font-size: 18px;
}
.ctrl-main:hover { background: #8b6dff; color: #fff; }
.voteskip.on { border-color: rgba(124, 92, 255, 0.5); color: var(--accent-text); }
.vol-row { display: flex; align-items: center; gap: 12px; margin-top: 4px; }
.vol-row .bar { max-width: 160px; }
.toggle-row { display: flex; align-items: center; gap: 8px; margin-left: auto; cursor: pointer; }
.toggle {
width: 42px; height: 24px; border-radius: 14px; border: none;
cursor: pointer; padding: 2px; display: flex;
background: rgba(255, 255, 255, 0.12);
justify-content: flex-start; transition: background 0.15s;
}
.toggle.on { background: var(--accent); justify-content: flex-end; }
.knob { width: 20px; height: 20px; border-radius: 50%; background: #fff; display: block; }
/* ── People rows (listeners, subscribers, participants) ──────────────── */
.people { display: flex; flex-direction: column; }
.person {
display: flex; align-items: center; gap: 12px;
padding: 9px 4px;
border-bottom: 1px solid rgba(255, 255, 255, 0.035);
}
.person:last-child { border-bottom: none; }
.avatar {
width: 32px; height: 32px; border-radius: 10px; flex: none;
display: inline-flex; align-items: center; justify-content: center;
font-weight: 700; font-size: 14px; color: #fff;
background: linear-gradient(135deg, #7c5cff, #5b3fd6);
}
.person-main { flex: 1; min-width: 0; }
.person-name { font-weight: 600; font-size: 13.5px; }
.person-sub { color: var(--muted-2); font-size: 11.5px; margin-top: 1px; }
.person-status { font-size: 12px; font-weight: 600; flex: none; }
/* ── Search / tabs ────────────────────────────────────────────────────── */
.search-row { display: flex; gap: 10px; margin-bottom: 14px; }
.search-row input { flex: 1; }
.tabs { display: flex; gap: 8px; margin-bottom: 16px; }
.tab {
padding: 9px 18px; border-radius: 10px;
border: 1px solid var(--line);
cursor: pointer; font-weight: 600; font-size: 13.5px;
background: transparent; color: var(--muted);
}
.tab.active { background: var(--accent-soft); border-color: rgba(124, 92, 255, 0.4); color: #fff; }
/* ── Library ──────────────────────────────────────────────────────────── */
.grid-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
.playlist-card {
border: 1px solid var(--line); border-radius: 12px;
padding: 14px; cursor: pointer;
background: var(--panel-2);
display: flex; flex-direction: column; gap: 10px;
}
.playlist-card:hover { border-color: rgba(124, 92, 255, 0.4); }
.playlist-card.active { border-color: rgba(124, 92, 255, 0.7); }
.playlist-actions { display: flex; gap: 6px; margin-top: 2px; }
.playlist-actions .btn { padding: 4px 10px; font-size: 12px; }
.playlist-cover { width: 100%; aspect-ratio: 1.6; border-radius: 9px; }
.playlist-name { font-weight: 600; font-size: 13.5px; }
.playlist-meta { color: var(--muted-2); font-size: 12px; }
/* ── Audit log ────────────────────────────────────────────────────────── */
.audit-scroll { max-height: 420px; overflow-y: auto; }
.audit-row {
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
align-items: baseline; padding: 8px 4px;
border-bottom: 1px solid var(--line); font-size: 13px;
}
.audit-row:last-child { border-bottom: none; }
.audit-method { font-weight: 600; }
.audit-time { font-size: 12px; white-space: nowrap; }
.audit-client { font-size: 12px; white-space: nowrap; }
/* ── Keyboard shortcuts overlay ───────────────────────────────────────── */
.shortcuts-modal { width: min(380px, 92vw); }
.shortcuts-list { display: flex; flex-direction: column; gap: 8px; margin: 14px 0 18px; }
.shortcut-row { display: flex; align-items: center; gap: 12px; font-size: 13.5px; }
.shortcut-row kbd {
min-width: 64px; text-align: center; padding: 3px 8px; border-radius: 6px;
background: var(--panel-2); border: 1px solid var(--line);
font-family: var(--font-mono, monospace); font-size: 12px; color: var(--text);
}
/* ── Lyrics ───────────────────────────────────────────────────────────── */
.lyrics-body { padding: 4px 2px; }
.lyrics-empty { color: var(--muted-2); font-size: 13px; padding: 8px 4px; }
.lyrics-synced { max-height: 320px; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }
.lyrics-line { color: var(--muted-2); font-size: 14px; line-height: 1.5; transition: color .15s, transform .15s; }
.lyrics-line.active { color: var(--text); font-weight: 600; transform: translateX(2px); }
.lyrics-plain { max-height: 320px; overflow-y: auto; white-space: pre-wrap; font-family: inherit; font-size: 14px; line-height: 1.55; color: var(--text-2); margin: 0; }
.lyrics-source { font-size: 11px; margin-top: 8px; text-align: right; }
/* ── Stats ────────────────────────────────────────────────────────────── */
.stat-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 18px; }
.stat-card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }
.stat-label { color: var(--muted-2); font-size: 12px; font-weight: 600; }
.stat-value { font-family: var(--font-head); font-size: 26px; font-weight: 700; margin-top: 6px; }
.stat-delta { font-size: 12px; margin-top: 4px; color: var(--muted-2); }
.stat-delta.up { color: var(--green-text); }
.stats-grid { display: grid; grid-template-columns: 1.4fr 1fr; gap: 18px; align-items: start; }
.split-bar { display: flex; height: 12px; border-radius: 7px; overflow: hidden; margin: 8px 0 12px; background: rgba(255,255,255,.06); }
.split-yt { background: #ff8080; }
.split-ya { background: #ffd977; }
.split-legend { display: flex; gap: 18px; font-size: 12.5px; color: var(--muted); }
.split-legend span { display: inline-flex; align-items: center; gap: 6px; }
.split-legend b { color: var(--text-2); margin-left: 2px; }
/* ── Watch Together ───────────────────────────────────────────────────── */
.watch-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 18px; align-items: start; }
.src-yt.active { background: rgba(255, 92, 92, 0.16); border-color: rgba(255, 92, 92, 0.4); color: var(--red-text); }
.src-tw.active { background: rgba(169, 112, 255, 0.18); border-color: rgba(169, 112, 255, 0.4); color: #c3a3ff; }
.src-direct.active { background: rgba(95, 224, 148, 0.16); border-color: rgba(95, 224, 148, 0.4); color: var(--green-text); }
.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 {
opacity: 0.4;
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-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 16px; }
.rpc-field { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.rpc-label { min-width: 140px; flex: none; font-size: 10.5px; font-weight: 700; letter-spacing: 0.08em; color: var(--faint); }
.rpc-value {
flex: 1; font-family: var(--font-mono); font-size: 12.5px;
background: rgba(255, 255, 255, 0.04); border: 1px solid var(--line);
border-radius: 9px; padding: 9px 12px;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.code-block {
font-family: var(--font-mono); font-size: 12px; line-height: 1.55;
background: rgba(0, 0, 0, 0.35); border: 1px solid var(--line);
border-radius: 10px; padding: 14px; overflow-x: auto;
color: #c8c8d2; margin-bottom: 12px;
}
/* ── Mini player ──────────────────────────────────────────────────────── */
.miniplayer {
position: fixed; left: 256px; right: 20px; bottom: 14px;
display: flex; align-items: center; gap: 14px;
background: rgba(18, 18, 26, 0.92);
backdrop-filter: blur(12px);
border: 1px solid var(--line); border-radius: 14px;
padding: 10px 16px; z-index: 40;
}
.mini-cover { width: 38px; height: 38px; border-radius: 9px; background: linear-gradient(135deg, #2a1a4a, #0d0d1f); flex: none; }
.mini-info { min-width: 0; width: 220px; }
.mini-title { font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mini-artist { color: var(--muted-2); font-size: 11.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mini-bar { flex: 1; }
/* ── Toast ────────────────────────────────────────────────────────────── */
.toast {
position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%);
background: #1d1d2a; border: 1px solid rgba(124, 92, 255, 0.35);
color: var(--text); font-size: 13px; font-weight: 600;
padding: 11px 20px; border-radius: 12px;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.5);
z-index: 80;
}
/* ── Responsive ───────────────────────────────────────────────────────── */
/* Hamburger + drawer backdrop exist only at drawer widths (≤900px). */
.hamburger { display: none; }
.header-title { display: flex; align-items: flex-start; gap: 10px; min-width: 0; }
.drawer-backdrop { display: none; }
@media (max-width: 1080px) {
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; }
}
/* Tablet and below: the sidebar becomes a slide-in drawer. */
@media (max-width: 900px) {
.sidebar {
position: fixed; left: 0; top: 0; bottom: 0; z-index: 90;
width: min(280px, 84vw); height: 100dvh;
background: var(--bg);
transform: translateX(-100%);
transition: transform 0.2s ease;
overflow-y: auto;
}
.sidebar.open { transform: none; box-shadow: 12px 0 40px rgba(0, 0, 0, 0.5); }
.hamburger { display: flex; margin-top: 3px; }
.drawer-backdrop {
display: block; position: fixed; inset: 0; z-index: 85;
background: rgba(0, 0, 0, 0.5);
}
.main { padding: 16px 14px calc(96px + env(safe-area-inset-bottom)); }
.header { flex-wrap: wrap; gap: 8px; }
.miniplayer {
left: 12px; right: 12px;
bottom: calc(10px + env(safe-area-inset-bottom));
}
}
/* Phone density. */
@media (max-width: 560px) {
.main { padding-left: 12px; padding-right: 12px; }
.header h1 { font-size: 20px; }
.card { padding: 14px; }
.np-title { font-size: 19px; }
.search-row, .chat-row, .rooms-create, .row-gap { flex-wrap: wrap; }
.search-row input, .chat-row input { min-width: 0; flex: 1 1 160px; }
.watch-controls { flex-wrap: wrap; row-gap: 8px; }
.watch-local .bar { flex: 1 1 100px; }
.tabs { overflow-x: auto; }
.audit-row { grid-template-columns: 1fr auto; }
.audit-time { grid-column: 1 / -1; }
.rpc-field { flex-direction: column; align-items: stretch; }
.rpc-label { min-width: 0; }
.miniplayer { gap: 10px; }
.mini-info { width: auto; flex: 1; min-width: 0; }
}
/* Touch: bigger targets, and a taller invisible hit area on drag bars. */
@media (pointer: coarse) {
.icon-btn { width: 38px; height: 38px; }
.ctrl { width: 44px; height: 44px; }
.ctrl-main { width: 54px; height: 54px; }
.bar::before { content: ''; position: absolute; inset: -10px 0; }
}
/* ── React port additions ─────────────────────────────────────────────── */
/* Language switcher in the sidebar connection row. */
.lang-select {
margin-left: auto; background: transparent; color: inherit;
border: 1px solid rgba(255, 255, 255, 0.12); border-radius: 6px;
font: inherit; font-size: 11px; padding: 2px 4px; cursor: pointer;
}
.lang-select option { color: #000; }
/* Reactions rendered inside the player box (the vanilla UI appended them
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 {
height: 3px; margin: 1px 0; border-radius: 2px;
background: linear-gradient(90deg, #7c5cff, #b28dff);
box-shadow: 0 0 8px rgba(124, 92, 255, 0.7);
}
/* Real image avatars from TeamSpeak (item 10). */
.avatar-img { object-fit: cover; }
/* Now Playing video (item 11). */
.np-video {
width: 100%; aspect-ratio: 16 / 9; border-radius: 14px;
overflow: hidden; background: #000;
}
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
.np-video-toggle.on { color: #b28dff; }
/* Announce composer modal (item 14). */
.modal-backdrop {
position: fixed; inset: 0; z-index: 100; display: flex;
align-items: center; justify-content: center;
background: rgba(6, 6, 14, 0.62); backdrop-filter: blur(3px);
}
.modal {
width: min(560px, 92vw); max-height: 88vh; overflow: auto;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px; padding: 18px 20px;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.5);
}
.modal-wide { width: min(860px, 94vw); }
.modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
.modal-head h2 { margin: 0; }
.modal-foot { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
.announce-toolbar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
.announce-toolbar .btn { padding: 4px 10px; font-weight: 600; min-width: 34px; }
.announce-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media (max-width: 720px) { .announce-grid { grid-template-columns: 1fr; } }
.announce-input {
width: 100%; resize: vertical; min-height: 220px;
font-family: inherit; font-size: 14px; line-height: 1.5;
}
.announce-preview {
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 10px;
padding: 10px 12px; overflow: auto;
}
.announce-preview-label {
font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;
color: #8a8a98; margin-bottom: 6px;
}
.ts-markup { font-size: 14px; line-height: 1.55; word-break: break-word; }
.ts-markup h3, .ts-markup h4, .ts-markup h5 { margin: 0.5em 0 0.3em; }
.ts-markup p { margin: 0.35em 0; }
.ts-markup blockquote {
border-left: 3px solid rgba(124, 92, 255, 0.6);
margin: 0.4em 0; padding-left: 10px; color: #c9c9d6;
}
.ts-markup code {
background: rgba(255, 255, 255, 0.08); padding: 1px 5px;
border-radius: 4px; font-size: 0.9em;
}
.ts-markup details { margin: 0.4em 0; }
.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; }
/* 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;
}
+254
View File
@@ -0,0 +1,254 @@
import { useEffect, useState } from 'react';
import { appStore, loadFavorites, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { cover } from '../lib/format';
import type { Playlist, PlaylistContents } from '../lib/types';
import { confirmDialog, promptDialog } from '../lib/dialog';
import { CloseIcon } from '../components/icons';
import { t, tf } from '../i18n';
export function LibraryView() {
const s = useStore(appStore);
const [playlists, setPlaylists] = useState<Playlist[]>([]);
const [selected, setSelected] = useState<PlaylistContents | null>(null);
const loadPlaylists = async () => {
const res = await safeCall<{ playlists?: Playlist[] }>('GetPlaylists');
setPlaylists((res && res.playlists) || []);
};
const openPlaylist = async (id: string) => {
const res = await safeCall<PlaylistContents>('GetPlaylist', {
playlistId: id,
});
if (res) setSelected(res);
};
useEffect(() => {
loadFavorites();
loadPlaylists();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<section className="view" id="view-library">
<div className="card">
<div className="card-head">
<h2>
{t('Your favorites')}{' '}
<span className="muted">
{s.favorites.length
? `· ${s.favorites.length}`
: ''}
</span>
</h2>
</div>
<div className="tracklist">
{!s.identity ? (
<EmptyRow text={t('Authenticate to use favorites')} />
) : !s.favorites.length ? (
<EmptyRow
text={t('No favorites yet — ♥ a track anywhere')}
/>
) : (
s.favorites.map((tr, i) => (
<TrackRow
key={tr.url || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query: tr.url || tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
{
icon: <CloseIcon />,
title: t('Remove'),
cls: 'danger',
onClick: async () => {
await safeCall('RemoveFavorite', {
url: tr.url,
});
toast(
t('Removed from favorites')
);
loadFavorites();
},
},
]}
/>
))
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h2>{t('Playlists')}</h2>
<button
className="btn btn-ghost"
onClick={async () => {
const name = await promptDialog({
title: t('Save playlist'),
message: t(
'Playlist name (saves the current queue):'
),
placeholder: t('Playlist name'),
confirmLabel: t('Save'),
});
if (!name) return;
await safeCall('SavePlaylist', {
name: name.trim(),
description: t('Saved from web UI'),
});
toast(tf('Playlist “{0}” saved', name));
loadPlaylists();
}}
>
{t('Save queue as playlist')}
</button>
</div>
<div className="grid-cards">
{!playlists.length ? (
<EmptyRow text={t('No playlists saved yet')} />
) : (
playlists.map((p, i) => (
<div
key={p.id}
className={
'playlist-card' +
(selected && selected.id === p.id
? ' active'
: '')
}
onClick={() => openPlaylist(p.id)}
>
<div
className="playlist-cover"
style={{ background: cover(i * 17 + 2) }}
/>
<div className="playlist-name">{p.name}</div>
<div className="playlist-meta">
{tf('{0} tracks', p.trackCount)}
</div>
<div className="playlist-actions">
<button
className="btn btn-ghost"
onClick={async (e) => {
e.stopPropagation();
toast(
tf(
'Loading playlist “{0}”…',
p.name
)
);
await safeCall('LoadPlaylist', {
playlistId: p.id,
});
}}
>
{t('Load')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async (e) => {
e.stopPropagation();
if (
!(await confirmDialog({
title: t('Delete playlist'),
message: tf(
'Delete playlist “{0}”? This cannot be undone.',
p.name
),
confirmLabel: t('Delete'),
danger: true,
}))
) {
return;
}
await safeCall('DeletePlaylist', {
playlistId: p.id,
});
toast(
tf(
'Playlist “{0}” deleted',
p.name
)
);
if (selected && selected.id === p.id)
setSelected(null);
loadPlaylists();
}}
>
{t('Delete')}
</button>
</div>
</div>
))
)}
</div>
</div>
{selected && (
<div className="card">
<div className="card-head">
<h2>
{selected.name}{' '}
<span className="muted">
{selected.tracks.length
? `· ${selected.tracks.length}`
: ''}
</span>
</h2>
<button
className="btn btn-ghost"
onClick={() => setSelected(null)}
>
{t('Close')}
</button>
</div>
<div className="tracklist">
{!selected.tracks.length ? (
<EmptyRow text={t('This playlist is empty')} />
) : (
selected.tracks.map((tr, i) => (
<TrackRow
key={tr.url || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query: tr.url || tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
]}
/>
))
)}
</div>
</div>
)}
</section>
);
}
+318
View File
@@ -0,0 +1,318 @@
import { useState } from 'react';
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { PlayerControls } from '../components/PlayerControls';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow';
import { NowPlayingVideo } from '../components/NowPlayingVideo';
import { LyricsPanel } from '../components/LyricsPanel';
import { coverStyle, sourceInfo } from '../lib/format';
import { youtubeIdFromUrl } from '../lib/youtube';
import {
HeartIcon,
RepeatIcon,
ShuffleIcon,
SkipPrevIcon,
} from '../components/icons';
import { t, tf } from '../i18n';
const VIDEO_PREF_KEY = 'echoion.npVideo';
async function togglePlay() {
const st = appStore.get().status || {};
if (st.isPlaying && !st.isPaused) await safeCall('Pause');
else await safeCall('Resume');
}
export function NowView() {
const s = useStore(appStore);
const [videoOn, setVideoOn] = useState(
localStorage.getItem(VIDEO_PREF_KEY) === '1'
);
const track = s.current;
const videoId = youtubeIdFromUrl(track?.url);
const videoAvailable = s.nowPlayingVideoAllowed && !!videoId;
const showVideo = videoAvailable && videoOn;
const st = s.status || {};
const src = track && sourceInfo(track);
const playing = !!st.isPlaying && !st.isPaused;
const volumePct = Math.round((st.volume ?? 0.5) * 100);
const durationMs = s.durationMs || track?.duration || 0;
const isFav = !!(track && track.url && s.favUrls.has(track.url));
const isAdmin = !!(s.identity && s.identity.isAdmin);
// Skipping over RPC is a force-skip (DJ/admin only, server-enforced);
// everyone else uses the vote-skip button. See item 15.
const canForceSkip = !!(
s.identity &&
(s.identity.isAdmin || s.identity.isDj)
);
const votes = st.skipVotes || 0;
const needed = st.skipVotesNeeded || 0;
return (
<section className="view" id="view-now">
<div className="now-grid">
<div className="card np-card">
{showVideo && videoId ? (
<NowPlayingVideo videoId={videoId} />
) : (
<div
className="np-cover"
style={{ background: coverStyle(track) }}
/>
)}
<div className="np-info">
{videoAvailable && (
<button
className={
'btn btn-ghost np-video-toggle' +
(videoOn ? ' on' : '')
}
onClick={() => {
const next = !videoOn;
setVideoOn(next);
localStorage.setItem(
VIDEO_PREF_KEY,
next ? '1' : '0'
);
}}
>
{videoOn
? t('Hide video')
: t('Watch video')}
</button>
)}
{src && <span className={src.cls}>{src.label}</span>}
<div className="np-title">
{track ? track.title : t('Nothing playing')}
</div>
<div className="np-artist">
{track ? track.artist || '' : ''}
</div>
<div className="np-added" />
<PlayerControls
playing={playing}
positionMs={s.positionMs}
durationMs={durationMs}
canControl
volumePct={volumePct}
onTogglePlay={togglePlay}
onSeekMs={(ms) =>
safeCall('Seek', { position: ms })
}
onVolume={(pct) =>
safeCall('SetVolume', { volume: pct / 100 })
}
onSkip={
canForceSkip
? () => safeCall('Skip', { count: 1 })
: undefined
}
extra={
<>
<button
className={
'ctrl' + (st.shuffle ? ' on' : '')
}
title={t('Shuffle')}
onClick={() =>
safeCall('ToggleShuffle')
}
>
<ShuffleIcon />
</button>
<button
className="ctrl"
title={t('Restart track')}
onClick={() =>
safeCall('Seek', { position: 0 })
}
>
<SkipPrevIcon />
</button>
<button
className={
'ctrl' + (st.repeat ? ' on' : '')
}
title={t('Repeat')}
onClick={() => safeCall('ToggleRepeat')}
>
<RepeatIcon />
</button>
<button
className={
'ctrl' + (isFav ? ' fav-on' : '')
}
title={t('Favorite')}
onClick={async () => {
if (!track) return;
if (isFav) {
await safeCall(
'RemoveFavorite',
{ url: track.url }
);
toast(
t('Removed from favorites')
);
} else {
await safeCall('AddFavorite', {
track,
});
toast(t('Added to favorites'));
}
loadFavorites();
}}
>
<HeartIcon />
</button>
<button
className={
'btn btn-ghost voteskip' +
(st.skipVoted ? ' on' : '')
}
title={t('Vote to skip')}
onClick={async () => {
const res = await safeCall<{
skipped?: boolean;
votes?: number;
needed?: number;
voted?: boolean;
}>('VoteSkip');
if (!res) return;
if (res.skipped) {
toast(
t(
'Vote passed — track skipped'
)
);
} else {
appStore.set({
status: {
...(appStore.get()
.status || {}),
skipVotes: res.votes,
skipVotesNeeded:
res.needed,
skipVoted: res.voted,
},
});
}
}}
>
<span>
{votes > 0
? tf(
'Vote skip {0}/{1}',
votes,
needed
)
: t('Vote skip')}
</span>
</button>
</>
}
extraLocal={
<label className="toggle-row">
<span className="muted">{t('Radio')}</span>
<button
type="button"
className={
'toggle' +
(st.autoplay ? ' on' : '')
}
onClick={async () => {
if (!isAdmin) {
toast(
t(
'Radio mode is admin-only — ask an admin or use !autoplay'
)
);
return;
}
const res = await safeCall<{
autoplay?: boolean;
}>('ToggleAutoplay');
if (res) {
appStore.set({
status: {
...(appStore.get()
.status || {}),
autoplay: res.autoplay,
},
});
toast(
res.autoplay
? t('Radio mode on')
: t('Radio mode off')
);
}
}}
>
<span className="knob" />
</button>
</label>
}
/>
</div>
</div>
<div className="col">
<div className="card">
<div className="card-head">
<h2>{t('Up Next')}</h2>
<button
className="link"
onClick={() => showView('queue')}
>
{t('Open queue →')}
</button>
</div>
<div className="tracklist">
{(() => {
const upcoming = s.queue
.filter((q) => !q.isPlaying)
.slice(0, 4);
if (!upcoming.length) {
return (
<EmptyRow text={t('Queue is empty')} />
);
}
return upcoming.map((q, i) => (
<TrackRow
key={q.queueId}
track={q.track}
num={i + 1}
/>
));
})()}
</div>
</div>
<LyricsPanel />
<div className="card">
<div className="card-head">
<h3>{t('Listening now')}</h3>
</div>
<div className="people">
{!s.listeners.filter((u) => u.online).length ? (
<EmptyRow
text={t('Nobody online right now')}
/>
) : (
s.listeners
.filter((u) => u.online)
.slice(0, 6)
.map((u, i) => (
<PersonRow
key={i}
name={u.nickname || u.uid}
uid={u.uid}
sub={t('Listening')}
/>
))
)}
</div>
</div>
</div>
</div>
</section>
);
}
+164
View File
@@ -0,0 +1,164 @@
import { useState } from 'react';
import { appStore, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { originalLinkAction } from '../lib/links';
import { confirmDialog } from '../lib/dialog';
import { CloseIcon, PlayIcon } from '../components/icons';
import { t, tf } from '../i18n';
async function playNow(queueId: number) {
await safeCall('MoveInQueue', { queueId, newPosition: 0 });
await safeCall('Skip', { count: 1 });
toast(t('Playing now'));
}
export function QueueView() {
const s = useStore(appStore);
const [dragQueueId, setDragQueueId] = useState<number | null>(null);
// Index where the dragged row would be inserted; drives the drop-line
// indicator so the user can see the landing spot (item 9).
const [dropIndex, setDropIndex] = useState<number | null>(null);
const commitDrop = () => {
if (dragQueueId != null && dropIndex != null) {
const from = s.queue.findIndex((e) => e.queueId === dragQueueId);
// Dropping below its own slot shifts the target down by one.
let target = dropIndex;
if (from !== -1 && from < dropIndex) target -= 1;
if (from !== target) {
safeCall('MoveInQueue', {
queueId: dragQueueId,
newPosition: target,
});
}
}
setDragQueueId(null);
setDropIndex(null);
};
return (
<section className="view" id="view-queue">
<div className="card">
<div className="card-head">
<h2>
{t('Queue')}{' '}
<span className="muted">
{s.queue.length
? `· ${tf('{0} tracks', s.queue.length)}`
: ''}
</span>
</h2>
<div className="row-gap">
<button
className="btn btn-ghost"
onClick={() => safeCall('ShuffleQueue')}
>
{t('Shuffle queue')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
!(await confirmDialog({
title: t('Clear queue'),
message: t('Clear the whole queue?'),
confirmLabel: t('Clear'),
danger: true,
}))
)
return;
await safeCall('ClearQueue');
toast(t('Queue cleared'));
}}
>
{t('Clear')}
</button>
</div>
</div>
<div
className="tracklist"
onDragLeave={(e) => {
// Only clear when leaving the list entirely.
if (
!e.currentTarget.contains(
e.relatedTarget as Node | null
)
) {
setDropIndex(null);
}
}}
onDrop={commitDrop}
>
{!s.queue.length ? (
<EmptyRow
text={t('Queue is empty — add something from Search')}
/>
) : (
s.queue.map((entry, i) => (
<div key={entry.queueId}>
{dragQueueId != null && dropIndex === i && (
<div className="drop-indicator" />
)}
<TrackRow
track={entry.track}
num={i + 1}
playing={entry.isPlaying}
actions={[
originalLinkAction(entry.track),
{
icon: <PlayIcon />,
title: t('Play now'),
onClick: () =>
playNow(entry.queueId),
},
{
icon: <CloseIcon />,
title: t('Remove'),
cls: 'danger',
onClick: () =>
safeCall('RemoveFromQueue', {
queueId: entry.queueId,
}),
},
]}
rowProps={{
draggable: !entry.isPlaying,
className:
dragQueueId === entry.queueId
? 'dragging'
: undefined,
onDragStart: () =>
setDragQueueId(entry.queueId),
onDragEnd: () => {
setDragQueueId(null);
setDropIndex(null);
},
onDragOver: (e) => {
e.preventDefault();
const r =
e.currentTarget.getBoundingClientRect();
const after =
e.clientY > r.top + r.height / 2;
setDropIndex(after ? i + 1 : i);
},
onDrop: (e) => {
e.preventDefault();
e.stopPropagation();
commitDrop();
},
}}
/>
</div>
))
)}
{dragQueueId != null &&
dropIndex === s.queue.length &&
s.queue.length > 0 && (
<div className="drop-indicator" />
)}
</div>
</div>
</section>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { useEffect, useState } from 'react';
import { getStoredToken, safeCall, toast } from '../lib/app';
import type { ServerInfo } from '../lib/types';
import { t, tf } from '../i18n';
async function resolveWsUrl(): Promise<string> {
let cfg: { rpcUrl?: string; rpcPort?: number } = {};
try {
cfg = await fetch('/config.json').then((r) => r.json());
} catch {
/* ignore */
}
const wsProto = location.protocol === 'https:' ? 'wss' : 'ws';
if (cfg.rpcUrl && cfg.rpcUrl.startsWith('/')) {
return `${wsProto}://${location.host}${cfg.rpcUrl}`;
}
if (cfg.rpcUrl && cfg.rpcUrl.length) return cfg.rpcUrl;
return `ws://${location.hostname}:${cfg.rpcPort || 8765}`;
}
export function RpcView() {
const [wsUrl, setWsUrl] = useState('');
const [uptime, setUptime] = useState('');
useEffect(() => {
resolveWsUrl().then(setWsUrl);
safeCall<ServerInfo>('GetServerInfo').then((info) => {
if (info && typeof info.uptimeSeconds === 'number') {
const h = Math.floor(info.uptimeSeconds / 3600);
setUptime(`up ${Math.floor(h / 24)}d ${h % 24}h`);
}
});
}, []);
const token = getStoredToken() || t('(authenticate first)');
const fields: Array<[string, string]> = [
['WEBSOCKET ENDPOINT', wsUrl],
['AUTH TOKEN', token],
[
'PROTOCOL',
'JSON over WebSocket · method names, params as JSON string',
],
];
const snippet = [
`const ws = new WebSocket('${wsUrl}');`,
`ws.onopen = () => ws.send(JSON.stringify({`,
` id: 1, method: 'Authenticate',`,
` params: JSON.stringify({ token: '<your token>' })`,
`}));`,
`ws.onmessage = (e) => console.log(JSON.parse(e.data));`,
].join('\n');
return (
<section className="view" id="view-rpc">
<div className="card">
<div className="card-head">
<h2>{t('Connect programmatically')}</h2>
<span className="pill">{uptime}</span>
</div>
<div className="rpc-fields">
{fields.map(([label, value]) => (
<div key={label} className="rpc-field">
<span className="rpc-label">{label}</span>
<span className="rpc-value">{value}</span>
<button
className="icon-btn"
title={t('Copy')}
onClick={() => {
navigator.clipboard
.writeText(value)
.catch(() => {});
toast(tf('{0} copied', label.toLowerCase()));
}}
>
⧉
</button>
</div>
))}
</div>
<pre className="code-block">{snippet}</pre>
<button
className="btn btn-ghost"
onClick={() => {
navigator.clipboard.writeText(snippet).catch(() => {});
toast(t('Snippet copied'));
}}
>
{t('Copy snippet')}
</button>
</div>
</section>
);
}
+123
View File
@@ -0,0 +1,123 @@
import { useState } from 'react';
import { appStore, loadFavorites, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { sourceInfo } from '../lib/format';
import type { Track } from '../lib/types';
import { HeartIcon } from '../components/icons';
import { t, tf } from '../i18n';
export function SearchView() {
const s = useStore(appStore);
const [query, setQuery] = useState('');
let items = s.searchResults;
if (s.searchTab === 'youtube') {
items = items.filter(
(tr) => (sourceInfo(tr) || {}).label === 'YOUTUBE'
);
}
if (s.searchTab === 'yandex') {
items = items.filter((tr) => (sourceInfo(tr) || {}).label === 'YANDEX');
}
return (
<section className="view" id="view-search">
<form
className="search-row"
onSubmit={async (e) => {
e.preventDefault();
const q = query.trim();
if (!q) return;
toast(tf('Searching “{0}”…', q));
const res = await safeCall<{ tracks?: Track[] }>(
'SearchTracks',
{ query: q }
);
appStore.set({ searchResults: (res && res.tracks) || [] });
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t(
'Search YouTube and Yandex Music… or paste a URL'
)}
autoComplete="off"
/>
<button className="btn btn-accent" type="submit">
{t('Search')}
</button>
</form>
<div className="tabs">
{(['all', 'youtube', 'yandex'] as const).map((tab) => (
<button
key={tab}
className={
'tab' + (s.searchTab === tab ? ' active' : '')
}
onClick={() => appStore.set({ searchTab: tab })}
>
{tab === 'all'
? t('All')
: tab === 'youtube'
? 'YouTube'
: 'Yandex'}
</button>
))}
</div>
<div className="card">
<div className="tracklist">
{!items.length ? (
<EmptyRow
text={t('No results yet — search for something')}
/>
) : (
items.map((tr, i) => (
<TrackRow
key={tr.url || tr.id || i}
track={tr}
num={i + 1}
actions={[
{
icon: '+',
title: t('Add to queue'),
onClick: async () => {
await safeCall('QueueTrack', {
query:
tr.url ||
tr.id ||
tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
{
icon: <HeartIcon />,
title: t('Save to favorites'),
cls:
tr.url && s.favUrls.has(tr.url)
? 'fav-on'
: undefined,
onClick: async () => {
await safeCall('AddFavorite', {
track: tr,
});
toast(t('Saved to favorites'));
loadFavorites();
},
},
]}
/>
))
)}
</div>
</div>
</section>
);
}
+215
View File
@@ -0,0 +1,215 @@
import { useCallback, useEffect, useState } from 'react';
import { appStore, safeCall, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { EmptyRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow';
import { AnnounceModal } from '../components/AnnounceModal';
import { EmojiManager } from '../components/EmojiManager';
import type { AuditEntry, Subscriber } from '../lib/types';
import { auditMethodName } from '../lib/auditMethods';
import { confirmDialog } from '../lib/dialog';
import { t, tf } from '../i18n';
export function ServerView() {
const s = useStore(appStore);
const [users, setUsers] = useState<Subscriber[]>([]);
const [audit, setAudit] = useState<AuditEntry[]>([]);
const [announceOpen, setAnnounceOpen] = useState(false);
const isAdmin = !!(s.identity && s.identity.isAdmin);
const loadSubscribers = useCallback(async () => {
if (!isAdmin) return;
const res = await safeCall<{ users?: Subscriber[] }>('ManageUsers', {
action: 'list',
});
const list = (res && res.users) || [];
setUsers(list);
appStore.set({ listeners: list });
}, [isAdmin]);
const loadAudit = useCallback(async () => {
if (!isAdmin) return;
const res = await safeCall<{ entries?: AuditEntry[] }>('GetAuditLog');
// Newest first — the server keeps a bounded ring in insertion order.
setAudit(((res && res.entries) || []).slice().reverse());
}, [isAdmin]);
useEffect(() => {
loadSubscribers();
loadAudit();
}, [loadSubscribers, loadAudit]);
return (
<section className="view" id="view-server">
<div className="card">
<div className="card-head">
<h2>
{t('Subscribers')}{' '}
<span className="muted">
{users.length ? `· ${users.length}` : ''}
</span>
</h2>
<div className="row-gap">
<button
className="btn btn-ghost"
onClick={() => setAnnounceOpen(true)}
>
{t('Announce…')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
await safeCall('ReloadConfig');
toast(t('Configuration reloaded'));
}}
>
{t('Reload config')}
</button>
<button
className="btn btn-ghost"
title={t(
'Stop and start the web server without touching the bot'
)}
onClick={async () => {
if (
!(await confirmDialog({
title: t('Restart web UI'),
message: t(
'Restart the web interface? Everyone disconnects briefly.'
),
confirmLabel: t('Restart'),
}))
) {
return;
}
const res = await safeCall(
'RestartWebInterface'
);
if (res) {
toast(
t(
'Web interface restarting — this page will reconnect'
)
);
}
}}
>
{t('Restart web UI')}
</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 className="people">
{!users.length ? (
<EmptyRow text={t('No subscribers')} />
) : (
users.map((u) => (
<PersonRow
key={u.uid}
name={u.nickname || u.uid}
uid={u.uid}
sub={u.uid}
status={u.online ? t('Online') : t('Offline')}
statusColor={u.online ? '#5fe094' : '#6a6a78'}
>
<button
className="btn btn-danger-ghost"
onClick={async () => {
const who = u.nickname || u.uid;
if (
!(await confirmDialog({
title: t('Unsubscribe'),
message: tf(
'Unsubscribe {0}?',
who
),
confirmLabel: t('Unsub'),
danger: true,
}))
) {
return;
}
await safeCall('ManageUsers', {
action: 'remove',
uid: u.uid,
});
toast(tf('Unsubscribed {0}', who));
loadSubscribers();
}}
>
{t('Unsub')}
</button>
</PersonRow>
))
)}
</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)} />
)}
</section>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { useEffect, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow';
import { originalLinkAction } from '../lib/links';
import type { AggregateStats, Track } from '../lib/types';
import { t, tf } from '../i18n';
export function StatsView() {
const [agg, setAgg] = useState<AggregateStats | null>(null);
const [history, setHistory] = useState<Track[]>([]);
useEffect(() => {
(async () => {
const [aggRes, historyRes] = await Promise.all([
safeCall<AggregateStats>('GetAggregateStats'),
safeCall<{ tracks?: Track[] }>('GetHistory', { limit: 12 }),
]);
setAgg(aggRes);
setHistory((historyRes && historyRes.tracks) || []);
})();
}, []);
const total = agg
? agg.youtubeCount + agg.yandexCount + agg.otherCount
: 0;
const ytPct = total && agg ? Math.round((agg.youtubeCount / total) * 100) : 0;
const yaPct = total && agg ? Math.round((agg.yandexCount / total) * 100) : 0;
const cards = agg
? (() => {
const hours = (agg.listeningMsToday / 3600000).toFixed(1);
const skipRate =
agg.playsTotal > 0
? (
(agg.skipsTotal /
(agg.playsTotal + agg.skipsTotal)) *
100
).toFixed(1)
: '0';
return [
{
label: t('Tracks played today'),
value: String(agg.tracksToday),
delta: tf('{0} all-time', agg.playsTotal),
up: agg.tracksToday > 0,
},
{
label: t('Listening hours'),
value: `${hours}h`,
delta: t('today'),
up: false,
},
{
label: t('Queue additions'),
value: String(agg.queueAdditionsToday),
delta: t('today'),
up: agg.queueAdditionsToday > 0,
},
{
label: t('Skips'),
value: String(agg.skipsToday),
delta: tf('{0}% skip rate', skipRate),
up: false,
},
];
})()
: [];
return (
<section className="view" id="view-stats">
<div className="stat-cards">
{cards.map((c, i) => (
<div key={i} className="stat-card">
<div className="stat-label">{c.label}</div>
<div className="stat-value mono">{c.value}</div>
<div className={'stat-delta' + (c.up ? ' up' : '')}>
{c.delta}
</div>
</div>
))}
</div>
<div className="stats-grid">
<div className="card">
<div className="card-head">
<h2>{t('Recently played')}</h2>
</div>
<div className="tracklist">
{!history.length ? (
<EmptyRow text={t('Nothing played yet')} />
) : (
history.map((tr, i) => (
<TrackRow
key={i}
track={tr}
num={i + 1}
actions={[
originalLinkAction(tr),
{
icon: '+',
title: t('Queue again'),
onClick: async () => {
await safeCall('QueueTrack', {
query: tr.url || tr.title,
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
},
},
]}
/>
))
)}
</div>
</div>
<div className="col">
<div className="card">
<div className="card-head">
<h3>{t('Top requesters')}</h3>
</div>
<div className="people">
{!agg || !agg.topRequesters.length ? (
<EmptyRow text={t('No requests logged yet')} />
) : (
agg.topRequesters.map((r, i) => (
<PersonRow
key={i}
name={r.nickname}
uid={r.uid}
sub={tf('{0} requests', r.count)}
/>
))
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h3>{t('Source split')}</h3>
</div>
<div className="split-bar">
<div
className="split-yt"
style={{ width: `${ytPct}%` }}
/>
<div
className="split-ya"
style={{ width: `${yaPct}%` }}
/>
</div>
<div className="split-legend">
<span>
<span
className="dot"
style={{ background: '#ff8080' }}
/>
YouTube <b className="mono">{ytPct}%</b>
</span>
<span>
<span
className="dot"
style={{ background: '#ffd977' }}
/>
Yandex <b className="mono">{yaPct}%</b>
</span>
</div>
</div>
</div>
</div>
</section>
);
}
+789
View File
@@ -0,0 +1,789 @@
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>
);
}
+18
View File
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"noEmit": true,
"types": ["vite/client", "youtube"]
},
"include": ["src"]
}
+26
View File
@@ -0,0 +1,26 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// Dev workflow: run the bot with web.enabled, then `npm run dev` — the vite
// dev server proxies the bot's HTTP endpoints and WebSockets so the app runs
// against live state with hot reload. Production build lands in ../web-dist
// (consumed by EchoionWeb/CMakeLists.txt).
export default defineConfig({
plugins: [react()],
build: {
// Output inside frontend/ (gitignored); CMake copies it to bin/web
// and installs it. Kept in-tree so a C++-only build with
// -DECHOION_BUILD_WEB=OFF can still ship a prior snapshot.
outDir: 'web-dist',
emptyOutDir: true,
},
server: {
proxy: {
'/config.json': 'http://127.0.0.1:8080',
'/avatar': 'http://127.0.0.1:8080',
'/rpc': { target: 'ws://127.0.0.1:8080', ws: true },
'/ws': { target: 'ws://127.0.0.1:8080', ws: true },
},
cors: true
},
});
+153
View File
@@ -0,0 +1,153 @@
#pragma once
#include "echoion/web/WatchSession.hpp"
#include <Void/Async/ThreadPool.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <atomic>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <thread>
#include <unordered_map>
namespace Echoion::Web
{
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
// Serves the static browser UI over HTTP, hosts the independent
// sync-watch WebSocket at GET /ws, and tunnels GET /rpc upgrades to the
// local RPC server so only the web port ever needs to be exposed. It has
// no handle on the music bot itself.
class HttpServer
{
public:
struct Config {
uint16_t port = 8080;
std::string bindAddress = "127.0.0.1";
std::string webRoot = "./web";
// Explicit RPC URL served to the browser; when empty the UI
// derives ws://<page-host>:<rpcPort>.
std::string rpcUrl;
uint16_t rpcPort = 8765;
// Server-wide switch for the Now Playing video preview,
// surfaced to the browser via /config.json.
bool nowPlayingVideo = true;
};
HttpServer();
~HttpServer();
bool start(const Config& config);
void stop();
[[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
// by Core (which owns the TeamSpeak plugin handle); best-effort —
// nullopt yields a 404 and the UI falls back to initials. Same
// lifetime rules as the identity resolver.
struct AvatarImage {
std::string contentType;
std::string bytes;
};
using AvatarProvider = std::function<std::optional<AvatarImage>(
const std::string& uid)>;
void setAvatarProvider(AvatarProvider provider)
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
avatarProvider_ = std::move(provider);
}
// A custom emoji image, served at GET /emoji/<name>. Same shape
// and lifetime rules as the avatar provider; installed by Core
// (which owns the emoji database).
using EmojiProvider = std::function<std::optional<AvatarImage>(
const std::string& name)>;
void setEmojiProvider(EmojiProvider provider)
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
emojiProvider_ = std::move(provider);
}
private:
void acceptLoop();
void doAccept();
void onAccept(asio::ip::tcp::socket socket);
void handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
void handleWatch(
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
// Tunnel a browser WebSocket upgrade at /rpc to the local RPC
// server as raw TCP: the original upgrade request is replayed
// upstream and bytes are pumped in both directions, so the real
// handshake/auth all happen against the RPC server itself.
void bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
http::request<http::string_body>& req,
beast::flat_buffer& residual);
// Serves one request; returns true when the connection should be
// kept open for the next request (HTTP keep-alive).
bool serveHttp(asio::ip::tcp::socket& socket,
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_;
asio::io_context ioContext_;
std::optional<asio::ip::tcp::acceptor> acceptor_;
std::thread serverThread_;
std::atomic<bool> running_{false};
// Per-connection handlers run on a worker pool; ~ThreadPool drains
// and joins them on stop.
static constexpr std::size_t POOL_SIZE = 32;
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};
// Live /rpc bridges (browser, upstream); shut down on stop() so
// the blocking pump loops unblock and the pool can join.
std::unordered_map<uint64_t,
std::pair<std::shared_ptr<asio::ip::tcp::socket>,
std::shared_ptr<asio::ip::tcp::socket>>>
bridges_;
std::mutex bridgesMutex_;
WatchSessionManager watch_;
std::jthread syncThread_;
// Called from pool threads; guarded so Core can (re)install them
// at any time. Both share one mutex (installed together at start).
AvatarProvider avatarProvider_;
EmojiProvider emojiProvider_;
std::mutex avatarProviderMutex_;
};
} // namespace Echoion::Web
+200
View File
@@ -0,0 +1,200 @@
#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
+859
View File
@@ -0,0 +1,859 @@
#include "echoion/web/HttpServer.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Net/Http.hpp>
#include <array>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <sstream>
#include <string_view>
namespace Echoion::Web
{
namespace
{
std::string_view contentType(const std::filesystem::path& path)
{
const std::string ext = path.extension().string();
if (ext == ".html") {
return "text/html; charset=utf-8";
}
if (ext == ".js") {
return "text/javascript; charset=utf-8";
}
if (ext == ".css") {
return "text/css; charset=utf-8";
}
if (ext == ".json") {
return "application/json; charset=utf-8";
}
if (ext == ".svg") {
return "image/svg+xml";
}
if (ext == ".png") {
return "image/png";
}
if (ext == ".ico") {
return "image/x-icon";
}
if (ext == ".woff2") {
return "font/woff2";
}
return "application/octet-stream";
}
std::optional<std::string> readFile(const std::filesystem::path& path)
{
std::ifstream file(path, std::ios::binary);
if (!file) {
return std::nullopt;
}
std::ostringstream ss;
ss << file.rdbuf();
return ss.str();
}
// Percent-decode one URL path segment (TeamSpeak uids are base64 and
// carry '+', '/', '=' — the browser sends them encoded).
std::string urlDecode(std::string_view in)
{
std::string out;
out.reserve(in.size());
for (std::size_t i = 0; i < in.size(); ++i) {
if (in[i] == '%' && i + 2 < in.size()) {
const auto hex = [](char c) -> int {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
};
const int hi = hex(in[i + 1]);
const int lo = hex(in[i + 2]);
if (hi >= 0 && lo >= 0) {
out += static_cast<char>(hi * 16 + lo);
i += 2;
continue;
}
}
out += in[i];
}
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
// shut down so the opposite pump unblocks too.
void pumpBytes(boost::asio::ip::tcp::socket& from,
boost::asio::ip::tcp::socket& to)
{
std::array<char, 8192> buf;
boost::system::error_code ec;
for (;;) {
const std::size_t n =
from.read_some(boost::asio::buffer(buf), ec);
if (ec || n == 0) {
break;
}
boost::asio::write(to, boost::asio::buffer(buf.data(), n), ec);
if (ec) {
break;
}
}
boost::system::error_code ignore;
from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore);
}
} // namespace
HttpServer::HttpServer() = default;
HttpServer::~HttpServer() { stop(); }
bool HttpServer::start(const Config& config)
{
if (running_.exchange(true)) {
return false;
}
config_ = config;
try {
ioContext_.restart();
asio::ip::tcp::endpoint endpoint(
asio::ip::make_address(config_.bindAddress), config_.port);
acceptor_.emplace(ioContext_);
acceptor_->open(endpoint.protocol());
acceptor_->set_option(asio::ip::tcp::acceptor::reuse_address(true));
acceptor_->bind(endpoint);
acceptor_->listen();
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);
syncThread_ =
std::jthread([this](std::stop_token st) { syncLoop(st); });
// A wrong webRoot only surfaces as bare 404s in the browser —
// call it out at startup instead.
const auto indexPath =
std::filesystem::path(config_.webRoot) / "index.html";
std::error_code fsEc;
if (!std::filesystem::exists(indexPath, fsEc)) {
Void::Log::warn(
"HttpServer", "{}",
std::format("webRoot '{}' has no index.html — the web UI "
"will return 404; copy the shipped web/ "
"assets (build/bin/web) there",
config_.webRoot));
}
Void::Log::info("HttpServer", "{}",
std::format("Web interface listening on {}:{}",
config_.bindAddress, config_.port));
return true;
} catch (const std::exception& e) {
running_ = false;
Void::Log::error(
"HttpServer", "{}",
std::format("Failed to start web interface: {}", e.what()));
return false;
}
}
void HttpServer::stop()
{
if (!running_.exchange(false)) {
return;
}
try {
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->cancel(ec);
}
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.
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
for (auto& [id, pair] : bridges_) {
boost::system::error_code ec;
pair.first->shutdown(asio::ip::tcp::socket::shutdown_both,
ec);
pair.second->shutdown(asio::ip::tcp::socket::shutdown_both,
ec);
}
bridges_.clear();
}
// Closed sockets make each handler's read() fail and return, then
// ~ThreadPool joins every worker.
pool_.reset();
if (serverThread_.joinable()) {
serverThread_.join();
}
if (acceptor_.has_value()) {
boost::system::error_code ec;
acceptor_->close(ec);
}
Void::Log::info("HttpServer", "{}", "Web interface stopped");
} catch (const std::exception& e) {
Void::Log::error(
"HttpServer", "{}",
std::format("Error stopping web interface: {}", e.what()));
}
}
void HttpServer::acceptLoop()
{
// Same interruptible async re-arm model as the RPC server: stop()
// cancels the acceptor (pending accept completes with operation_aborted
// and does not re-arm) and stops the context, so run() returns.
doAccept();
for (;;) {
try {
ioContext_.run();
break;
} catch (const std::exception& e) {
Void::Log::error(
"HttpServer", "{}",
std::format("Web accept loop error: {}", e.what()));
if (!running_.load()) {
break;
}
}
}
}
void HttpServer::doAccept()
{
auto socket = std::make_shared<asio::ip::tcp::socket>(ioContext_);
acceptor_->async_accept(
*socket, [this, socket](const boost::system::error_code& ec) {
if (ec == asio::error::operation_aborted || !running_.load()) {
return;
}
if (ec) {
Void::Log::warn(
"HttpServer", "{}",
std::format("Web accept failed: {}", ec.message()));
} else {
onAccept(std::move(*socket));
}
if (running_.load()) {
doAccept();
}
});
}
void HttpServer::onAccept(asio::ip::tcp::socket socket)
{
// Hand off to the pool: reading the request (and any subsequent
// WebSocket loop) is blocking and must not stall the accept thread.
auto held = std::make_shared<asio::ip::tcp::socket>(std::move(socket));
if (pool_) {
pool_->submit([this, held]() { handleConnection(held); });
}
}
void HttpServer::handleConnection(
std::shared_ptr<asio::ip::tcp::socket> socket)
{
beast::error_code ec;
beast::flat_buffer buffer;
// Serve requests on this connection until the peer closes, an error
// occurs, or the request asks not to keep the connection alive.
while (running_.load()) {
http::request<http::string_body> req;
http::read(*socket, buffer, req, ec);
if (ec) {
return;
}
if (websocket::is_upgrade(req)) {
if (req.target() == "/rpc") {
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;
}
if (!serveHttp(*socket, req)) {
return;
}
}
}
void HttpServer::bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
http::request<http::string_body>& req,
beast::flat_buffer& residual)
{
boost::system::error_code ec;
auto upstream = std::make_shared<asio::ip::tcp::socket>(ioContext_);
upstream->connect(
asio::ip::tcp::endpoint(asio::ip::make_address("127.0.0.1"),
config_.rpcPort),
ec);
if (ec) {
Void::Log::warn(
"HttpServer", "{}",
std::format("RPC bridge: cannot reach RPC server on "
"127.0.0.1:{}: {}",
config_.rpcPort, ec.message()));
return;
}
// Forward the browser's effective IP so the RPC server can offer
// address-based autologin. Never trust a client-supplied value; a
// reverse proxy's X-Forwarded-For (first hop) wins over the socket
// address because the proxy connects from its own host.
req.erase("X-Echoion-Client-Ip");
std::string clientIp;
if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) {
clientIp = std::string(xff->value());
if (auto comma = clientIp.find(','); comma != std::string::npos) {
clientIp = clientIp.substr(0, comma);
}
while (!clientIp.empty() && clientIp.front() == ' ') {
clientIp.erase(clientIp.begin());
}
}
if (clientIp.empty()) {
boost::system::error_code epEc;
if (auto ep = browser->remote_endpoint(epEc); !epEc) {
clientIp = ep.address().to_string();
}
}
if (!clientIp.empty()) {
req.set("X-Echoion-Client-Ip", clientIp);
}
// Replay the browser's upgrade request (plus any bytes already read
// past it) so the real WebSocket handshake happens against the RPC
// server itself.
http::write(*upstream, req, ec);
if (!ec && residual.size() > 0) {
asio::write(*upstream, residual.data(), ec);
}
if (ec) {
return;
}
const uint64_t connId = nextConnId_++;
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
bridges_[connId] = {browser, upstream};
}
Void::Log::debug("HttpServer", "{}",
std::format("RPC bridge {} opened", connId));
// Each direction owns its socket's read side; either side failing
// shuts both down, unblocking the other pump.
std::thread down(
[browser, upstream]() { pumpBytes(*upstream, *browser); });
pumpBytes(*browser, *upstream);
down.join();
{
std::lock_guard<std::mutex> lock(bridgesMutex_);
bridges_.erase(connId);
}
Void::Log::debug("HttpServer", "{}",
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,
const http::request<http::string_body>& req)
{
beast::error_code ec;
const bool isHead = req.method() == http::verb::head;
auto respond = [&](http::status status, std::string_view type,
std::string body, std::string_view cacheControl = {},
std::string_view lastModified = {}) {
http::response<http::string_body> res{status, req.version()};
res.set(http::field::server, "Echoion");
res.set(http::field::content_type, type);
if (!cacheControl.empty()) {
res.set(http::field::cache_control, cacheControl);
}
if (!lastModified.empty()) {
res.set(http::field::last_modified, lastModified);
}
res.keep_alive(req.keep_alive());
// HEAD advertises the real Content-Length but carries no body.
res.content_length(
status == http::status::not_modified ? 0 : body.size());
if (!isHead && status != http::status::not_modified) {
res.body() = std::move(body);
}
http::write(socket, res, ec);
};
if (req.method() != http::verb::get && !isHead) {
respond(http::status::method_not_allowed, "text/plain",
"Method Not Allowed");
return !ec && req.keep_alive();
}
std::string target(req.target());
if (auto q = target.find('?'); q != std::string::npos) {
target = target.substr(0, q);
}
// Tells the browser where the RPC server lives. By default it is the
// same-origin /rpc bridge, so only the web port needs exposing; an
// explicitly configured rpcUrl still overrides.
if (target == "/config.json") {
using Void::Json::Value;
const std::string rpcUrl =
config_.rpcUrl.empty() ? "/rpc" : config_.rpcUrl;
respond(
http::status::ok, "application/json",
Void::Json::serialize(Void::Json::object(
{{"rpcUrl", Value{rpcUrl}},
{"rpcPort",
Value{static_cast<long long>(config_.rpcPort)}},
{"nowPlayingVideo", Value{config_.nowPlayingVideo}}})));
return !ec && req.keep_alive();
}
// User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap
// without pinning stale avatars for long.
constexpr std::string_view kAvatarPrefix = "/avatar/";
if (target.starts_with(kAvatarPrefix)) {
// The query string (the web UI appends ?v=N to bypass the browser's
// negative cache when retrying) is already stripped from `target`
// above, so the remainder is just the encoded uid.
const std::string uid =
urlDecode(target.substr(kAvatarPrefix.size()));
AvatarProvider provider;
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
provider = avatarProvider_;
}
Void::Log::info("HttpServer", "{}",
std::format("GET /avatar uid='{}' provider={}", uid,
provider ? "set" : "none"));
if (!uid.empty() && provider) {
if (auto image = provider(uid)) {
Void::Log::info(
"HttpServer", "{}",
std::format("avatar 200 uid='{}' type={} bytes={}", uid,
image->contentType, image->bytes.size()));
respond(http::status::ok, image->contentType,
std::move(image->bytes), "private, max-age=300");
return !ec && req.keep_alive();
}
}
Void::Log::info("HttpServer", "{}",
std::format("avatar 404 uid='{}'", uid));
respond(http::status::not_found, "text/plain", "Not Found",
"private, max-age=60");
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 == "/") {
target = "/index.html";
}
// Reject path traversal outright.
if (target.find("..") != std::string::npos) {
respond(http::status::bad_request, "text/plain", "Bad Request");
return !ec && req.keep_alive();
}
std::filesystem::path path =
std::filesystem::path(config_.webRoot) / target.substr(1);
auto contents = readFile(path);
if (!contents) {
respond(http::status::not_found, "text/plain", "Not Found");
return !ec && req.keep_alive();
}
// Fonts and Vite's content-hashed bundle assets (/assets/*, e.g.
// index-Bq3KBlm7.js) are immutable-forever — a content change mints a
// new filename. Everything else (index.html, /config.json, fonts.css)
// revalidates cheaply via Last-Modified.
const bool immutable =
path.extension() == ".woff2" || target.starts_with("/assets/");
const std::string_view cache =
immutable ? "public, max-age=31536000, immutable" : "no-cache";
std::string lastModified;
std::error_code fsEc;
if (auto ftime = std::filesystem::last_write_time(path, fsEc); !fsEc) {
const auto sys =
std::chrono::clock_cast<std::chrono::system_clock>(ftime);
lastModified =
std::format("{:%a, %d %b %Y %H:%M:%S} GMT",
std::chrono::floor<std::chrono::seconds>(sys));
}
if (!lastModified.empty()) {
if (auto ims = req.find(http::field::if_modified_since);
ims != req.end() && ims->value() == lastModified) {
respond(http::status::not_modified, contentType(path), "",
cache, lastModified);
return !ec && req.keep_alive();
}
}
respond(http::status::ok, contentType(path), std::move(*contents),
cache, lastModified);
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
+849
View File
@@ -0,0 +1,849 @@
#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