Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-15 19:50:44 +03:00
1 parent ef3139ca64
commit 818d391022
59 files changed
+2336 -8080

No files matched your search

+2
View File
@@ -1,4 +1,6 @@
*build*
release
.claude
.cache
.idea
AGENTS.md
-3
View File
@@ -4,9 +4,6 @@
[submodule "EchoionCore"]
path = EchoionCore
url = ssh://gitea@git.faumaray.ru/void/echoioncore.git
[submodule "EchoionPlugin"]
path = EchoionPlugin
url = ssh://gitea@git.faumaray.ru/void/echoionplugin.git
[submodule "EchoionDesktop"]
path = EchoionDesktop
url = ssh://gitea@git.faumaray.ru/void/echoiondesktop.git
+4 -14
View File
@@ -127,10 +127,9 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# Options
option(BUILD_API "Build EchoionApi" ON)
option(BUILD_CORE "Build EchoionCore" ON)
option(BUILD_PLUGIN "Build archived EchoionPlugin compatibility target" OFF)
option(BUILD_DESKTOP "Build EchoionDesktop" ON)
option(BUILD_WEB "Build EchoionWeb (browser interface + sync-watch)" ON)
option(BUILD_STANDALONE "Build EchoionStandalone (daemon; no TeamSpeak client)" ON)
option(BUILD_WEB "Build EchoionWeb browser dashboard" ON)
option(BUILD_STANDALONE "Build EchoionStandalone daemon with native TeamSpeak client" ON)
option(BUILD_TESTS "Build tests" OFF)
if(BUILD_TESTS)
@@ -145,7 +144,7 @@ if(BUILD_API)
add_subdirectory(EchoionApi)
endif()
if(BUILD_PLUGIN OR BUILD_STANDALONE)
if(BUILD_STANDALONE)
add_subdirectory(EchoionHost)
endif()
@@ -164,12 +163,8 @@ if(BUILD_WEB AND BUILD_CORE)
endif()
endif()
if(BUILD_PLUGIN)
add_subdirectory(EchoionPlugin)
endif()
# VoidTeamspeak is resolved above as a regular reusable package. The legacy
# in-tree EchoionProtocol directory is intentionally no longer built.
# TeamSpeak client plugin and in-tree protocol directories are no longer built.
# EchoionStandalone links the host-common loader and native protocol client.
if(BUILD_STANDALONE)
@@ -282,10 +277,6 @@ if(BUILD_CORE AND TARGET EchoionCore)
install_with_dependencies(EchoionCore)
endif()
if(BUILD_PLUGIN AND TARGET EchoionPlugin)
install_with_dependencies(EchoionPlugin)
endif()
# Print configuration summary
message(STATUS "")
message(STATUS "Echoion Configuration:")
@@ -293,7 +284,6 @@ message(STATUS " Version: ${PROJECT_VERSION}")
message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS " Build API: ${BUILD_API}")
message(STATUS " Build Core: ${BUILD_CORE}")
message(STATUS " Build Plugin: ${BUILD_PLUGIN}")
message(STATUS " Build Desktop: ${BUILD_DESKTOP}")
message(STATUS " Build Tests: ${BUILD_TESTS}")
message(STATUS " Static Link: ${ECHOION_STATIC_LINK}")
Submodule EchoionPlugin deleted from 470ab507e1.
@@ -1,10 +1,8 @@
#pragma once
// Implements Echoion's IPluginInterface against the native TeamSpeak UDP
// protocol through VoidTeamspeak instead of the TS3 Client Plugin SDK. This is the
// single seam that lets the whole Core run as a standalone application: Core
// only ever talks to IPluginInterface, so swapping this implementation in for
// the plugin drops the TeamSpeak-client dependency entirely.
// Implements Echoion's host interface by adapting VoidTeamspeak's typed client
// operations and events. TeamSpeak protocol details remain inside
// VoidTeamspeak; Core only sees the host-neutral Echoion API contract.
#include <PluginInterface.hpp>
@@ -63,12 +61,42 @@ namespace Echoion::Standalone
uint64_t channelId) override;
Api::Result<void> kickClient(uint64_t clientId,
const std::string& reason) override;
Api::Result<void>
kickClientFromChannel(uint64_t clientId,
const std::string& reason) override;
Api::Result<void> banClient(uint64_t clientId,
uint64_t durationSeconds,
const std::string& reason) override;
[[nodiscard]] Api::Result<std::vector<Api::BanInfo>>
getBans() override;
Api::Result<void> unban(uint64_t banId) override;
// Channels
[[nodiscard]] Api::Result<std::vector<Api::ChannelInfo>>
getChannels() const override;
[[nodiscard]] Api::Result<std::optional<Api::ChannelInfo>>
getChannel(uint64_t channelId) const override;
Api::Result<uint64_t> createChannel(
const Api::ChannelCreateOptions& options) override;
Api::Result<void>
editChannel(uint64_t channelId,
const Api::ChannelEditOptions& options) override;
Api::Result<void> reorderChannel(uint64_t channelId,
uint64_t parentId,
uint64_t orderAfterId) override;
Api::Result<void> deleteChannel(uint64_t channelId,
bool force) override;
[[nodiscard]] Api::Result<std::vector<Api::ServerGroupInfo>>
getServerGroups() override;
Api::Result<void>
addClientToServerGroup(uint64_t groupId,
uint64_t clientDatabaseId) override;
Api::Result<void>
removeClientFromServerGroup(uint64_t groupId,
uint64_t clientDatabaseId) override;
[[nodiscard]] Api::Result<Api::ServerInfo>
getTeamSpeakServerInfo() override;
// Messaging
Api::Result<void>
@@ -85,14 +113,6 @@ namespace Echoion::Standalone
sendAudioData(const std::span<const short>& data) override;
Api::Result<void>
setWhisperList(const std::vector<uint64_t>& clientIds) override;
[[nodiscard]] Api::Result<AudioStreamId>
createAudioStream(const AudioStreamOptions& options) override;
Api::Result<void> destroyAudioStream(AudioStreamId id) override;
Api::Result<void> sendAudioDataToStream(
AudioStreamId id, const std::span<const short>& data) override;
Api::Result<void> setAudioStreamRecipients(
AudioStreamId id,
const std::vector<uint64_t>& recipients) override;
// Connection
Api::Result<void>
@@ -102,28 +122,22 @@ namespace Echoion::Standalone
Api::Result<void> reconnect() override;
// Events
void
registerEventCallback(const Api::EventCallback& cb) override;
void
unregisterEventCallback(const Api::EventCallback& cb) override;
// Prevent new event dispatches, release registered callbacks and wait
// until every callback already in flight has returned. The host must
// call this before unloading code that owns an event callback.
void registerEventCallback(const Api::EventCallback& cb) override;
void unregisterEventCallback(const Api::EventCallback& cb) override;
// Prevent new event dispatches, release registered callbacks and
// wait until every callback already in flight has returned. The
// host must call this before unloading code that owns an event
// callback.
void quiesceEventCallbacks();
private:
void wireCallbacks();
void onCommand(std::string_view name,
const std::vector<Void::TeamSpeak::CommandFields>& records);
void onTextMessage(const Void::TeamSpeak::CommandFields& params);
void broadcast(const Api::PluginEvent& event);
void upsertClientGroup(const Void::TeamSpeak::CommandFields& p,
bool emitConnected);
void refreshClient(const Void::TeamSpeak::CommandFields& params);
void loadInitialSnapshot();
[[nodiscard]] Api::Result<void> commandResult(
const Void::Result::Result<void, Void::TeamSpeak::Error>& result) const;
const Void::Result::Result<void, Void::TeamSpeak::Error>&
result) const;
StandaloneSettings settings_;
std::shared_ptr<Void::TeamSpeak::Identity> identity_;
@@ -134,17 +148,14 @@ namespace Echoion::Standalone
std::atomic<bool> initialized_{false};
mutable std::mutex mirrorMutex_;
std::map<uint64_t, Api::ClientInfo> clients_;
std::map<uint64_t, Api::ChannelInfo> channels_;
std::map<uint64_t, Void::TeamSpeak::RemoteClient> clients_;
std::map<uint64_t, Void::TeamSpeak::Channel> channels_;
std::optional<Void::TeamSpeak::ServerInfo> serverInfo_;
std::map<uint64_t, std::string> clientIps_;
std::map<uint64_t, std::string> avatarHashes_;
std::map<uint64_t, std::string> avatarUrls_;
std::map<uint64_t, std::string> avatarPaths_;
std::vector<uint64_t> whisperList_;
struct AudioStreamRuntime;
std::map<AudioStreamId, std::shared_ptr<AudioStreamRuntime>> audioStreams_;
std::atomic<AudioStreamId> nextAudioStreamId_{1};
mutable std::mutex audioStreamsMutex_;
std::jthread snapshotThread_;
EventCallbackGate eventCallbacks_;
File diff suppressed because it is too large. Load diff
+67 -61
View File
@@ -1,21 +1,16 @@
// Standalone Echoion host.
//
// Replaces the TeamSpeak-client + plugin sandwich: loads the same hot-reloadable
// Core shared library via the (TeamSpeak-independent) CoreLoader, but backs
// IPluginInterface with a native TeamSpeak UDP protocol client instead of the
// TS3 Client Plugin SDK. The bot therefore runs as a plain daemon — no
// TeamSpeak client, no Weston/RDP, no plugin directory.
// Standalone Echoion host. It loads the hot-reloadable Core through CoreLoader
// and adapts Echoion's host contract to VoidTeamspeak's typed client API.
#include "echoion/host/CoreLoader.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include "echoion/standalone/ReleaseManifest.hpp"
#include "echoion/standalone/StandaloneClientInterface.hpp"
#include <CoreInterface.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/System/FileWatcher.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <atomic>
@@ -50,8 +45,8 @@ namespace
g_cv.notify_all();
}
std::optional<std::string_view> argumentValue(
int argc, char** argv, std::string_view name)
std::optional<std::string_view> argumentValue(int argc, char** argv,
std::string_view name)
{
for (int index = 1; index + 1 < argc; ++index) {
if (std::string_view{argv[index]} == name) {
@@ -76,14 +71,17 @@ namespace
{
const auto transaction = directory / "release-transaction";
if (!std::filesystem::exists(transaction) ||
std::getenv("ECHOION_REEXEC_VERSION")) return;
std::getenv("ECHOION_REEXEC_VERSION")) {
return;
}
auto version = Void::FileSystem::read_file(transaction);
if (version && !version->empty()) {
std::ignore = Void::FileSystem::atomic_write(
directory / "failed-release", *version);
Void::Log::error("main",
"Release {} failed its startup health check; stable service restored",
*version);
"Release {} failed its startup health check; "
"stable service restored",
*version);
}
std::ignore = Void::FileSystem::remove_path(transaction);
}
@@ -132,10 +130,9 @@ namespace
for (int i = 1; i < argc; ++i) {
const std::string_view argument{argv[i]};
if (argument == "--help") {
std::cout
<< "Usage: echoiond [--config PATH]\n"
" echoiond --import-identity EXPORT.ini "
"[--identity-path PATH] [--force]\n";
std::cout << "Usage: echoiond [--config PATH]\n"
" echoiond --import-identity EXPORT.ini "
"[--identity-path PATH] [--force]\n";
return 0;
}
if (argument == "--import-identity") {
@@ -165,7 +162,8 @@ namespace
}
const auto identity =
Void::TeamSpeak::Identity::importTeamSpeakIni(source->string());
if (const auto parent = destination.parent_path(); !parent.empty()) {
if (const auto parent = destination.parent_path();
!parent.empty()) {
std::filesystem::create_directories(parent);
}
identity.save(destination.string());
@@ -186,9 +184,10 @@ int main(int argc, char** argv)
std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n';
std::abort();
});
if (const auto validationPath = argumentValue(argc, argv,
"--validate-release")) {
auto manifest = Echoion::Standalone::ReleaseManifest::load(*validationPath);
if (const auto validationPath =
argumentValue(argc, argv, "--validate-release")) {
auto manifest =
Echoion::Standalone::ReleaseManifest::load(*validationPath);
if (!manifest) {
std::cerr << manifest.error().message << '\n';
return 2;
@@ -203,8 +202,8 @@ int main(int argc, char** argv)
std::filesystem::path cfgDir = configDir();
recordInterruptedRelease(cfgDir);
std::filesystem::path cfgPath = cfgDir / "config.json";
const auto identityPath = std::filesystem::path(envOr(
"ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()));
const auto identityPath = std::filesystem::path(
envOr("ECHOION_IDENTITY_PATH", (cfgDir / "identity.txt").string()));
if (const auto importResult = importIdentity(argc, argv, identityPath);
importResult >= 0) {
return importResult;
@@ -222,8 +221,9 @@ int main(int argc, char** argv)
settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8);
settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000);
auto interface = std::make_shared<Echoion::Standalone::StandaloneClientInterface>(
settings);
auto interface =
std::make_shared<Echoion::Standalone::StandaloneClientInterface>(
settings);
if (auto r = interface->initialize(); !r) {
Void::Log::error("main", "interface init failed: {}",
r.error().message);
@@ -242,7 +242,7 @@ int main(int argc, char** argv)
if (const auto restorePath = argumentValue(argc, argv, "--restore-state")) {
if (auto result = loader.restoreCheckpoint(*restorePath); !result) {
Void::Log::error("main", "failed to restore restart checkpoint: {}",
result.error().message);
result.error().message);
return 1;
}
}
@@ -254,12 +254,12 @@ int main(int argc, char** argv)
}
core->setPluginInterface(interface);
interface->registerEventCallback([core](const Echoion::Api::PluginEvent& ev) {
std::ignore = core->onPluginEvent(ev);
});
loader.setHotReloadPrepareCallback([interface] {
interface->quiesceEventCallbacks();
});
interface->registerEventCallback(
[core](const Echoion::Api::PluginEvent& ev) {
std::ignore = core->onPluginEvent(ev);
});
loader.setHotReloadPrepareCallback(
[interface] { interface->quiesceEventCallbacks(); });
// Re-register the Core callback after each hot reload (new Core instance).
loader.setHotReloadCallback([&loader, interface] {
if (auto c = loader.getCore()) {
@@ -278,14 +278,15 @@ int main(int argc, char** argv)
if (const char* manifest = std::getenv("ECHOION_RELEASE_MANIFEST")) {
releaseManifestPath = manifest;
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(*releaseManifestPath,
releaseWatcher->watch(
*releaseManifestPath,
[](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
requestUpdate();
}
});
Void::Log::info("main", "Watching release manifest {}",
releaseManifestPath->string());
releaseManifestPath->string());
} else {
// Compatibility mode for development. Production release bundles use
// transactional daemon re-exec instead of replacing Core in isolation.
@@ -296,13 +297,14 @@ int main(int argc, char** argv)
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
std::ignore = Void::FileSystem::atomic_write(
cfgDir / "release-health", version);
std::ignore = Void::FileSystem::remove_path(
cfgDir / "release-transaction");
std::ignore =
Void::FileSystem::atomic_write(cfgDir / "release-health", version);
std::ignore =
Void::FileSystem::remove_path(cfgDir / "release-transaction");
std::ignore = Void::FileSystem::remove_path(cfgDir / "failed-release");
::unsetenv("ECHOION_REEXEC_VERSION");
Void::Log::info("main", "Release {} passed startup health check", version);
Void::Log::info("main", "Release {} passed startup health check",
version);
}
std::optional<Echoion::Standalone::ReleaseManifest> pendingRelease;
@@ -310,49 +312,52 @@ int main(int argc, char** argv)
while (!g_stop.load() && !pendingRelease) {
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock, [] {
return g_stop.load() || g_updateRequested.load();
});
g_cv.wait(lock,
[] { return g_stop.load() || g_updateRequested.load(); });
}
if (g_stop.load() || !releaseManifestPath) {
break;
}
g_updateRequested = false;
auto manifest = Echoion::Standalone::ReleaseManifest::load(
*releaseManifestPath);
auto manifest =
Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath);
if (!manifest) {
Void::Log::error("main", "release rejected: {}",
manifest.error().message);
manifest.error().message);
continue;
}
if (auto failed = Void::FileSystem::read_file(cfgDir / "failed-release");
if (auto failed =
Void::FileSystem::read_file(cfgDir / "failed-release");
failed && *failed == manifest->version) {
Void::Log::error("main",
"Release {} was previously rolled back; publish a new version to retry",
manifest->version);
"Release {} was previously rolled back; publish a "
"new version to retry",
manifest->version);
continue;
}
auto executable = std::filesystem::canonical("/proc/self/exe");
auto validation = Void::Process::run(executable,
{"--validate-release", releaseManifestPath->string()}, {},
std::chrono::seconds{30});
auto validation = Void::Process::run(
executable, {"--validate-release", releaseManifestPath->string()},
{}, std::chrono::seconds{30});
if (!validation || validation->exit_code != 0) {
Void::Log::error("main", "release validation failed: {}",
validation ? validation->err : validation.error().message());
validation ? validation->err
: validation.error().message());
continue;
}
checkpointPath = configDir() / "restart-state.bin";
if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) {
Void::Log::error("main", "release checkpoint failed: {}",
checkpoint.error().message);
checkpoint.error().message);
continue;
}
pendingRelease = std::move(*manifest);
}
releaseWatcher.reset();
Void::Log::info("main", "{}", pendingRelease
? "Applying validated release..." : "Shutting down...");
Void::Log::info("main", "{}",
pendingRelease ? "Applying validated release..."
: "Shutting down...");
loader.disableAutoReload();
(void)interface->disconnectFromServer();
interface->quiesceEventCallbacks();
@@ -360,10 +365,10 @@ int main(int argc, char** argv)
(void)interface->shutdown();
if (pendingRelease) {
if (auto transaction = Void::FileSystem::atomic_write(
cfgDir / "release-transaction", pendingRelease->version);
cfgDir / "release-transaction", pendingRelease->version);
!transaction) {
Void::Log::error("main", "cannot record release transaction: {}",
transaction.error().message());
transaction.error().message());
return 1;
}
::setenv("ECHOION_CORE_PATH", pendingRelease->core.c_str(), 1);
@@ -380,10 +385,11 @@ int main(int argc, char** argv)
}
arguments.emplace_back("--restore-state");
arguments.push_back(checkpointPath.string());
if (auto result = Void::Process::reexec(pendingRelease->executable,
arguments); !result) {
if (auto result =
Void::Process::reexec(pendingRelease->executable, arguments);
!result) {
Void::Log::error("main", "release re-exec failed: {}",
result.error().message());
result.error().message());
return 1;
}
}
+1 -2
View File
@@ -37,7 +37,6 @@ target_link_libraries(EchoionWeb
Void::Data
Void::Log
Void::Async
Void::Net
PRIVATE
Threads::Threads
Boost::beast
@@ -56,7 +55,7 @@ endif()
# 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)
option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON)
set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend")
set(_web_dist "${_web_frontend}/web-dist")
@@ -1,7 +1,7 @@
{
"name": "Echoion Music Bot",
"short_name": "Echoion",
"description": "Control the Echoion TeamSpeak music bot — play, queue, search and watch together.",
"description": "Control the Echoion TeamSpeak music bot and view live server activity.",
"start_url": "/",
"scope": "/",
"display": "standalone",
+6 -7
View File
@@ -1,12 +1,12 @@
// 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.
// live surfaces — /rpc (WebSockets aren't interceptable anyway),
// /config.json, /api/* and /avatar/* 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 CACHE = 'echoion-shell-v4';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => {
@@ -48,10 +48,9 @@ self.addEventListener('fetch', (event) => {
// Never intercept the live control/config/media surfaces.
if (
url.pathname === '/config.json' ||
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/ws') ||
url.pathname.startsWith('/avatar') ||
url.pathname.startsWith('/emoji')
url.pathname.startsWith('/avatar')
) {
return;
}
+2 -18
View File
@@ -5,11 +5,8 @@
// - 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.
//
@@ -25,17 +22,6 @@ 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',
@@ -48,8 +34,8 @@ const KNOWN_DYNAMIC = new Set([
'Focus search',
'This help',
// HEADS view titles/subtitles (App.tsx)
'Now Playing',
'What Echoion is streaming to the channel',
'Dashboard',
'Live playback and TeamSpeak server activity',
'Queue',
'Reorder and manage upcoming tracks',
'Search',
@@ -58,8 +44,6 @@ const KNOWN_DYNAMIC = new Set([
'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',
+6 -26
View File
@@ -1,6 +1,5 @@
import { useEffect } from 'react';
import { appStore, boot, getStoredToken, toast } from './lib/app';
import { initWatch } from './lib/watch';
import { appStore, boot } from './lib/app';
import { initRouter } from './lib/router';
import { initShortcuts } from './lib/shortcuts';
import { initMediaSession } from './lib/mediaSession';
@@ -11,24 +10,20 @@ 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 { DashboardView } from './views/DashboardView';
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';
import { RoomsView } from './views/RoomsView';
const HEADS: Record<string, [string, string]> = {
now: ['Now Playing', 'What Echoion is streaming to the channel'],
dashboard: ['Dashboard', 'Live playback and TeamSpeak server activity'],
queue: ['Queue', 'Reorder and manage upcoming tracks'],
search: ['Search', 'Find tracks across YouTube and Yandex Music'],
library: ['Library', 'Your favorites and saved playlists'],
stats: ['History & Stats', 'Playback history and server insights'],
rooms: ['Listening Rooms', 'Independent music streams for different groups'],
watch: ['Watch Together', 'Synced viewing room — everyone in step'],
server: ['Server & Admin', 'Manage subscribers and broadcast'],
rpc: ['RPC / API', 'Connect to Echoion programmatically'],
};
@@ -39,20 +34,12 @@ export function App() {
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;
const [title, sub] = HEADS[s.view] || HEADS.dashboard;
return (
<div id="app">
@@ -84,7 +71,7 @@ export function App() {
<div className="header-right">
<span className="pill">
<span className="dot dot-green" />
{s.onlineCount}&nbsp;{t('listening')}
{s.onlineCount}&nbsp;{t('online')}
</span>
<button
className="icon-btn"
@@ -99,18 +86,11 @@ export function App() {
</div>
</header>
{s.view === 'now' && <NowView />}
{s.view === 'dashboard' && <DashboardView />}
{s.view === 'queue' && <QueueView />}
{s.view === 'search' && <SearchView />}
{s.view === 'library' && <LibraryView />}
{s.view === 'stats' && <StatsView />}
{s.view === 'rooms' && <RoomsView />}
{/* The watch view stays mounted so the embedded player and
room connection survive view switches (the old UI only
toggled `hidden`). */}
<div hidden={s.view !== 'watch'}>
<WatchView />
</div>
{s.view === 'server' && <ServerView />}
{s.view === 'rpc' && <RpcView />}
@@ -1,112 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { useStore } from '../lib/store';
import { emojiStore, loadCustomEmojis } from '../lib/emoji';
import { safeCall, toast } from '../lib/app';
import { CloseIcon } from './icons';
import { t } from '../i18n';
// Admin custom-emoji manager (item 16): upload an image (≤64KB) under a
// shortcode name, list existing ones, and remove them. The image is sent as
// base64 to AddCustomEmoji and served back at /emoji/<name>.
export function EmojiManager() {
const { custom } = useStore(emojiStore);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
loadCustomEmojis();
}, []);
const upload = async () => {
const file = fileRef.current?.files?.[0];
const clean = name.trim().toLowerCase();
if (!/^[a-z0-9_]{1,32}$/.test(clean)) {
toast(t('Emoji name must be 1-32 chars of a-z, 0-9, _'));
return;
}
if (!file) {
toast(t('Choose an image file'));
return;
}
if (file.size > 64 * 1024) {
toast(t('Emoji image too large (max ~64KB)'));
return;
}
setBusy(true);
const dataBase64 = await new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const res = String(reader.result);
resolve(res.slice(res.indexOf(',') + 1)); // strip data: prefix
};
reader.readAsDataURL(file);
});
const res = await safeCall('AddCustomEmoji', {
name: clean,
mime: file.type,
dataBase64,
});
setBusy(false);
if (res) {
toast(t('Emoji added'));
setName('');
if (fileRef.current) fileRef.current.value = '';
loadCustomEmojis();
}
};
return (
<div className="card">
<div className="card-head">
<h2>
{t('Custom emojis')}{' '}
<span className="muted">
{custom.length ? `· ${custom.length}` : ''}
</span>
</h2>
</div>
<div className="emoji-manage-row">
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder={t('shortcode (a-z0-9_)')}
maxLength={32}
/>
<input ref={fileRef} type="file" accept="image/*" />
<button
className="btn btn-accent"
disabled={busy}
onClick={upload}
>
{t('Add emoji')}
</button>
</div>
<div className="emoji-manage-grid">
{custom.map((c) => (
<div key={c.name} className="emoji-manage-item">
<img
className="emoji-img-lg"
src={`/emoji/${c.name}`}
alt={c.name}
/>
<span className="mono">:{c.name}:</span>
<button
className="icon-btn danger"
title={t('Remove')}
onClick={async () => {
await safeCall('RemoveCustomEmoji', {
name: c.name,
});
toast(t('Emoji removed'));
loadCustomEmojis();
}}
>
<CloseIcon />
</button>
</div>
))}
</div>
</div>
);
}
@@ -1,113 +0,0 @@
import { useEffect, useRef } from 'react';
import { useStore } from '../lib/store';
import {
EMOJI_CATEGORIES,
emojiStore,
rememberEmoji,
} from '../lib/emoji';
import { t } from '../i18n';
// A popover emoji picker: recently-used, curated Unicode categories, and the
// server's custom image emojis. `onPick` receives either a unicode char or a
// :shortcode: for a custom emoji.
export function EmojiPicker(props: {
onPick: (token: string) => void;
onClose: () => void;
}) {
const { custom, recent } = useStore(emojiStore);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
props.onClose();
}
};
// Defer so the opening click doesn't immediately close it.
const id = setTimeout(
() => document.addEventListener('mousedown', onDoc),
0
);
return () => {
clearTimeout(id);
document.removeEventListener('mousedown', onDoc);
};
}, [props]);
const pick = (token: string) => {
rememberEmoji(token);
props.onPick(token);
};
return (
<div className="emoji-picker" ref={ref}>
{recent.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Recent')}</div>
<div className="emoji-grid">
{recent.map((token, i) =>
token.startsWith(':') ? (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
<img
src={`/emoji/${token.slice(1, -1)}`}
alt={token}
className="emoji-img"
/>
</button>
) : (
<button
key={i}
className="emoji-btn"
onClick={() => pick(token)}
>
{token}
</button>
)
)}
</div>
</div>
)}
{custom.length > 0 && (
<div className="emoji-section">
<div className="emoji-section-label">{t('Custom')}</div>
<div className="emoji-grid">
{custom.map((c) => (
<button
key={c.name}
className="emoji-btn"
title={`:${c.name}:`}
onClick={() => pick(`:${c.name}:`)}
>
<img
src={`/emoji/${c.name}`}
alt={c.name}
className="emoji-img"
/>
</button>
))}
</div>
</div>
)}
{EMOJI_CATEGORIES.map((cat) => (
<div key={cat.label} className="emoji-section">
<div className="emoji-section-label">{cat.label}</div>
<div className="emoji-grid">
{cat.emoji.map((e) => (
<button
key={e}
className="emoji-btn"
onClick={() => pick(e)}
>
{e}
</button>
))}
</div>
</div>
))}
</div>
);
}
@@ -14,7 +14,7 @@ async function togglePlay() {
// 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;
if (s.view === 'dashboard' || !s.current) return null;
const playing = !!(s.status && s.status.isPlaying && !s.status.isPaused);
const canForceSkip = !!(
s.identity &&
@@ -11,11 +11,9 @@ import {
} 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.
// Dashboard playback controls. This component is presentational; authenticated
// RPC callbacks are supplied by the dashboard while visitors receive a
// disabled, read-only transport surface.
export function PlayerControls(props: {
playing: boolean;
positionMs: number;
@@ -45,7 +43,7 @@ export function PlayerControls(props: {
: 0;
return (
<div className="player-controls">
<div className="watch-controls">
<div className="player-control-row">
<button
className="ctrl ctrl-main"
title={t('Play/Pause')}
@@ -102,7 +100,7 @@ export function PlayerControls(props: {
{props.extra}
</div>
{(props.showLocal ?? true) && (
<div className="watch-controls watch-local">
<div className="player-control-row player-local-row">
<span className="muted">{t('Vol')}</span>
<Bar
slim
@@ -1,99 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import type { PlayerExtraControl } from '../lib/embedProtocols';
import { t } from '../i18n';
import { GearIcon } from './icons';
export function PlayerSettingsMenu(props: {
extras: PlayerExtraControl[];
rate: number;
rateOptions?: number[];
canControl: boolean;
onExtra: (id: string, value: string) => void;
onRate: (rate: number) => void;
}) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const local = props.extras.filter((control) => control.scope === 'local');
const room = props.extras.filter(
(control) => control.scope === 'synced' && control.id !== 'speed'
);
const hasRoom = room.length > 0 || !!props.rateOptions?.length;
useEffect(() => {
if (!open) return;
const close = (event: MouseEvent) => {
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', close);
return () => document.removeEventListener('mousedown', close);
}, [open]);
if (local.length === 0 && !hasRoom) return null;
const renderControl = (control: PlayerExtraControl) => (
<label className="player-setting" key={control.id}>
<span>{t(control.label)}</span>
<select
value={control.current ?? ''}
disabled={control.scope === 'synced' && !props.canControl}
title={
control.scope === 'synced' && !props.canControl
? t('Only the host can change this')
: undefined
}
onChange={(event) => props.onExtra(control.id, event.target.value)}
>
{control.current == null && <option value="">{t('Choose')}</option>}
{control.options.map((option) => (
<option key={option.value} value={option.value}>
{t(option.label)}
</option>
))}
</select>
</label>
);
return (
<div className="player-settings" ref={rootRef}>
<button
className="ctrl"
title={t('Settings')}
aria-expanded={open}
onClick={() => setOpen((value) => !value)}
>
<GearIcon />
</button>
{open && (
<div className="player-settings-popover">
{local.length > 0 && (
<section>
<div className="player-settings-heading">{t('Local')}</div>
{local.map(renderControl)}
</section>
)}
{hasRoom && (
<section>
<div className="player-settings-heading">{t('Room')}</div>
{props.rateOptions && (
<label className="player-setting">
<span>{t('Speed')}</span>
<select
value={String(props.rate)}
disabled={!props.canControl}
onChange={(event) =>
props.onRate(Number(event.target.value))
}
>
{props.rateOptions.map((rate) => (
<option key={rate} value={rate}>{rate}×</option>
))}
</select>
</label>
)}
{room.map(renderControl)}
</section>
)}
</div>
)}
</div>
);
}
+20 -6
View File
@@ -18,7 +18,6 @@ import {
HeartIcon,
PlayIcon,
QueueIcon,
RoomsIcon,
SearchIcon,
StatsIcon,
WatchIcon,
@@ -26,13 +25,11 @@ import {
import { t, useLanguage } from '../i18n';
const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [
{ view: 'now', icon: <PlayIcon />, label: 'Now Playing' },
{ view: 'dashboard', icon: <PlayIcon />, label: 'Dashboard' },
{ view: 'queue', icon: <QueueIcon />, label: 'Queue' },
{ view: 'search', icon: <SearchIcon />, label: 'Search' },
{ view: 'library', icon: <HeartIcon />, label: 'Library' },
{ view: 'stats', icon: <StatsIcon />, label: 'History & Stats' },
{ view: 'rooms', icon: <RoomsIcon />, label: 'Listening Rooms' },
{ view: 'watch', icon: <WatchIcon />, label: 'Watch Together' },
{ view: 'server', icon: <GearIcon />, label: 'Server & Admin' },
{ view: 'rpc', icon: <CodeIcon />, label: 'RPC / API' },
];
@@ -74,13 +71,14 @@ export function Sidebar() {
<button
key={item.view}
className={
'nav-item' + (s.view === item.view ? ' active' : '')
'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 && (
{item.view === 'dashboard' && playing && (
<span className="live-dot" />
)}
{item.view === 'queue' && s.queue.length > 0 && (
@@ -88,6 +86,22 @@ export function Sidebar() {
)}
</button>
))}
{s.watchUrl && (
<a
className="nav-item"
href={s.watchUrl}
target="_blank"
rel="noreferrer"
>
<span className="nav-ico">
<WatchIcon />
</span>
{t('Watch Together')}
<span className="nav-external" aria-hidden="true">
↗
</span>
</a>
)}
</nav>
<div className="sidebar-foot">
@@ -0,0 +1,472 @@
import { useCallback, useEffect, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type { RpcMethodName } from '../lib/rpc';
import { confirmDialog, promptDialog } from '../lib/dialog';
import { EmptyRow } from './TrackRow';
import { t, tf } from '../i18n';
interface AdminClient {
id: number;
databaseId: number | null;
uid: string | null;
nickname: string;
channelId: number;
talking: boolean;
muted: boolean;
deafened: boolean;
away: boolean;
groups: number[];
}
interface AdminChannel {
id: number;
name: string;
parentId: number | null;
default: boolean;
password: boolean;
maxClients: number;
currentClients: number;
clients: AdminClient[];
channels: AdminChannel[];
}
interface DirectoryResponse {
server: {
name: string;
connected: boolean;
clientCount: number;
maxClients: number;
};
channels: AdminChannel[];
}
interface Ban {
id: number;
uid: string | null;
nickname: string | null;
reason: string;
createdAt: number;
durationSeconds: number;
}
interface ServerGroup {
id: number;
name: string;
default: boolean;
}
export function TeamSpeakAdmin() {
const [directory, setDirectory] = useState<DirectoryResponse | null>(null);
const [bans, setBans] = useState<Ban[]>([]);
const [groups, setGroups] = useState<ServerGroup[]>([]);
const [loading, setLoading] = useState(false);
const refresh = useCallback(async () => {
setLoading(true);
const [nextDirectory, nextBans, nextGroups] = await Promise.all([
safeCall<DirectoryResponse>('GetTeamSpeakDirectory'),
safeCall<{ bans?: Ban[] }>('GetTeamSpeakBans'),
safeCall<{ groups?: ServerGroup[] }>('GetTeamSpeakServerGroups'),
]);
if (nextDirectory) setDirectory(nextDirectory);
if (nextBans) setBans(nextBans.bans || []);
if (nextGroups) setGroups(nextGroups.groups || []);
setLoading(false);
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
const mutate = useCallback(
async (
method: RpcMethodName,
params: Record<string, unknown>,
message: string
) => {
const result = await safeCall(method, params);
if (!result) return false;
toast(message);
await refresh();
return true;
},
[refresh]
);
async function sendServerMessage() {
const message = await promptDialog({
title: t('Server message'),
message: t('Message sent to every connected TeamSpeak client:'),
confirmLabel: t('Send'),
});
if (message) {
await mutate(
'SendTeamSpeakServerMessage',
{ message },
t('Server message sent')
);
}
}
async function createChannel(parentId = 0) {
const name = await promptDialog({
title: t('Create channel'),
message: t('Channel name:'),
confirmLabel: t('Create'),
});
if (name) {
await mutate(
'CreateTeamSpeakChannel',
{ name, parentId, permanent: true },
t('Channel created')
);
}
}
function ClientRow({ client }: { client: AdminClient }) {
return (
<div className="ts-admin-client">
<div className="ts-admin-client-main">
<span
className={'ts-presence' + (client.talking ? ' talking' : '')}
/>
<strong>{client.nickname}</strong>
<span className="muted">#{client.id}</span>
{client.away && <span className="ts-tag">{t('away')}</span>}
{client.muted && <span className="ts-tag">{t('muted')}</span>}
{client.deafened && <span className="ts-tag">{t('deafened')}</span>}
</div>
<div className="ts-admin-private muted">
<span>UID: {client.uid || '—'}</span>
<span>DB: {client.databaseId || '—'}</span>
<span>{t('Groups')}: {client.groups.join(', ') || '—'}</span>
</div>
<div className="ts-admin-actions">
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', client.nickname),
message: t('Private message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakPrivateMessage',
{ clientId: client.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const channelId = await promptDialog({
title: tf('Move {0}', client.nickname),
message: t('Destination channel ID:'),
confirmLabel: t('Move'),
});
if (channelId && /^\d+$/.test(channelId))
await mutate(
'MoveTeamSpeakClient',
{ clientId: client.id, channelId: Number(channelId) },
t('Client moved')
);
}}
>
{t('Move')}
</button>
{client.databaseId && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Add server group'),
message: groups.length
? groups.map((g) => `${g.id}: ${g.name}`).join('\n')
: t('Server group ID:'),
confirmLabel: t('Add'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'AddTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group added')
);
}}
>
{t('Add group')}
</button>
)}
{client.databaseId && client.groups.length > 0 && (
<button
className="btn btn-ghost"
onClick={async () => {
const groupId = await promptDialog({
title: t('Remove server group'),
message: `${t('Current groups')}: ${client.groups.join(', ')}`,
confirmLabel: t('Remove'),
});
if (groupId && /^\d+$/.test(groupId))
await mutate(
'RemoveTeamSpeakServerGroupMember',
{
groupId: Number(groupId),
clientDatabaseId: client.databaseId,
},
t('Group removed')
);
}}
>
{t('Remove group')}
</button>
)}
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: tf('Kick {0}', client.nickname),
message: t('Kick this client from the server?'),
confirmLabel: t('Kick'),
danger: true,
})
)
await mutate(
'KickTeamSpeakClient',
{ clientId: client.id, fromServer: true },
t('Client kicked')
);
}}
>
{t('Kick')}
</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
const duration = await promptDialog({
title: tf('Ban {0}', client.nickname),
message: t('Duration in seconds (0 = permanent):'),
confirmLabel: t('Continue'),
});
if (!duration || !/^\d+$/.test(duration)) return;
if (
await confirmDialog({
title: tf('Ban {0}', client.nickname),
message: t('Apply this ban now?'),
confirmLabel: t('Ban'),
danger: true,
})
)
await mutate(
'BanTeamSpeakClient',
{
clientId: client.id,
durationSeconds: Number(duration),
},
t('Client banned')
);
}}
>
{t('Ban')}
</button>
</div>
</div>
);
}
function Channel({ channel, depth = 0 }: { channel: AdminChannel; depth?: number }) {
return (
<div className="ts-admin-channel" style={{ marginLeft: depth * 16 }}>
<div className="ts-admin-channel-head">
<strong>{channel.name}</strong>
<span className="muted">#{channel.id}</span>
<span className="ts-capacity">
{channel.currentClients}/{channel.maxClients || '∞'}
</span>
<button className="btn btn-ghost" onClick={() => createChannel(channel.id)}>
{t('Add child')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const name = await promptDialog({
title: t('Rename channel'),
message: channel.name,
confirmLabel: t('Save'),
});
if (name)
await mutate(
'EditTeamSpeakChannel',
{ channelId: channel.id, name },
t('Channel updated')
);
}}
>
{t('Edit')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const message = await promptDialog({
title: tf('Message {0}', channel.name),
message: t('Channel message:'),
confirmLabel: t('Send'),
});
if (message)
await mutate(
'SendTeamSpeakChannelMessage',
{ channelId: channel.id, message },
t('Message sent')
);
}}
>
{t('Message')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
const parentId = await promptDialog({
title: t('Reorder channel'),
message: t('Parent channel ID (0 = root):'),
confirmLabel: t('Continue'),
});
if (parentId === null || !/^\d+$/.test(parentId)) return;
const orderAfterId = await promptDialog({
title: t('Reorder channel'),
message: t('Previous sibling channel ID (0 = first):'),
confirmLabel: t('Move'),
});
if (orderAfterId === null || !/^\d+$/.test(orderAfterId)) return;
await mutate(
'ReorderTeamSpeakChannel',
{
channelId: channel.id,
parentId: Number(parentId),
orderAfterId: Number(orderAfterId),
},
t('Channel reordered')
);
}}
>
{t('Reorder')}
</button>
{!channel.default && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Delete channel'),
message: tf('Delete {0} and its contents?', channel.name),
confirmLabel: t('Delete'),
danger: true,
})
)
await mutate(
'DeleteTeamSpeakChannel',
{ channelId: channel.id, force: true },
t('Channel deleted')
);
}}
>
{t('Delete')}
</button>
)}
</div>
{channel.clients.map((client) => (
<ClientRow key={client.id} client={client} />
))}
{channel.channels.map((child) => (
<Channel key={child.id} channel={child} depth={depth + 1} />
))}
</div>
);
}
return (
<div className="admin-stack">
<div className="card">
<div className="card-head">
<div>
<h2>{directory?.server.name || t('TeamSpeak')}</h2>
<div className="muted">
{directory?.server.connected ? t('Connected') : t('Disconnected')}
{' · '}
{directory?.server.clientCount || 0}/{directory?.server.maxClients || '∞'}
</div>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={sendServerMessage}>
{t('Server message')}
</button>
<button className="btn btn-ghost" onClick={() => createChannel()}>
{t('Create channel')}
</button>
<button className="btn btn-ghost" disabled={loading} onClick={refresh}>
{loading ? t('Loading…') : t('Refresh')}
</button>
</div>
</div>
<div className="ts-admin-tree">
{directory?.channels.length ? (
directory.channels.map((channel) => (
<Channel key={channel.id} channel={channel} />
))
) : (
<EmptyRow text={t('No TeamSpeak topology available')} />
)}
</div>
</div>
<div className="card">
<div className="card-head">
<h2>{t('Bans')}</h2>
<span className="muted">{bans.length}</span>
</div>
<div className="tracklist">
{bans.length ? (
bans.map((ban) => (
<div className="ts-ban-row" key={ban.id}>
<div>
<strong>{ban.nickname || ban.uid || `#${ban.id}`}</strong>
<div className="muted">{ban.reason || t('No reason')}</div>
</div>
<span className="muted">
{ban.durationSeconds ? `${ban.durationSeconds}s` : t('Permanent')}
</span>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
await confirmDialog({
title: t('Remove ban'),
message: t('Remove this TeamSpeak ban?'),
confirmLabel: t('Unban'),
danger: true,
})
)
await mutate(
'UnbanTeamSpeakClient',
{ banId: ban.id },
t('Ban removed')
);
}}
>
{t('Unban')}
</button>
</div>
))
) : (
<EmptyRow text={t('No bans')} />
)}
</div>
</div>
</div>
);
}
@@ -1,145 +0,0 @@
import { useState } from 'react';
import { rpc } from '../lib/rpc';
import { send, watchStore } from '../lib/watch';
import { toast } from '../lib/app';
import { useStore } from '../lib/store';
import { thumbFor } from '../lib/format';
import type { Track } from '../lib/types';
import { t, tf } from '../i18n';
// Normalize a Twitch channel entry: accept a bare login name, an @handle, or a
// full twitch.tv URL, and reduce it to the channel login the embed player
// expects. Numeric ids pass through (best effort — resolving them to a login
// would need the Helix API, which isn't wired up).
function normalizeTwitchChannel(input: string): string {
let s = input.trim();
const m = s.match(/twitch\.tv\/([^/?#]+)/i);
if (m) s = m[1];
s = s.replace(/^@/, '');
return s.toLowerCase().replace(/[^a-z0-9_]/g, '');
}
// Add tracks to a watch room from inside it. YouTube uses the unauthenticated
// SearchTracks RPC (results added by title + thumbnail); Twitch has no search
// backend, so it offers an add-by-channel-name/id field instead.
export function WatchSearch({ disabled }: { disabled: boolean }) {
const w = useStore(watchStore);
const [query, setQuery] = useState('');
const [channel, setChannel] = useState('');
const [results, setResults] = useState<Track[]>([]);
const [open, setOpen] = useState(false);
if (w.sourceChoice === 'twitch') {
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={(e) => {
e.preventDefault();
const ch = normalizeTwitchChannel(channel);
if (!ch) return;
send({
type: 'watch.queue.add',
source: 'twitch',
url: ch,
title: ch,
});
toast(tf('Added “{0}” to queue', ch));
setChannel('');
}}
>
<input
value={channel}
onChange={(e) => setChannel(e.target.value)}
placeholder={t(
'Twitch channel name or id to queue…'
)}
autoComplete="off"
disabled={disabled}
/>
<button
className="btn btn-accent"
type="submit"
disabled={disabled}
>
{t('Add channel')}
</button>
</form>
</div>
);
}
return (
<div className="watch-search">
<form
className="search-row"
onSubmit={async (e) => {
e.preventDefault();
const q = query.trim();
if (!q) return;
try {
const res = await rpc.call<{ tracks?: Track[] }>(
'SearchTracks',
{ query: q }
);
setResults((res && res.tracks) || []);
setOpen(true);
} catch (err) {
toast((err as { message?: string }).message || 'error');
}
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t('Search YouTube to queue…')}
autoComplete="off"
disabled={disabled}
/>
<button className="btn btn-accent" type="submit" disabled={disabled}>
{t('Search')}
</button>
</form>
{open && results.length > 0 && (
<div className="watch-search-results">
{results.slice(0, 8).map((tr, i) => (
<button
key={tr.url || tr.id || i}
className="watch-search-item"
onClick={() => {
send({
type: 'watch.queue.add',
source: 'youtube',
url: tr.url || tr.id,
title: tr.title || '',
});
toast(
tf(
'Added “{0}” to queue',
tr.title || ''
)
);
setOpen(false);
setQuery('');
}}
>
<div
className="track-cover"
style={
thumbFor(tr)
? {
background: `url("${thumbFor(tr)}") center/cover`,
}
: undefined
}
/>
<span className="watch-search-title">
{tr.title}
</span>
</button>
))}
</div>
)}
</div>
);
}
+101 -135
View File
@@ -4,15 +4,12 @@
export const ru: Record<string, string> = {
// Sidebar / navigation
'Now Playing': 'Сейчас играет',
'Dashboard': 'Панель',
'Queue': 'Очередь',
'Search': 'Поиск',
'Library': 'Библиотека',
'History & Stats': 'История и статистика',
'Watch Together': 'Совместный просмотр',
'Listening Rooms': 'Комнаты прослушивания',
'Independent music streams for different groups':
'Независимые музыкальные потоки для разных групп',
'Server & Admin': 'Сервер и админ',
'RPC / API': 'RPC / API',
'MUSIC BOT · TS3': 'МУЗЫКАЛЬНЫЙ БОТ · TS3',
@@ -26,15 +23,14 @@ export const ru: Record<string, string> = {
'connected': 'подключено',
'disconnected': 'отключено',
'error': 'ошибка',
'listening': 'слушают',
// View headers
'What Echoion is streaming to the channel': 'Что Echoion стримит в канал',
'Live playback and TeamSpeak server activity':
'Текущее воспроизведение и активность сервера TeamSpeak',
'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 из кода',
@@ -125,75 +121,31 @@ export const ru: Record<string, string> = {
'{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 и др.) для совместного просмотра',
// Shared playback and action labels
'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}',
'LIVE': 'ЭФИР',
'Send': 'Отправить',
'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
'Administration': 'Администрирование',
'Administrator authentication required': 'Требуется вход администратора',
'Sign in with an account in a configured TeamSpeak admin group.':
'Войдите под учётной записью, входящей в настроенную группу администраторов TeamSpeak.',
'TeamSpeak': 'TeamSpeak',
'Echoion service': 'Служба Echoion',
'Bot messaging and runtime operations':
'Сообщения бота и управление службой',
'Subscribers': 'Подписчики',
'Emojis': 'Эмодзи',
'Audit history': 'Журнал действий',
'Room emojis moved to VoidWatch and are managed from its administration page.':
'Эмодзи комнат перенесены в VoidWatch и управляются на его странице администрирования.',
'Open VoidWatch admin ↗': 'Открыть панель VoidWatch ↗',
'Announce…': 'Объявление…',
'Reload config': 'Перезагрузить конфиг',
'Restart web UI': 'Перезапустить веб-интерфейс',
'Stop and start the web server without touching the bot':
'Остановить и запустить веб-сервер, не трогая бота',
'Unsub all': 'Отписать всех',
'No subscribers': 'Нет подписчиков',
'Nobody online right now': 'Сейчас никого нет в сети',
@@ -201,7 +153,6 @@ export const ru: Record<string, string> = {
'Offline': 'Не в сети',
'Unsub': 'Отписать',
'Unsubscribe {0}?': 'Отписать {0}?',
'Unsubscribed {0}': '{0} отписан',
'Announcement to all subscribers:': 'Объявление всем подписчикам:',
'Announcement sent': 'Объявление отправлено',
'Configuration reloaded': 'Конфигурация перезагружена',
@@ -213,11 +164,92 @@ export const ru: Record<string, string> = {
'Удалить ВСЕ подписки? Это нельзя отменить.',
'All subscriptions removed': 'Все подписки удалены',
'Listening': 'Слушает',
'Audit log': 'Журнал аудита',
'Refresh': 'Обновить',
'No audit entries yet': 'Записей аудита пока нет',
'client #{0}': 'клиент №{0}',
// Public TeamSpeak directory
'TeamSpeak server': 'Сервер TeamSpeak',
'Complete channel directory': 'Полное дерево каналов',
'Connected': 'Подключено',
'Disconnected': 'Отключено',
'No channels available': 'Нет доступных каналов',
'Password protected': 'Защищён паролем',
'Talking': 'Говорит',
'Away': 'Отошёл',
'Muted': 'Микрофон выключен',
'Deafened': 'Звук выключен',
'clients': 'клиентов',
'channels': 'каналов',
'capacity': 'вместимость',
'online': 'в сети',
'default': 'по умолчанию',
'locked': 'закрыт',
'away': 'отошёл',
'muted': 'микрофон выкл.',
'deafened': 'звук выкл.',
// TeamSpeak administration
'No TeamSpeak topology available': 'Дерево TeamSpeak недоступно',
'Message': 'Сообщение',
'Message {0}': 'Сообщение для {0}',
'Private message:': 'Личное сообщение:',
'Channel message:': 'Сообщение в канал:',
'Message sent': 'Сообщение отправлено',
'Server message': 'Сообщение серверу',
'Message sent to every connected TeamSpeak client:':
'Сообщение всем подключённым клиентам TeamSpeak:',
'Server message sent': 'Сообщение серверу отправлено',
'Move': 'Переместить',
'Move {0}': 'Переместить {0}',
'Destination channel ID:': 'ID целевого канала:',
'Client moved': 'Клиент перемещён',
'Kick': 'Выгнать',
'Kick {0}': 'Выгнать {0}',
'Kick this client from the server?': 'Выгнать этого клиента с сервера?',
'Client kicked': 'Клиент выгнан',
'Ban': 'Заблокировать',
'Ban {0}': 'Заблокировать {0}',
'Duration in seconds (0 = permanent):':
'Срок в секундах (0 = бессрочно):',
'Apply this ban now?': 'Заблокировать этого клиента сейчас?',
'Client banned': 'Клиент заблокирован',
'Bans': 'Блокировки',
'No bans': 'Блокировок нет',
'No reason': 'Без причины',
'Permanent': 'Бессрочно',
'Remove ban': 'Снять блокировку',
'Remove this TeamSpeak ban?': 'Снять эту блокировку TeamSpeak?',
'Unban': 'Разблокировать',
'Ban removed': 'Блокировка снята',
'Groups': 'Группы',
'Current groups': 'Текущие группы',
'Server group ID:': 'ID серверной группы:',
'Add server group': 'Добавление в серверную группу',
'Add group': 'Добавить в группу',
'Group added': 'Клиент добавлен в группу',
'Remove server group': 'Удаление из серверной группы',
'Remove group': 'Удалить из группы',
'Group removed': 'Клиент удалён из группы',
'Create channel': 'Создать канал',
'Channel name:': 'Название канала:',
'Create': 'Создать',
'Channel created': 'Канал создан',
'Add child': 'Добавить подканал',
'Rename channel': 'Переименовать канал',
'Edit': 'Изменить',
'Channel updated': 'Канал обновлён',
'Reorder': 'Переместить',
'Reorder channel': 'Переместить канал',
'Parent channel ID (0 = root):': 'ID родительского канала (0 = корень):',
'Previous sibling channel ID (0 = first):':
'ID предыдущего канала на этом уровне (0 = первый):',
'Channel reordered': 'Канал перемещён',
'Delete channel': 'Удалить канал',
'Delete {0} and its contents?': 'Удалить {0} вместе с содержимым?',
'Channel deleted': 'Канал удалён',
'Continue': 'Продолжить',
// RPC view
'Connect programmatically': 'Программное подключение',
'Copy snippet': 'Скопировать пример',
@@ -262,22 +294,7 @@ export const ru: Record<string, string> = {
'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': 'Сохранить',
@@ -289,56 +306,5 @@ export const ru: Record<string, string> = {
'Playlist name': 'Название плейлиста',
'Save playlist': 'Сохранить плейлист',
// Independent TeamSpeak listening rooms
'MULTI-STREAM': 'МУЛЬТИПОТОК',
'NOW TUNED': 'СЕЙЧАС В КОМНАТЕ',
'Your channel, split into listening spaces':
'Разделите канал на пространства для прослушивания',
'Each room has its own queue and bot stream. Join one to hear and control it.':
'У каждой комнаты своя очередь и поток бота. Войдите, чтобы слушать и управлять.',
'Room name': 'Название комнаты',
'Create room': 'Создать комнату',
'Created room “{0}”': 'Комната «{0}» создана',
'Live rooms': 'Активные комнаты',
'No listening rooms yet': 'Комнат прослушивания пока нет',
'{0} listeners · {1} queued': '{0} слушателей · {1} в очереди',
'JOINED': 'ВЫ В КОМНАТЕ',
'PAUSED': 'ПАУЗА',
'IDLE': 'ТИШИНА',
'Choose a room': 'Выберите комнату',
'Your TeamSpeak audio follows the room you join.':
'Звук TeamSpeak переключается на комнату, в которую вы вошли.',
'Leave': 'Выйти',
'Delete room': 'Удалить комнату',
'Delete “{0}” for everyone?': 'Удалить «{0}» для всех?',
'Stop': 'Остановить',
'Skip': 'Пропустить',
'Move up': 'Переместить выше',
'Move down': 'Переместить ниже',
'Pause': 'Пауза',
'Resume': 'Продолжить',
'Paused': 'На паузе',
'Streaming now': 'Сейчас транслируется',
'Ready': 'Готово',
'{0} people are tuned in': 'Подключено: {0}',
'Paste a URL or search for a track…':
'Вставьте ссылку или найдите трек…',
'Add': 'Добавить',
'Added to room queue': 'Добавлено в очередь комнаты',
'Room queue': 'Очередь комнаты',
'This room queue is empty': 'Очередь этой комнаты пуста',
// Controllable embeds (Kodik / Playerjs)
'Embed synced': 'Встраиваемый плеер синхронизирован',
'Embed is view-only': 'Встраиваемый плеер — только просмотр',
'Settings': 'Настройки',
'Local': 'Локально',
'Quality': 'Качество',
'Speed': 'Скорость',
'Voiceover': 'Озвучка',
'Episode': 'Серия',
'Subtitles': 'Субтитры',
'Off': 'Выкл.',
'Choose': 'Выбрать',
'Only the host can change this': 'Изменять может только ведущий',
};
+155 -15
View File
@@ -5,10 +5,9 @@
import { rpc, type RpcMethodName } from './rpc';
import { Store } from './store';
import { t, tf, setLanguage, getLanguage } from '../i18n';
import { setWatchName } from './watch';
import { loadCustomEmojis } from './emoji';
import type {
Identity,
PublicDashboard,
QueueEntry,
ServerInfo,
Status,
@@ -17,13 +16,11 @@ import type {
} from './types';
export type ViewName =
| 'now'
| 'dashboard'
| 'queue'
| 'search'
| 'library'
| 'stats'
| 'rooms'
| 'watch'
| 'server'
| 'rpc';
@@ -42,6 +39,8 @@ export interface AppState {
durationMs: number;
onlineCount: number;
listeners: Subscriber[];
publicDashboard: PublicDashboard | null;
watchUrl: string;
toast: string | null;
// Server-wide switch for the Now Playing video preview (item 11), from
// /config.json; users can still disable it locally.
@@ -51,10 +50,14 @@ export interface AppState {
// Sidebar drawer on small screens (hamburger in the header); ignored by
// CSS on desktop widths where the sidebar is always visible.
sidebarOpen: boolean;
capabilities: {
plugins: boolean;
webExtensions: boolean;
};
}
export const appStore = new Store<AppState>({
view: 'now',
view: 'dashboard',
connection: 'disconnected',
identity: null,
status: null,
@@ -68,10 +71,16 @@ export const appStore = new Store<AppState>({
durationMs: 0,
onlineCount: 0,
listeners: [],
publicDashboard: null,
watchUrl: '',
toast: null,
nowPlayingVideoAllowed: true,
shortcutsOpen: false,
sidebarOpen: false,
capabilities: {
plugins: false,
webExtensions: false,
},
});
// ── toast ────────────────────────────────────────────────────────────────────
@@ -124,9 +133,7 @@ export async function changeLanguage(language: 'en' | 'ru') {
export function applyIdentity(auth: Identity | null) {
appStore.set({ identity: auth });
if (auth) {
setWatchName(auth.nickname || null);
void loadUserPrefs();
void loadCustomEmojis();
}
}
@@ -176,6 +183,7 @@ export async function connectWithToken(tokenInput: string) {
const auth = (await rpc.authenticate(token)) as Identity;
localStorage.setItem('echoion.token', token);
applyIdentity(auth);
await loadCapabilities();
toast(tf('Welcome, {0}!', auth.nickname || t('friend')));
}
refreshAll();
@@ -210,9 +218,6 @@ export function showView(view: ViewName) {
// Navigation closes the mobile drawer.
appStore.set({ view, sidebarOpen: false });
// Reflect the selection in the URL for back/forward + shareable links.
// The watch view owns its own #watch/<room> hash (see watch.ts), so a
// re-selection never clobbers an existing room deep link.
if (view === 'watch' && location.hash.startsWith('#watch')) return;
const target = `#${view}`;
if (location.hash !== target) location.hash = target;
}
@@ -275,6 +280,47 @@ export async function loadFavorites() {
// ── boot ─────────────────────────────────────────────────────────────────────
let booted = false;
let dashboardEtag = '';
export async function refreshPublicDashboard() {
try {
const response = await fetch('/api/public/dashboard', {
headers: dashboardEtag ? { 'If-None-Match': dashboardEtag } : {},
cache: 'no-cache',
});
if (response.status === 304) return;
if (!response.ok) return;
const dashboard = (await response.json()) as PublicDashboard;
dashboardEtag = response.headers.get('ETag') || '';
const state = appStore.get();
const publicTrack = dashboard.playback.track;
const sameTrack =
publicTrack && state.current && publicTrack.id === state.current.id;
const current = publicTrack
? {
...(sameTrack ? state.current! : {}),
...publicTrack,
duration:
publicTrack.durationMs ?? publicTrack.duration ?? 0,
}
: null;
appStore.set({
publicDashboard: dashboard,
current,
status: {
...(state.status || {}),
isPlaying: dashboard.playback.isPlaying,
isPaused: dashboard.playback.isPaused,
volume: dashboard.playback.volume,
},
positionMs: dashboard.playback.positionMs,
durationMs: current?.duration || 0,
onlineCount: dashboard.server.clientCount,
});
} catch {
/* The RPC login remains usable if the public snapshot is unavailable. */
}
}
export function boot() {
if (booted) return;
@@ -283,24 +329,29 @@ export function boot() {
// Apply the persisted language before anything renders text.
setLanguage(getLanguage(), false);
// Server config: the Now Playing video preview can be disabled globally.
// Server config: the video preview policy and external VoidWatch link.
fetch('/config.json')
.then((r) => r.json())
.then((cfg) => {
if (cfg && cfg.nowPlayingVideo === false) {
appStore.set({ nowPlayingVideoAllowed: false });
}
appStore.set({
nowPlayingVideoAllowed: cfg?.nowPlayingVideo !== false,
watchUrl:
typeof cfg?.watchUrl === 'string' ? cfg.watchUrl : '',
});
})
.catch(() => {
/* keep the default (allowed) */
});
rpc.onState = (s) => appStore.set({ connection: s });
void refreshPublicDashboard();
setInterval(() => void refreshPublicDashboard(), 5000);
// After an automatic reconnect, restore the authenticated session from
// the stored token (or autologin) and pull fresh state.
rpc.onReconnected = async () => {
await restoreSession();
await loadCapabilities();
refreshAll();
toast(t('Reconnected'));
};
@@ -335,6 +386,9 @@ export function boot() {
});
}
});
rpc.on('plugins.updated', () => {
if (appStore.get().capabilities.webExtensions) void loadWebExtensions();
});
// Local 1s ticker keeps the progress bar moving between server updates.
setInterval(() => {
@@ -361,6 +415,92 @@ export function boot() {
// Session restore is independent of the connection: even if auth fails
// we still refresh so guests see live state instead of a blank app.
await restoreSession();
await loadCapabilities();
refreshAll();
})();
}
async function loadCapabilities() {
const capabilities = await safeCall<AppState['capabilities']>(
'GetCapabilities'
);
if (capabilities) {
appStore.set({ capabilities });
if (capabilities.webExtensions) await loadWebExtensions();
}
}
interface PluginWebAsset {
id: string;
javascript: string;
css: string;
}
interface LoadedWebExtension {
signature: string;
cleanup?: () => void;
}
const loadedWebExtensions = new Map<string, LoadedWebExtension>();
function unloadWebExtension(id: string) {
const loaded = loadedWebExtensions.get(id);
if (!loaded) return;
try {
loaded.cleanup?.();
} catch (error) {
console.error(`Echoion plugin web asset ${id} cleanup failed`, error);
}
document
.querySelectorAll(`style[data-echoion-plugin="${CSS.escape(id)}"]`)
.forEach((style) => style.remove());
loadedWebExtensions.delete(id);
}
async function loadWebExtensions() {
const response = await safeCall<{ assets?: PluginWebAsset[] }>(
'GetPluginExtensions'
);
if (!response) return;
const assets = response.assets || [];
const currentIds = new Set(assets.map((asset) => asset.id).filter(Boolean));
for (const id of loadedWebExtensions.keys()) {
if (!currentIds.has(id)) unloadWebExtension(id);
}
for (const asset of assets) {
if (!asset.id) continue;
const signature = `${asset.javascript}\0${asset.css}`;
if (loadedWebExtensions.get(asset.id)?.signature === signature) continue;
unloadWebExtension(asset.id);
let style: HTMLStyleElement | undefined;
if (asset.css) {
style = document.createElement('style');
style.dataset.echoionPlugin = asset.id;
style.textContent = asset.css;
document.head.appendChild(style);
}
try {
const host = {
call: async (plugin: string, method: string, params: unknown = {}) =>
rpc.call('PluginCall', {
plugin,
method,
params: JSON.stringify(params),
}),
store: appStore,
toast,
};
const cleanup = new Function(
'Echoion',
`'use strict';\n${asset.javascript}`
)(host);
loadedWebExtensions.set(asset.id, {
signature,
cleanup: typeof cleanup === 'function' ? cleanup : undefined,
});
} catch (error) {
style?.remove();
console.error(`Echoion plugin web asset ${asset.id} failed`, error);
}
}
}
@@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest';
import { auditMethodName } from './auditMethods';
describe('audit RPC method mapping', () => {
it('keeps listening-room methods append-only and aligned with RpcTypes.hpp', () => {
expect(auditMethodName(53)).toBe('ListListeningRooms');
expect(auditMethodName(62)).toBe('GetListeningRoomQueue');
expect(auditMethodName(63)).toBe('SkipListeningRoom');
expect(auditMethodName(66)).toBe('ClearListeningRoomQueue');
it('keeps removed room audit slots and newer methods aligned', () => {
expect(auditMethodName(53)).toBe('Reserved53');
expect(auditMethodName(66)).toBe('Reserved66');
expect(auditMethodName(67)).toBe('GetCapabilities');
expect(auditMethodName(72)).toBe('Reserved72');
expect(auditMethodName(73)).toBe('GetTeamSpeakDirectory');
expect(auditMethodName(88)).toBe('SendTeamSpeakServerMessage');
});
});
+39 -17
View File
@@ -54,24 +54,46 @@ const RPC_METHOD_BY_INDEX: readonly string[] = [
'ToggleAutoplay',
'GetUserPrefs',
'SetUserPrefs',
'GetCustomEmojis',
'AddCustomEmoji', // 50
'RemoveCustomEmoji',
'Reserved49',
'Reserved50',
'Reserved51',
'GetLyrics',
'ListListeningRooms',
'CreateListeningRoom',
'DeleteListeningRoom',
'JoinListeningRoom',
'LeaveListeningRoom',
'PlayInListeningRoom',
'PauseListeningRoom',
'ResumeListeningRoom',
'StopListeningRoom',
'GetListeningRoomQueue',
'SkipListeningRoom',
'RemoveFromListeningRoomQueue',
'MoveInListeningRoomQueue',
'ClearListeningRoomQueue',
'Reserved53',
'Reserved54',
'Reserved55',
'Reserved56',
'Reserved57',
'Reserved58',
'Reserved59',
'Reserved60',
'Reserved61',
'Reserved62',
'Reserved63',
'Reserved64',
'Reserved65',
'Reserved66',
'GetCapabilities',
'GetPluginExtensions',
'PluginCall',
'Reserved70',
'Reserved71',
'Reserved72',
'GetTeamSpeakDirectory',
'MoveTeamSpeakClient',
'KickTeamSpeakClient',
'BanTeamSpeakClient',
'GetTeamSpeakBans',
'UnbanTeamSpeakClient',
'CreateTeamSpeakChannel',
'EditTeamSpeakChannel',
'ReorderTeamSpeakChannel',
'DeleteTeamSpeakChannel',
'GetTeamSpeakServerGroups',
'AddTeamSpeakServerGroupMember',
'RemoveTeamSpeakServerGroupMember',
'SendTeamSpeakPrivateMessage',
'SendTeamSpeakChannelMessage',
'SendTeamSpeakServerMessage',
];
export function auditMethodName(method: number): string {
@@ -1,254 +0,0 @@
import { describe, expect, it } from 'vitest';
import { EMBED_PROTOCOLS, prepareEmbedUrl } from './embedProtocols';
const byName = (name: string) => EMBED_PROTOCOLS.find((p) => p.name === name)!;
const kodik = byName('kodik');
const playerjs = byName('playerjs');
const alloha = byName('alloha');
const vimeo = byName('vimeo');
const playerjsSpec = byName('player.js');
const rutube = byName('rutube');
const dailymotion = byName('dailymotion');
const vk = byName('vk');
describe('kodik parse', () => {
it('parses JSON-string time updates', () => {
expect(
kodik.parse(
JSON.stringify({ key: 'kodik_player_time_update', value: 42.5 })
)
).toEqual({ kind: 'time', seconds: 42.5 });
});
it('parses duration and play/pause/ended state', () => {
expect(
kodik.parse({ key: 'kodik_player_duration_update', value: 1440 })
).toEqual({ kind: 'duration', seconds: 1440 });
expect(kodik.parse({ key: 'kodik_player_play' })).toEqual({ kind: 'play' });
expect(kodik.parse({ key: 'kodik_player_pause' })).toEqual({
kind: 'pause',
});
expect(kodik.parse({ key: 'kodik_player_video_ended' })).toEqual({
kind: 'ended',
});
});
it('rejects everything else', () => {
expect(kodik.parse('garbage')).toBeNull();
expect(kodik.parse('{"broken json')).toBeNull();
expect(kodik.parse({ event: 'time', answer: 3 })).toBeNull();
expect(kodik.parse(null)).toBeNull();
expect(kodik.parse(42)).toBeNull();
});
it('is hostname-pinned and seeks by reloading with start_from', () => {
expect(kodik.matchUrl!('https://kodikplayer.com/seria/1/hash/720p')).toBe(
true
);
expect(kodik.matchUrl!('https://kodik.info/video/1/hash/720p')).toBe(true);
expect(kodik.matchUrl!('https://youtube.com/x')).toBe(false);
// start_from is set (overwritten) while signed params are preserved.
const seeked = kodik.reloadSeek!(
'https://kodikplayer.com/seria/1/hash/720p?d_sign=abc&start_from=5',
42.9
);
expect(seeked).toContain('start_from=42');
expect(seeked).toContain('d_sign=abc');
expect(seeked).not.toContain('start_from=5');
});
});
describe('playerjs.com parse', () => {
it('parses object and JSON-string events', () => {
expect(playerjs.parse({ event: 'time', answer: 12 })).toEqual({
kind: 'time',
seconds: 12,
});
expect(
playerjs.parse(JSON.stringify({ event: 'duration', answer: 600 }))
).toEqual({ kind: 'duration', seconds: 600 });
expect(playerjs.parse({ event: 'end' })).toEqual({ kind: 'ended' });
});
it('does not lock on player.js-spec or unknown shapes', () => {
expect(playerjs.parse({ context: 'player.js', event: 'play' })).toBeNull();
expect(playerjs.parse({ event: 'infoDelivery' })).toBeNull();
expect(playerjs.parse({ key: 'kodik_player_play' })).toBeNull();
});
it('normalizes quality, voiceover and subtitle capabilities', () => {
expect(
playerjs.parse({
event: 'qualities',
answer: [{ id: '720', name: '720p' }, '1080p'],
})
).toMatchObject({
kind: 'extraList',
control: { id: 'quality', scope: 'local' },
});
expect(
playerjs.parse({
event: 'audiotracks',
answer: { ru: 'Russian', en: 'English' },
})
).toMatchObject({
kind: 'extraList',
control: { id: 'audiotrack', scope: 'synced' },
});
expect(playerjs.parse({ event: 'subtitle', answer: 1 })).toEqual({
kind: 'extraCurrent',
id: 'subtitle',
value: '1',
});
});
});
describe('alloha detection', () => {
it('pins known Alloha player hosts', () => {
expect(alloha.matchUrl!('https://alloha.tv/embed/123')).toBe(true);
expect(alloha.matchUrl!('https://cdn.allarknow.online/player')).toBe(true);
expect(alloha.matchUrl!('https://example.com/player')).toBe(false);
});
});
describe('vimeo parse', () => {
it('parses timeupdate with bundled duration and the getDuration reply', () => {
expect(
vimeo.parse({ event: 'timeupdate', data: { seconds: 10, duration: 200 } })
).toEqual({ kind: 'time', seconds: 10, duration: 200 });
expect(vimeo.parse({ method: 'getDuration', value: 200 })).toEqual({
kind: 'duration',
seconds: 200,
});
expect(vimeo.parse({ event: 'play' })).toEqual({ kind: 'play' });
});
it('does not lock on a playerjs.com message (has `answer`) or garbage', () => {
expect(vimeo.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vimeo.parse('garbage')).toBeNull();
expect(vimeo.parse({ event: 'infoDelivery' })).toBeNull();
});
it('matchUrl selects vimeo hosts only', () => {
expect(vimeo.matchUrl!('https://player.vimeo.com/video/123')).toBe(true);
expect(vimeo.matchUrl!('https://vimeo.com/123')).toBe(true);
expect(vimeo.matchUrl!('https://youtube.com/watch?v=x')).toBe(false);
});
it('prepareUrl hides native chrome', () => {
const p = vimeo.prepareUrl!('https://player.vimeo.com/video/123');
expect(p).toContain('controls=0');
expect(p).toContain('title=0');
});
});
describe('player.js (embedly spec) parse', () => {
it('parses context-tagged events', () => {
expect(
playerjsSpec.parse({
context: 'player.js',
event: 'timeupdate',
value: { seconds: 5, duration: 100 },
})
).toEqual({ kind: 'time', seconds: 5, duration: 100 });
expect(
playerjsSpec.parse({ context: 'player.js', event: 'pause' })
).toEqual({ kind: 'pause' });
expect(playerjsSpec.parse({ context: 'player.js', event: 'ready' })).toEqual(
{ kind: 'hello' }
);
});
it('rejects messages without the player.js context', () => {
expect(playerjsSpec.parse({ event: 'play' })).toBeNull();
expect(playerjsSpec.parse('garbage')).toBeNull();
});
});
describe('rutube parse + matchUrl', () => {
it('parses player:* events', () => {
expect(
rutube.parse(
JSON.stringify({ type: 'player:currentTime', data: { time: 30 } })
)
).toEqual({ kind: 'time', seconds: 30 });
expect(
rutube.parse({ type: 'player:changeState', data: { state: 'playing' } })
).toEqual({ kind: 'play' });
expect(
rutube.parse({ type: 'player:durationChange', data: { duration: 90 } })
).toEqual({ kind: 'duration', seconds: 90 });
});
it('ignores foreign messages', () => {
expect(rutube.parse({ event: 'play', answer: 1 })).toBeNull();
expect(rutube.parse({ key: 'kodik_player_play' })).toBeNull();
expect(rutube.matchUrl!('https://rutube.ru/play/embed/123')).toBe(true);
expect(rutube.matchUrl!('https://vimeo.com/1')).toBe(false);
});
});
describe('dailymotion parse + prepareUrl', () => {
it('parses classic querystring events', () => {
expect(dailymotion.parse('event=timeupdate&time=12&duration=240')).toEqual(
{ kind: 'time', seconds: 12, duration: 240 }
);
expect(dailymotion.parse('event=pause')).toEqual({ kind: 'pause' });
expect(dailymotion.parse('event=video_end')).toEqual({ kind: 'ended' });
expect(dailymotion.parse({ event: 'play' })).toBeNull();
});
it('matchUrl + prepareUrl inject api=postMessage and preserve params', () => {
expect(dailymotion.matchUrl!('https://www.dailymotion.com/embed/video/x'))
.toBe(true);
expect(dailymotion.matchUrl!('https://dai.ly/x')).toBe(true);
const prepared = dailymotion.prepareUrl!(
'https://www.dailymotion.com/embed/video/x?foo=1'
);
expect(prepared).toContain('api=postMessage');
expect(prepared).toContain('controls=0');
expect(prepared).toContain('foo=1');
// idempotent
expect(dailymotion.prepareUrl!(prepared)).toBe(prepared);
});
});
describe('vk parse + prepareUrl', () => {
it('parses player_api events', () => {
expect(
vk.parse({ type: 'player_api', event: 'timeupdate', time: 8, duration: 60 })
).toEqual({ kind: 'time', seconds: 8, duration: 60 });
expect(vk.parse({ type: 'player_api', event: 'started' })).toEqual({
kind: 'play',
});
expect(vk.parse({ type: 'player_api', event: 'paused' })).toEqual({
kind: 'pause',
});
});
it('ignores foreign messages and injects js_api=1', () => {
expect(vk.parse({ event: 'play', answer: 1 })).toBeNull();
expect(vk.matchUrl!('https://vk.com/video_ext.php?oid=1')).toBe(true);
expect(vk.matchUrl!('https://vkvideo.ru/video_ext.php?oid=1')).toBe(true);
expect(vk.prepareUrl!('https://vk.com/video_ext.php?oid=1')).toContain(
'js_api=1'
);
});
});
describe('registry order + prepareEmbedUrl', () => {
it('generic (content-detected) set is player.js then playerjs', () => {
expect(
EMBED_PROTOCOLS.filter((p) => !p.matchUrl).map((p) => p.name)
).toEqual(['player.js', 'playerjs']);
});
it('prepareEmbedUrl applies hostname-matched params, leaves others alone', () => {
expect(
prepareEmbedUrl('https://www.dailymotion.com/embed/video/x')
).toContain('api=postMessage');
expect(prepareEmbedUrl('https://kodik.info/seria/1/hash/720p')).toBe(
'https://kodik.info/seria/1/hash/720p'
);
});
});
@@ -1,972 +0,0 @@
// Adapters for postMessage-controllable embed players in the Watch view.
//
// A generic iframe can only be driven if the player inside exposes a
// postMessage API — everything else stays view-only by browser design.
// Protocols supported (each is one self-contained entry in EMBED_PROTOCOLS):
// - kodik: JSON *strings* like {key:'kodik_player_time_update', value:sec};
// commands {key:'kodik_player_api', value:{method}}.
// - vimeo: {method:'play'|...} strings; events {event:'timeupdate',
// data:{seconds,duration}}. Hostname-selected (player.vimeo.com).
// - rutube / dailymotion / vk: hostname-selected; some need opt-in URL
// params (prepareUrl) and their command/event shapes are community-
// documented — flagged VERIFY, one-line fixes if a live embed differs.
// - player.js (embedly spec): {context:'player.js', ...} — Wistia & co.
// - playerjs (playerjs.com, many CIS hosters): {api:'play'|...} commands,
// {event, answer} events.
// Shapes marked VERIFY are community-documented, not official; dev builds
// console.debug every unrecognized frame message to reverse-engineer them.
//
// Detection: for a hostname-matched player only that protocol is probed;
// otherwise the generic set is probed until one `parse` recognizes a message
// and locks the adapter. On timeout the embed is uncontrollable and the
// caller keeps today's host-driven view-only behavior.
export interface EmbedAdapter {
protocol: string;
// True for players (Kodik) driven by reloading the iframe rather than
// postMessage commands: the caller should avoid drift-reconcile churn and
// not expect pause to work.
reloadBased: boolean;
play(): void;
pause(): void;
seekMs(ms: number): void;
setVolume(v01: number): void; // 0..1
positionMs(): number;
durationMs(): number;
paused(): boolean;
extras(): PlayerExtraControl[];
setExtra(id: string, value: string): void;
destroy(): void;
}
export interface ExtraControlOption {
value: string;
label: string;
}
export interface PlayerExtraControl {
id: string;
label: string;
kind: 'select' | 'button';
options: ExtraControlOption[];
current: string | null;
scope: 'local' | 'synced';
}
// Fired only for events NOT caused by our own commands (see suppression
// below) — i.e. gestures made inside the embed UI, which the host must relay
// to the room.
export interface EmbedCallbacks {
onPlay(positionMs: number): void;
onPause(positionMs: number): void;
onSeek(positionMs: number): void;
onDurationChange(durationMs: number): void;
onEnded(): void;
onExtraControls(controls: PlayerExtraControl[]): void;
}
export type EmbedEvent =
// `duration` piggybacks on time events for players (Vimeo, player.js, DM,
// VK) that bundle it into their timeupdate payload.
| { kind: 'time'; seconds: number; duration?: number }
| { kind: 'duration'; seconds: number }
| { kind: 'play' }
| { kind: 'pause' }
| { kind: 'ended' }
| { kind: 'extraList'; control: PlayerExtraControl }
| { kind: 'extraCurrent'; id: string; value: string }
// Recognized the protocol but the event carries no state we track; enough
// to lock detection.
| { kind: 'hello' };
export interface ProtocolDef {
name: string;
// Hostname-based selection: when a URL matches, only this protocol is
// probed (skips content-based detection). Left undefined for generic
// protocols detected purely by the messages they emit (kodik, player.js).
matchUrl?(url: string): boolean;
// Inject opt-in query params the player needs before the iframe loads
// (e.g. Dailymotion `?api=postMessage`, VK `?js_api=1`).
prepareUrl?(url: string): string;
// Some players (Kodik) expose no postMessage command API — the only way to
// seek is to reload the iframe at a start offset. When present, the adapter
// seeks by setting frame.src to this URL instead of posting a command.
reloadSeek?(currentSrc: string, seconds: number): string;
probe(win: Window): void;
parse(data: unknown): EmbedEvent | null;
play(win: Window): void;
pause(win: Window): void;
seek(win: Window, seconds: number): void;
volume(win: Window, v01: number): void;
probeExtras?(win: Window): void;
setExtra?(win: Window, id: string, value: string): void;
staticExtras?(url: string): PlayerExtraControl[];
}
// Embeds are served from many mirror domains (esp. Kodik), so the target
// origin can't be pinned; we never trust incoming data beyond parsing known
// shapes into numbers.
function post(win: Window, msg: unknown) {
try {
win.postMessage(msg, '*');
} catch {
/* frame navigating/gone */
}
}
const asNumber = (v: unknown): number =>
typeof v === 'number' ? v : Number(v);
// Embed URLs are absolute, so no base is needed; guard `location` so the
// helpers also work under the node test runner.
const baseHref = (): string | undefined =>
typeof location !== 'undefined' ? location.href : undefined;
function hostOf(url: string): string {
try {
return new URL(url, baseHref()).hostname.toLowerCase();
} catch {
return '';
}
}
function isHostOrSubdomain(host: string, domain: string): boolean {
return host === domain || host.endsWith(`.${domain}`);
}
function withParams(url: string, params: Record<string, string>): string {
try {
const u = new URL(url, baseHref());
for (const [k, v] of Object.entries(params)) {
if (!u.searchParams.has(k)) u.searchParams.set(k, v);
}
return u.toString();
} catch {
return url;
}
}
// Overwrite a single query param (preserves the rest, incl. Kodik's signed
// d_sign/ref_sign params).
function setParam(url: string, key: string, value: string): string {
try {
const u = new URL(url, baseHref());
u.searchParams.set(key, value);
return u.toString();
} catch {
return url;
}
}
// Normalize an object-or-JSON-string payload into a plain object, or null.
function asObj(data: unknown): Record<string, unknown> | null {
let obj: unknown = data;
if (typeof data === 'string') {
const s = data.trim();
if (!s.startsWith('{') && !s.startsWith('[')) return null;
try {
obj = JSON.parse(s);
} catch {
return null;
}
}
return obj && typeof obj === 'object'
? (obj as Record<string, unknown>)
: null;
}
function toOptions(value: unknown): ExtraControlOption[] {
const entries = Array.isArray(value)
? value.map((item, index) => [String(index), item] as const)
: value && typeof value === 'object'
? Object.entries(value as Record<string, unknown>)
: [];
return entries.flatMap(([fallback, item]) => {
if (item && typeof item === 'object') {
const option = item as Record<string, unknown>;
const raw = option.value ?? option.id ?? option.index ?? fallback;
const label = option.label ?? option.name ?? option.title ?? raw;
return [{ value: String(raw), label: String(label) }];
}
return item == null
? []
: [{ value: fallback, label: String(item) }];
});
}
function extraControl(
id: string,
label: string,
scope: PlayerExtraControl['scope'],
options: ExtraControlOption[],
current: string | null = null
): PlayerExtraControl {
return { id, label, scope, options, current, kind: 'select' };
}
const kodik: ProtocolDef = {
name: 'kodik',
// Kodik (kodikplayer.com and its mirrors). Hostname-pinned so it always
// locks as `kodik` and never falls back to view-only.
matchUrl: (url) => {
const host = hostOf(url);
return ['kodik.info', 'kodik.cc', 'kodik.biz', 'kodik.online', 'kodikplayer.com']
.some((domain) => isHostOrSubdomain(host, domain));
},
// Kodik has NO postMessage command API — the only way to seek is to reload
// the iframe at a start offset (preserving its signed params). start_from
// auto-resumes playback from that second.
reloadSeek: (src, seconds) =>
setParam(src, 'start_from', String(Math.max(0, Math.floor(seconds)))),
probe(win) {
// Community-documented; harmless if ignored by the player.
post(win, { key: 'kodik_player_api', value: { method: 'get_duration' } });
post(win, { key: 'kodik_player_api', value: { method: 'get_time' } });
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.includes('kodik_player')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as { key?: unknown; value?: unknown } | null;
if (!m || typeof m.key !== 'string' || !m.key.startsWith('kodik_player')) {
return null;
}
const n = asNumber(m.value);
switch (m.key) {
case 'kodik_player_time_update':
case 'kodik_player_current_time':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'kodik_player_duration_update':
case 'kodik_player_duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'kodik_player_play':
return { kind: 'play' };
case 'kodik_player_pause':
return { kind: 'pause' };
case 'kodik_player_video_ended':
return { kind: 'ended' };
default:
// Unmapped kodik_player_* event — still unambiguously Kodik.
return { kind: 'hello' };
}
},
play: (win) => post(win, { key: 'kodik_player_api', value: { method: 'play' } }),
pause: (win) => post(win, { key: 'kodik_player_api', value: { method: 'pause' } }),
seek: (win, seconds) =>
post(win, { key: 'kodik_player_api', value: { method: 'seek', seconds } }),
volume: (win, v01) =>
post(win, {
key: 'kodik_player_api',
value: { method: 'change_volume', volume: v01 },
}),
};
const playerjs: ProtocolDef = {
name: 'playerjs',
probe(win) {
post(win, { api: 'duration' });
post(win, { api: 'time' });
},
probeExtras(win) {
for (const api of ['qualities', 'audiotracks', 'subtitles']) {
post(win, { api });
}
},
staticExtras() {
return [
extraControl(
'speed',
'Speed',
'synced',
[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map((speed) => ({
value: String(speed),
label: `${speed}×`,
})),
'1'
),
];
},
parse(data) {
let obj: unknown = data;
if (typeof data === 'string') {
if (!data.startsWith('{')) return null;
try {
obj = JSON.parse(data);
} catch {
return null;
}
}
const m = obj as
| { event?: unknown; answer?: unknown; context?: unknown }
| null;
if (!m || typeof m.event !== 'string') return null;
// A {context:'player.js'} message belongs to the embedly spec adapter,
// not this one.
if (m.context === 'player.js') return null;
const n = asNumber(m.answer);
// Only lock on events Playerjs actually emits — a bare {event:...}
// could belong to some other player's protocol.
switch (m.event) {
case 'qualities':
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.answer)
),
};
case 'audiotracks':
return {
kind: 'extraList',
control: extraControl(
'audiotrack',
'Voiceover',
'synced',
toOptions(m.answer)
),
};
case 'subtitles':
return {
kind: 'extraList',
control: extraControl(
'subtitle',
'Subtitles',
'local',
[
{ value: '-1', label: 'Off' },
...toOptions(m.answer),
]
),
};
case 'episodes':
return {
kind: 'extraList',
control: extraControl(
'episode',
'Episode',
'synced',
toOptions(m.answer)
),
};
case 'quality':
case 'audiotrack':
case 'subtitle':
case 'speed':
case 'episode':
return {
kind: 'extraCurrent',
id: m.event,
value: String(m.answer ?? ''),
};
case 'time':
case 'updatetime':
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
case 'duration':
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'end':
case 'ended':
return { kind: 'ended' };
case 'init':
case 'inited':
case 'ready':
case 'volume':
return { kind: 'hello' };
default:
return null;
}
},
play: (win) => post(win, { api: 'play' }),
pause: (win) => post(win, { api: 'pause' }),
seek: (win, seconds) => post(win, { api: 'seek', set: seconds }),
volume: (win, v01) => post(win, { api: 'volume', set: v01 }),
setExtra: (win, id, value) => {
if (!['quality', 'audiotrack', 'subtitle', 'speed', 'episode', 'next', 'prev'].includes(id)) {
return;
}
post(win, { api: id, set: value });
},
};
const alloha: ProtocolDef = {
...playerjs,
name: 'alloha',
matchUrl: (url) =>
['alloha.tv', 'alloha.video', 'alloha.online', 'allarknow.online'].some(
(domain) => isHostOrSubdomain(hostOf(url), domain)
),
};
// Vimeo (vimeo/player.js): well documented. Selected by hostname; disambiguated
// from playerjs.com by carrying `data`, not `answer`.
const vimeo: ProtocolDef = {
name: 'vimeo',
matchUrl: (url) => /(^|\.)vimeo\.com$/.test(hostOf(url)),
// Our overlay bar is the only control surface, so hide Vimeo's native chrome.
prepareUrl: (url) =>
withParams(url, {
controls: '0',
title: '0',
byline: '0',
portrait: '0',
}),
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, JSON.stringify({ method: 'addEventListener', value: ev }));
}
post(win, JSON.stringify({ method: 'getDuration' }));
},
probeExtras(win) {
post(win, JSON.stringify({ method: 'getQualities' }));
},
parse(data) {
const m = asObj(data);
if (!m) return null;
if (m.method === 'getDuration') {
const n = asNumber(m.value);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
if (m.method === 'getQualities') {
return {
kind: 'extraList',
control: extraControl(
'quality',
'Quality',
'local',
toOptions(m.value)
),
};
}
if (typeof m.event !== 'string') return null;
if ('answer' in m) return null; // that's a playerjs.com message
const d = (m.data ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(d.seconds);
const dur = asNumber(d.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
case 'finish':
return { kind: 'ended' };
case 'ready':
case 'loaded':
return { kind: 'hello' };
default:
return null; // bare {event} without vimeo markers → not ours
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) =>
post(w, JSON.stringify({ method: 'setCurrentTime', value: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', value: v })),
setExtra: (w, id, value) => {
if (id === 'quality') {
post(w, JSON.stringify({ method: 'setQuality', value }));
}
},
};
// embedly player.js SPEC (github.com/embedly/player.js): the `context` field
// makes every message unambiguous. Generic (no matchUrl) — covers Wistia etc.
const PJS = { context: 'player.js', version: '0.0.11' } as const;
const playerjsSpec: ProtocolDef = {
name: 'player.js',
probe(win) {
for (const ev of ['timeupdate', 'play', 'pause', 'ended']) {
post(win, {
...PJS,
method: 'addEventListener',
listener: `ec_${ev}`,
value: ev,
});
}
},
parse(data) {
const m = asObj(data);
if (!m || m.context !== 'player.js' || typeof m.event !== 'string') {
return null;
}
const v = (m.value ?? {}) as { seconds?: unknown; duration?: unknown };
switch (m.event) {
case 'timeupdate': {
const sec = asNumber(v.seconds);
const dur = asNumber(v.duration);
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
}
case 'play':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // any context:'player.js' event is ours
}
},
play: (w) => post(w, { ...PJS, method: 'play' }),
pause: (w) => post(w, { ...PJS, method: 'pause' }),
seek: (w, s) => post(w, { ...PJS, method: 'setCurrentTime', value: s }),
volume: (w, v) => post(w, { ...PJS, method: 'setVolume', value: v }),
};
// Rutube (RutubePlayerJSAPI). VERIFY command/subscribe shapes on a live embed.
const rutube: ProtocolDef = {
name: 'rutube',
matchUrl: (url) => /(^|\.)rutube\.ru$/.test(hostOf(url)),
probe(win) {
// Rutube emits events only after an explicit subscribe. VERIFY payload.
post(win, JSON.stringify({ type: 'player:subscribe', data: {} }));
},
parse(data) {
const m = asObj(data);
if (!m || typeof m.type !== 'string' || !m.type.startsWith('player:')) {
return null;
}
const d = (m.data ?? {}) as {
time?: unknown;
duration?: unknown;
state?: unknown;
};
switch (m.type) {
case 'player:currentTime': {
const n = asNumber(d.time);
return isFinite(n) ? { kind: 'time', seconds: n } : { kind: 'hello' };
}
case 'player:durationChange': {
const n = asNumber(d.duration);
return isFinite(n) && n > 0
? { kind: 'duration', seconds: n }
: { kind: 'hello' };
}
case 'player:changeState': {
const st = String(d.state);
if (st === 'playing') return { kind: 'play' };
if (st === 'paused' || st === 'stopped') return { kind: 'pause' };
if (st === 'ended') return { kind: 'ended' };
return { kind: 'hello' };
}
default:
return { kind: 'hello' }; // player:* is unambiguously Rutube
}
},
play: (w) => post(w, JSON.stringify({ type: 'player:play', data: {} })),
pause: (w) => post(w, JSON.stringify({ type: 'player:pause', data: {} })),
seek: (w, s) =>
post(w, JSON.stringify({ type: 'player:setCurrentTime', data: { time: s } })),
volume: (w, v) =>
post(w, JSON.stringify({ type: 'player:setVolume', data: { volume: v } })),
};
// Dailymotion classic embed (?api=postMessage → querystring events). VERIFY;
// the newer geo.dailymotion.com SDK uses JSON — add a branch here if needed.
const dailymotion: ProtocolDef = {
name: 'dailymotion',
matchUrl: (url) => /(^|\.)(dailymotion\.com|dai\.ly)$/.test(hostOf(url)),
// api=postMessage enables control; controls=0 + ui-* hide the native chrome
// (our overlay bar drives playback instead).
prepareUrl: (url) =>
withParams(url, {
api: 'postMessage',
controls: '0',
'ui-start-screen-info': 'false',
'ui-logo': 'false',
}),
probe() {
/* classic embed auto-emits once api=postMessage is set */
},
parse(data) {
if (typeof data !== 'string' || !data.includes('event=')) return null;
const p = new URLSearchParams(data);
const ev = p.get('event');
if (!ev) return null;
const sec = Number(p.get('time'));
const dur = Number(p.get('duration'));
switch (ev) {
case 'timeupdate':
case 'progress':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'durationchange':
return isFinite(dur) && dur > 0
? { kind: 'duration', seconds: dur }
: { kind: 'hello' };
case 'play':
case 'playing':
return { kind: 'play' };
case 'pause':
return { kind: 'pause' };
case 'video_end':
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' };
}
},
play: (w) => post(w, JSON.stringify({ command: 'play', parameters: [] })),
pause: (w) => post(w, JSON.stringify({ command: 'pause', parameters: [] })),
seek: (w, s) => post(w, JSON.stringify({ command: 'seek', parameters: [s] })),
volume: (w, v) =>
post(w, JSON.stringify({ command: 'setVolume', parameters: [v] })),
};
// VK Video (?js_api=1 → {type:'player_api', event}). VERIFY command shapes.
const vk: ProtocolDef = {
name: 'vk',
matchUrl: (url) => /(^|\.)(vk\.com|vkvideo\.ru|vk\.ru)$/.test(hostOf(url)),
prepareUrl: (url) => withParams(url, { js_api: '1' }),
probe(win) {
post(win, JSON.stringify({ method: 'addEventListener', event: '*' }));
},
parse(data) {
const m = asObj(data);
if (!m || m.type !== 'player_api' || typeof m.event !== 'string') {
return null;
}
const sec = asNumber(m.time ?? m.position);
const dur = asNumber(m.duration);
switch (m.event) {
case 'timeupdate':
return isFinite(sec)
? {
kind: 'time',
seconds: sec,
duration: isFinite(dur) && dur > 0 ? dur : undefined,
}
: { kind: 'hello' };
case 'started':
case 'resumed':
return { kind: 'play' };
case 'paused':
return { kind: 'pause' };
case 'ended':
return { kind: 'ended' };
default:
return { kind: 'hello' }; // type:'player_api' is unambiguously VK
}
},
play: (w) => post(w, JSON.stringify({ method: 'play' })),
pause: (w) => post(w, JSON.stringify({ method: 'pause' })),
seek: (w, s) => post(w, JSON.stringify({ method: 'seek', time: s })),
volume: (w, v) => post(w, JSON.stringify({ method: 'setVolume', volume: v })),
};
// Hostname-selected protocols first (they're picked by URL, never by content);
// then the generic set probed by the messages they emit — kodik first (its
// keys are unambiguous), the embedly spec before the looser playerjs.com.
// Exported for the parse unit tests.
export const EMBED_PROTOCOLS: ProtocolDef[] = [
kodik,
alloha,
vimeo,
rutube,
dailymotion,
vk,
playerjsSpec,
playerjs,
];
// Inject any opt-in params a hostname-matched player needs, before iframe.src.
export function prepareEmbedUrl(url: string): string {
const p = EMBED_PROTOCOLS.find((x) => x.matchUrl?.(url));
// Signed players such as Kodik depend on their own origin for scripts,
// AJAX, cookies and anti-abuse checks. Keep them on the provider origin;
// Echoion controls them only through their postMessage surface.
return p?.prepareUrl ? p.prepareUrl(url) : url;
}
const PROBE_INTERVAL_MS = 750;
// Commands are echoed back as events by the player; ignore relay callbacks
// for this long after each command we send.
const SUPPRESS_MS = 800;
// A time event this far off the extrapolated position counts as a user seek.
const SEEK_JUMP_SEC = 2.5;
// Minimum gap between reload-based (Kodik) iframe reloads.
const RELOAD_DEBOUNCE_MS = 4000;
export function detectEmbedAdapter(
frame: HTMLIFrameElement,
cb: EmbedCallbacks,
timeoutMs = 5000
): Promise<EmbedAdapter | null> {
return new Promise((resolve) => {
let locked: ProtocolDef | null = null;
// A hostname-matched player is probed alone; otherwise probe the
// generic (content-detected) set. frame.src is the prepared URL.
const matched =
EMBED_PROTOCOLS.find((p) => p.matchUrl?.(frame.src)) ?? null;
const probeSet = matched
? [matched]
: EMBED_PROTOCOLS.filter((p) => !p.matchUrl);
// Normalized player state. Embeds push time updates rather than expose
// getters, so position is the last event extrapolated by wall clock.
let lastTimeSec = 0;
let lastTimeAt = performance.now();
let durationSec = 0;
let playing = false;
let suppressUntil = 0;
const extraControls = new Map<string, PlayerExtraControl>();
const positionMs = () =>
Math.floor(
(lastTimeSec +
(playing ? (performance.now() - lastTimeAt) / 1000 : 0)) *
1000
);
const suppressed = () => performance.now() < suppressUntil;
const applyEvent = (ev: EmbedEvent) => {
switch (ev.kind) {
case 'time': {
const jumped =
Math.abs(ev.seconds - positionMs() / 1000) >
SEEK_JUMP_SEC;
// Advancing time implies playing even when the protocol
// never sends an explicit play event.
const advancing = ev.seconds > lastTimeSec + 0.05;
lastTimeSec = ev.seconds;
lastTimeAt = performance.now();
// Some protocols bundle duration into the time event.
if (
ev.duration != null &&
Math.abs(ev.duration - durationSec) > 0.5
) {
durationSec = ev.duration;
cb.onDurationChange(Math.floor(ev.duration * 1000));
}
if (jumped && !suppressed()) {
cb.onSeek(Math.floor(ev.seconds * 1000));
}
if (!playing && advancing) {
playing = true;
if (!suppressed()) cb.onPlay(positionMs());
}
break;
}
case 'duration':
if (Math.abs(ev.seconds - durationSec) > 0.5) {
durationSec = ev.seconds;
cb.onDurationChange(Math.floor(ev.seconds * 1000));
}
break;
case 'play':
if (!playing) {
playing = true;
lastTimeAt = performance.now();
if (!suppressed()) cb.onPlay(positionMs());
}
break;
case 'pause':
if (playing) {
lastTimeSec = positionMs() / 1000;
playing = false;
if (!suppressed()) cb.onPause(positionMs());
}
break;
case 'ended':
playing = false;
cb.onEnded();
break;
case 'extraList':
if (ev.control.options.length > 0) {
extraControls.set(ev.control.id, ev.control);
cb.onExtraControls([...extraControls.values()]);
}
break;
case 'extraCurrent': {
const control = extraControls.get(ev.id);
if (control && control.current !== ev.value) {
extraControls.set(ev.id, { ...control, current: ev.value });
cb.onExtraControls([...extraControls.values()]);
}
break;
}
case 'hello':
break;
}
};
// contentWindow is read live on every use: it changes when the frame
// navigates, while ev.source comparison below stays valid because the
// browsing context object is stable for the life of the element.
const win = () => frame.contentWindow;
const makeAdapter = (p: ProtocolDef): EmbedAdapter => {
for (const control of p.staticExtras?.(frame.src) ?? []) {
extraControls.set(control.id, control);
}
if (extraControls.size > 0) {
cb.onExtraControls([...extraControls.values()]);
}
const probeExtras = () => {
const current = win();
if (current) p.probeExtras?.(current);
};
probeExtras();
const extraProbeTimers = [1500, 3000].map((delay) =>
window.setTimeout(probeExtras, delay)
);
// Reload-based (Kodik) seeking: replace frame.src at a start offset,
// debounced so drift-reconcile can't spam reloads (each reload
// re-buffers and may replay an ad).
let lastReloadAt = 0;
const reloadTo = (sec: number) => {
const now = performance.now();
if (now - lastReloadAt < RELOAD_DEBOUNCE_MS) return;
lastReloadAt = now;
suppressUntil = now + SUPPRESS_MS;
lastTimeSec = Math.max(0, sec);
lastTimeAt = now;
playing = true; // start_from auto-resumes
frame.src = p.reloadSeek!(frame.src, sec);
};
return {
protocol: p.name,
reloadBased: !!p.reloadSeek,
play() {
// Commands update state optimistically so positionMs()/paused()
// reflect intent immediately — otherwise the 3s sync heartbeat
// would fight the slow embed acknowledgement.
suppressUntil = performance.now() + SUPPRESS_MS;
playing = true;
lastTimeAt = performance.now();
if (p.reloadSeek) {
// No play command — resume by reloading at the current spot.
reloadTo(lastTimeSec);
return;
}
const w = win();
if (w) p.play(w);
},
pause() {
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = positionMs() / 1000;
playing = false;
// Reload-based players (Kodik) have no pause — best-effort no-op.
if (p.reloadSeek) return;
const w = win();
if (w) p.pause(w);
},
seekMs(ms: number) {
if (p.reloadSeek) {
reloadTo(ms / 1000);
return;
}
suppressUntil = performance.now() + SUPPRESS_MS;
lastTimeSec = ms / 1000;
lastTimeAt = performance.now();
const w = win();
if (w) p.seek(w, ms / 1000);
},
setVolume(v01: number) {
const w = win();
if (w) p.volume(w, Math.max(0, Math.min(1, v01)));
},
extras: () => [...extraControls.values()],
setExtra(id, value) {
const control = extraControls.get(id);
if (!control || !p.setExtra) return;
suppressUntil = performance.now() + 1500;
extraControls.set(id, { ...control, current: value });
cb.onExtraControls([...extraControls.values()]);
const current = win();
if (current) p.setExtra(current, id, value);
},
positionMs,
durationMs: () => Math.floor(durationSec * 1000),
paused: () => !playing,
destroy() {
window.removeEventListener('message', handler);
clearInterval(probeTimer);
clearTimeout(giveUp);
for (const timer of extraProbeTimers) clearTimeout(timer);
},
};
};
const handler = (ev: MessageEvent) => {
if (ev.source !== frame.contentWindow) return;
if (locked) {
const e = locked.parse(ev.data);
if (e) applyEvent(e);
else if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
return;
}
for (const p of probeSet) {
const e = p.parse(ev.data);
if (e) {
locked = p;
clearInterval(probeTimer);
clearTimeout(giveUp);
applyEvent(e);
resolve(makeAdapter(p));
return;
}
}
if (import.meta.env.DEV) {
console.debug('[embed] unrecognized message', ev.data);
}
};
window.addEventListener('message', handler);
const sendProbes = () => {
const w = win();
if (!w || locked) return;
for (const p of probeSet) p.probe(w);
};
// The inner player may boot slowly; keep probing until lock or timeout.
const probeTimer = setInterval(sendProbes, PROBE_INTERVAL_MS);
frame.addEventListener('load', sendProbes);
sendProbes();
const giveUp = setTimeout(() => {
if (locked) return;
window.removeEventListener('message', handler);
clearInterval(probeTimer);
resolve(null);
}, timeoutMs);
});
}
-96
View File
@@ -1,96 +0,0 @@
// Emoji support for watch chat and reactions (item 16). A curated Unicode set
// across categories (dependency-free — no multi-MB emoji-data bundle), plus
// admin-managed custom image emojis served at /emoji/<name> and referenced by
// :name: shortcodes. Recently-used emoji are remembered locally.
import { Store } from './store';
import { rpc } from './rpc';
export interface CustomEmoji {
name: string;
mime: string;
}
export const emojiStore = new Store<{
custom: CustomEmoji[];
recent: string[]; // unicode chars or :shortcode:
}>({
custom: [],
recent: JSON.parse(localStorage.getItem('echoion.recentEmoji') || '[]'),
});
export async function loadCustomEmojis() {
try {
const res = await rpc.call<{ emojis?: CustomEmoji[] }>(
'GetCustomEmojis'
);
emojiStore.set({ custom: (res && res.emojis) || [] });
} catch {
/* not connected / not authed — leave empty */
}
}
export function rememberEmoji(token: string) {
const recent = [
token,
...emojiStore.get().recent.filter((r) => r !== token),
].slice(0, 24);
emojiStore.set({ recent });
localStorage.setItem('echoion.recentEmoji', JSON.stringify(recent));
}
// Curated categories of common Unicode emoji.
export const EMOJI_CATEGORIES: Array<{ label: string; emoji: string[] }> = [
{
label: 'Smileys',
emoji: [
'😀', '😁', '😂', '🤣', '😊', '😇', '🙂', '😉', '😍', '🥰',
'😘', '😜', '🤪', '😎', '🤩', '🥳', '😏', '😒', '😔', '😞',
'😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶',
'😱', '😨', '🤗', '🤔', '🤫', '🤥', '😴', '🤤', '😷', '🤒',
],
},
{
label: 'Gestures',
emoji: [
'👍', '👎', '👌', '✌️', '🤞', '🤟', '🤘', '👊', '✊', '🙌',
'👏', '🙏', '💪', '👀', '👋', '🤙', '💅', '🖖', '🫶', '🤝',
],
},
{
label: 'Hearts',
emoji: [
'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍', '💔', '❣️',
'💕', '💞', '💓', '💗', '💖', '💘', '💝', '✨', '💯', '🔥',
],
},
{
label: 'Fun',
emoji: [
'🎉', '🎊', '🥂', '🍻', '🍕', '🍿', '🎮', '🎧', '🎵', '🎸',
'⚡', '🌟', '💥', '👑', '🚀', '🏆', '🎯', '💎', '🌈', '☀️',
],
},
];
// Render a chat message: plain text with :name: custom-emoji shortcodes
// replaced by <img> tags. Returns React nodes (text is auto-escaped by React).
export function renderChatText(text: string): (string | EmojiToken)[] {
const out: (string | EmojiToken)[] = [];
const re = /:([a-z0-9_]{1,32}):/g;
const custom = new Set(emojiStore.get().custom.map((c) => c.name));
let last = 0;
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
if (!custom.has(m[1])) continue;
if (m.index > last) out.push(text.slice(last, m.index));
out.push({ emojiName: m[1] });
last = m.index + m[0].length;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
export interface EmojiToken {
emojiName: string;
}
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { viewFromHash } from './router';
describe('dashboard routing', () => {
it('uses dashboard as the default and redirects the retired now view', () => {
expect(viewFromHash('')).toBe('dashboard');
expect(viewFromHash('#now')).toBe('dashboard');
expect(viewFromHash('#dashboard')).toBe('dashboard');
});
it('keeps the remaining flat views bookmarkable', () => {
expect(viewFromHash('#queue')).toBe('queue');
expect(viewFromHash('#server')).toBe('server');
});
});
+13 -24
View File
@@ -1,51 +1,40 @@
// Tiny hash router: keeps the active view in the URL so views are
// 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.
// the app has a single flat set of views.
import { appStore, type ViewName } from './app';
import { joinRoom, watchStore } from './watch';
const VIEWS: readonly ViewName[] = [
'now',
'dashboard',
'queue',
'search',
'library',
'stats',
'rooms',
'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(/^#\/?/, '');
// The view named by the current hash, defaulting to `dashboard`. Old `#now`
// bookmarks are intentionally canonicalized during router initialization.
export function viewFromHash(hash = location.hash): ViewName {
const raw = hash.replace(/^#\/?/, '');
const base = raw.split(/[/?]/)[0];
if (base === 'now') return 'dashboard';
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;
: 'dashboard';
}
export function initRouter() {
// Initial view comes from the hash (refresh / shared link).
appStore.set({ view: viewFromHash() });
const initial = viewFromHash();
appStore.set({ view: initial });
if (location.hash.replace(/^#\/?/, '').split(/[/?]/)[0] === 'now') {
history.replaceState(null, '', '#dashboard');
}
window.addEventListener('hashchange', () => {
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);
}
});
}
+19 -17
View File
@@ -62,23 +62,25 @@ export type RpcMethodName =
| 'GetAuditLog'
| 'GetUserPrefs'
| 'SetUserPrefs'
| 'GetCustomEmojis'
| 'AddCustomEmoji'
| 'RemoveCustomEmoji'
| 'ListListeningRooms'
| 'CreateListeningRoom'
| 'DeleteListeningRoom'
| 'JoinListeningRoom'
| 'LeaveListeningRoom'
| 'PlayInListeningRoom'
| 'PauseListeningRoom'
| 'ResumeListeningRoom'
| 'StopListeningRoom'
| 'GetListeningRoomQueue'
| 'SkipListeningRoom'
| 'RemoveFromListeningRoomQueue'
| 'MoveInListeningRoomQueue'
| 'ClearListeningRoomQueue';
| 'GetCapabilities'
| 'GetPluginExtensions'
| 'PluginCall'
| 'GetTeamSpeakDirectory'
| 'MoveTeamSpeakClient'
| 'KickTeamSpeakClient'
| 'BanTeamSpeakClient'
| 'GetTeamSpeakBans'
| 'UnbanTeamSpeakClient'
| 'CreateTeamSpeakChannel'
| 'EditTeamSpeakChannel'
| 'ReorderTeamSpeakChannel'
| 'DeleteTeamSpeakChannel'
| 'GetTeamSpeakServerGroups'
| 'AddTeamSpeakServerGroupMember'
| 'RemoveTeamSpeakServerGroupMember'
| 'SendTeamSpeakPrivateMessage'
| 'SendTeamSpeakChannelMessage'
| 'SendTeamSpeakServerMessage';
type Pending = {
+42 -15
View File
@@ -12,6 +12,48 @@ export interface Track {
source?: number; // TrackSource enum: 1 = YouTube, 6 = Yandex
}
export interface PublicDashboardClient {
nickname: string;
talking: boolean;
muted: boolean;
deafened: boolean;
away: boolean;
}
export interface PublicDashboardChannel {
id: number;
name: string;
parentId: number | null;
order: number;
default: boolean;
permanent: boolean;
semiPermanent: boolean;
password: boolean;
maxClients: number;
currentClients: number;
clients: PublicDashboardClient[];
channels: PublicDashboardChannel[];
}
export interface PublicDashboard {
server: {
name: string;
connected: boolean;
clientCount: number;
maxClients: number;
channelCount: number;
revision: number;
};
channels: PublicDashboardChannel[];
playback: {
isPlaying: boolean;
isPaused: boolean;
positionMs: number;
volume: number;
track: (Track & { durationMs?: number; album?: string }) | null;
};
}
export interface QueueEntry {
queueId: number;
track: Track;
@@ -19,21 +61,6 @@ export interface QueueEntry {
addedBy?: string;
}
export interface ListeningRoom {
name: string;
ownerId: number;
members: number[];
isPlaying: boolean;
isPaused: boolean;
queueSize: number;
isOwner: boolean;
}
export interface ListeningRoomList {
rooms: ListeningRoom[];
currentRoom?: string;
}
export interface Status {
isPlaying?: boolean;
isPaused?: boolean;
@@ -1,53 +0,0 @@
import { useEffect, useState, type RefObject } from 'react';
// Auto-hides the Watch player's overlay controls (and the mouse cursor) after
// `idleMs` of no input while a video is PLAYING, and reveals them instantly on
// any input — like a regular video player, in both windowed and fullscreen.
// Hover / keyboard-focus reveal (and keeping controls up while a dropdown is
// open) is left to CSS (:hover / :focus-within); this hook only owns the idle
// timeout and the "always visible while paused" rule. Returns the hidden flag.
export function useControlsAutoHide(
shellRef: RefObject<HTMLElement | null>,
opts: { playing: boolean; enabled?: boolean; idleMs?: number }
): boolean {
const { playing, enabled = true, idleMs = 3000 } = opts;
const [hidden, setHidden] = useState(false);
useEffect(() => {
const shell = shellRef.current;
// Paused, disabled, or no element: always show, no timer.
if (!shell || !enabled || !playing) {
setHidden(false);
return;
}
let timer: number | undefined;
const arm = () => {
if (timer) window.clearTimeout(timer);
timer = window.setTimeout(() => setHidden(true), idleMs);
};
const reveal = () => {
setHidden(false); // React bails when already false → no churn
arm();
};
const events = [
'mousemove',
'pointerdown',
'touchstart',
'keydown',
'focusin',
] as const;
for (const e of events) {
shell.addEventListener(e, reveal, { passive: true });
}
// Entering/leaving fullscreen counts as activity.
document.addEventListener('fullscreenchange', reveal);
arm();
return () => {
if (timer) window.clearTimeout(timer);
for (const e of events) shell.removeEventListener(e, reveal);
document.removeEventListener('fullscreenchange', reveal);
};
}, [shellRef, playing, enabled, idleMs]);
return hidden;
}
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -1,6 +1,5 @@
// Shared loader for the YouTube IFrame API. Both Watch Together and the Now
// Playing video preview use it; the script is injected once and callers await
// the same readiness promise.
// Shared loader for the dashboard's muted YouTube preview. 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):
+1 -1
View File
@@ -5,7 +5,7 @@ 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';
export const WEB_BUILD_ID = '2026.07.13-external-player-fix.1';
document.documentElement.dataset.echoionBuild = WEB_BUILD_ID;
console.info(`[Echoion] web build ${WEB_BUILD_ID}`);
+109 -270
View File
@@ -166,7 +166,7 @@ select:focus:not(:focus-visible) { outline: none; }
/* Inline SVG icons (components/icons.tsx) baseline-align inside text buttons
and never shrink in flex rows. */
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .room-chip svg, .link svg {
.btn svg, .icon-btn svg, .ctrl svg, .pill svg, .link svg {
vertical-align: -0.125em; flex: none;
}
@@ -398,145 +398,15 @@ select:focus:not(:focus-visible) { outline: none; }
.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;
}
/* ── Shared playback controls ─────────────────────────────────────────── */
.player-control-row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.player-control-row .ctrl-main { width: 42px; height: 42px; }
.player-local-row .bar { flex: 0 0 130px; }
.player-local-row[hidden] { display: none; }
.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; }
@@ -587,7 +457,7 @@ select:focus:not(:focus-visible) { outline: none; }
.drawer-backdrop { display: none; }
@media (max-width: 1080px) {
.now-grid, .stats-grid, .watch-grid { grid-template-columns: 1fr; }
.now-grid, .stats-grid { grid-template-columns: 1fr; }
}
/* Tablet and below: the sidebar becomes a slide-in drawer. */
@@ -620,10 +490,10 @@ select:focus:not(:focus-visible) { outline: none; }
.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; }
.search-row, .row-gap { flex-wrap: wrap; }
.search-row input { min-width: 0; flex: 1 1 160px; }
.player-control-row { flex-wrap: wrap; row-gap: 8px; }
.player-local-row .bar { flex: 1 1 100px; }
.tabs { overflow-x: auto; }
.audit-row { grid-template-columns: 1fr auto; }
.audit-time { grid-column: 1 / -1; }
@@ -653,9 +523,6 @@ select:focus:not(:focus-visible) { outline: none; }
/* Reactions rendered inside the player box (the vanilla UI appended them
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 {
@@ -675,6 +542,104 @@ select:focus:not(:focus-visible) { outline: none; }
.np-video-toggle { align-self: flex-start; margin-bottom: 8px; }
.np-video-toggle.on { color: #b28dff; }
/* Public TeamSpeak directory. Nested channels keep their server order while
the guide line makes deep trees readable without turning them into tables. */
.ts-directory-card { min-height: 360px; }
.ts-server-head { align-items: flex-start; }
.ts-server-head h2 { margin-bottom: 2px; }
.ts-connected { color: #74e5a2; border-color: rgba(95, 224, 148, 0.3); }
.ts-disconnected { color: #ef8a8a; border-color: rgba(239, 99, 99, 0.28); }
.ts-summary {
display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
margin: 14px 0 16px;
}
.ts-summary > div {
display: flex; flex-direction: column; gap: 2px;
padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.ts-summary strong { font-size: 18px; }
.ts-summary span { color: var(--muted-2); font-size: 11px; }
.ts-tree { display: flex; flex-direction: column; gap: 3px; }
.ts-channel {
position: relative;
margin-left: calc(var(--tree-depth, 0) * 18px);
}
.ts-channel::before {
content: ''; position: absolute; left: -10px; top: 0; bottom: 0;
border-left: 1px solid rgba(255, 255, 255, 0.08);
}
.ts-channel-row, .ts-client-row {
display: flex; align-items: center; min-width: 0;
border-radius: 8px;
}
.ts-channel-row { min-height: 34px; padding: 4px 7px; gap: 7px; }
.ts-channel-row:hover, .ts-client-row:hover { background: rgba(255, 255, 255, 0.035); }
.ts-channel-caret { width: 14px; color: var(--faint); text-align: center; }
.ts-channel-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-weight: 650; }
.ts-capacity { margin-left: auto; color: var(--faint); font: 11px var(--font-mono); }
.ts-tag {
padding: 2px 6px; border-radius: 999px; color: var(--muted-2);
background: rgba(255, 255, 255, 0.06); font-size: 9px;
letter-spacing: 0.04em; text-transform: uppercase;
}
.ts-client-row { min-height: 30px; margin-left: 26px; padding: 3px 8px; gap: 8px; }
.ts-presence { width: 7px; height: 7px; flex: none; border-radius: 50%; background: #687080; }
.ts-presence.talking { background: #5fe094; box-shadow: 0 0 0 4px rgba(95, 224, 148, 0.1); }
.ts-client-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 13px; }
.ts-client-flags { display: flex; gap: 5px; margin-left: auto; }
.ts-client-flags span {
color: var(--faint); font-size: 9px; text-transform: uppercase;
letter-spacing: 0.04em;
}
.nav-external { margin-left: auto; color: var(--faint); }
/* Guarded administration surface. */
.admin-tabs {
display: flex; gap: 4px; overflow-x: auto; margin-bottom: 14px;
padding: 4px; border: 1px solid var(--line); border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.admin-tab {
flex: none; border: 0; border-radius: 8px; padding: 8px 13px;
background: transparent; color: var(--muted-2); cursor: pointer;
font: inherit; font-size: 12px; font-weight: 650;
}
.admin-tab.active { background: rgba(124, 92, 255, 0.16); color: #c9bfff; }
.admin-stack { display: flex; flex-direction: column; gap: 14px; }
.admin-action-grid { display: flex; flex-wrap: wrap; gap: 10px; }
.admin-guard { max-width: 620px; }
.ts-admin-tree { display: flex; flex-direction: column; gap: 7px; }
.ts-admin-channel {
border-left: 1px solid rgba(255, 255, 255, 0.08);
padding: 7px 0 2px 10px;
}
.ts-admin-channel-head {
display: flex; align-items: center; gap: 7px; flex-wrap: wrap;
min-height: 34px;
}
.ts-admin-channel-head .ts-capacity { margin-left: 0; margin-right: auto; }
.ts-admin-client {
display: grid; grid-template-columns: minmax(180px, 0.8fr) minmax(250px, 1.2fr) auto;
gap: 10px; align-items: center; margin: 5px 0 5px 20px; padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.055); border-radius: 9px;
background: rgba(255, 255, 255, 0.018);
}
.ts-admin-client-main, .ts-admin-private, .ts-admin-actions {
display: flex; align-items: center; gap: 7px; min-width: 0; flex-wrap: wrap;
}
.ts-admin-private { font: 10px var(--font-mono); }
.ts-admin-actions { justify-content: flex-end; }
.ts-admin-actions .btn, .ts-admin-channel-head .btn { padding: 5px 8px; font-size: 10px; }
.ts-ban-row {
display: grid; grid-template-columns: 1fr auto auto; gap: 12px;
align-items: center; padding: 9px 0; border-bottom: 1px solid var(--line);
}
@media (max-width: 900px) {
.ts-admin-client { grid-template-columns: 1fr; }
.ts-admin-actions { justify-content: flex-start; }
}
/* Announce composer modal (item 14). */
.modal-backdrop {
position: fixed; inset: 0; z-index: 100; display: flex;
@@ -720,129 +685,3 @@ select:focus:not(:focus-visible) { outline: none; }
}
.ts-markup details { margin: 0.4em 0; }
.ts-markup summary { cursor: pointer; font-weight: 600; }
/* Watch Together room switcher (item 3). */
.pill-room { cursor: pointer; border: none; font: inherit; }
.rooms-panel {
display: flex; flex-direction: column; gap: 10px;
padding: 12px; margin: 4px 0 2px;
border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 12px;
background: rgba(255, 255, 255, 0.03);
}
.rooms-list { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.room-chip {
background: rgba(255, 255, 255, 0.06); border: 1px solid transparent;
border-radius: 8px; padding: 5px 10px; cursor: pointer;
color: inherit; font: inherit; font-size: 13px;
}
.room-chip.active { border-color: #7c5cff; color: #b28dff; }
.rooms-create { display: flex; gap: 8px; }
.rooms-create input { flex: 1; }
/* ── Independent listening rooms ─────────────────────────────────────── */
.listening-rooms-view { --room-cyan: #61e4d8; --room-cyan-soft: rgba(97, 228, 216, .12); }
.rooms-hero {
display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(280px, .7fr);
gap: 28px; align-items: end; margin-bottom: 18px; padding: 24px;
border: 1px solid rgba(97, 228, 216, .15); border-radius: 18px;
background: radial-gradient(circle at 92% 8%, rgba(97, 228, 216, .14), transparent 34%), linear-gradient(115deg, rgba(124, 92, 255, .11), rgba(255, 255, 255, .025));
position: relative; overflow: hidden;
}
.rooms-hero::after {
content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .22;
background-image: linear-gradient(rgba(255,255,255,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.035) 1px, transparent 1px);
background-size: 28px 28px; mask-image: linear-gradient(90deg, transparent, #000);
}
.rooms-hero > * { position: relative; z-index: 1; }
.rooms-hero h2 { font-size: clamp(20px, 2.5vw, 31px); max-width: 620px; letter-spacing: -.035em; }
.rooms-hero p { color: var(--muted); line-height: 1.55; max-width: 620px; margin-top: 8px; }
.rooms-kicker { display: block; margin-bottom: 7px; color: var(--room-cyan); font-family: var(--font-mono); font-size: 10px; font-weight: 700; letter-spacing: .18em; }
.listening-room-create { display: flex; gap: 8px; }
.listening-room-create input { flex: 1; min-width: 0; }
.listening-room-create .btn, .room-play-form .btn { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.listening-room-grid { display: grid; grid-template-columns: minmax(260px, .7fr) minmax(0, 1.3fr); gap: 18px; align-items: start; }
.room-directory, .room-console { min-height: 440px; }
.listening-room-list { display: flex; flex-direction: column; gap: 8px; }
.listening-room-card { width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding: 12px; text-align: left; color: var(--text-2); background: rgba(255,255,255,.025); border: 1px solid rgba(255,255,255,.055); border-radius: 11px; cursor: pointer; transition: border-color .16s, background .16s, transform .16s; }
.listening-room-card:hover { transform: translateX(2px); border-color: rgba(97,228,216,.22); background: rgba(97,228,216,.045); }
.listening-room-card.active { border-color: rgba(97,228,216,.5); background: var(--room-cyan-soft); box-shadow: inset 3px 0 0 var(--room-cyan); }
.room-signal { width: 9px; height: 9px; border-radius: 50%; background: var(--faint); box-shadow: 0 0 0 4px rgba(255,255,255,.025); }
.room-signal.playing { background: var(--room-cyan); box-shadow: 0 0 0 4px rgba(97,228,216,.1), 0 0 14px rgba(97,228,216,.45); animation: ech-pulse 1.6s infinite; }
.room-card-copy { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.room-card-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.room-card-copy small { color: var(--muted-2); }
.room-state { font-family: var(--font-mono); font-size: 9px; font-weight: 700; letter-spacing: .1em; color: var(--room-cyan); }
.room-console { position: relative; overflow: hidden; }
.room-console::before { content: ''; position: absolute; top: 0; right: 0; width: 180px; height: 180px; background: radial-gradient(circle at top right, rgba(124,92,255,.1), transparent 68%); pointer-events: none; }
.room-console-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 14px; margin-bottom: 18px; position: relative; }
.room-console-head h2 { font-size: 25px; }
.room-console-empty { min-height: 390px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; color: var(--muted); }
.room-console-empty h2 { color: var(--text); margin: 8px 0 5px; }
.room-console-glyph { font-family: var(--font-mono); font-size: 54px; font-weight: 700; color: rgba(97,228,216,.15); letter-spacing: -.12em; }
.room-transport { display: flex; align-items: center; gap: 12px; padding: 14px; margin-bottom: 14px; border: 1px solid rgba(97,228,216,.12); border-radius: 13px; background: linear-gradient(90deg, rgba(97,228,216,.07), rgba(255,255,255,.025)); }
.room-transport .ctrl-main { background: var(--room-cyan); color: #061715; box-shadow: 0 5px 22px rgba(97,228,216,.22); }
.stop-square { width: 9px; height: 9px; background: currentColor; border-radius: 1px; }
.room-transport-copy { display: flex; flex-direction: column; gap: 2px; }
.room-transport-copy small { color: var(--muted-2); }
.room-play-form { display: flex; gap: 8px; margin-bottom: 20px; }
.room-play-form input { flex: 1; min-width: 0; }
.room-queue-head { display: flex; justify-content: space-between; align-items: center; border-top: 1px solid var(--line); padding-top: 16px; margin-bottom: 5px; }
.room-queue-head span { color: var(--muted-2); font-family: var(--font-mono); font-size: 11px; }
.room-tracklist { max-height: 330px; overflow-y: auto; }
@media (max-width: 1080px) {
.listening-room-grid { grid-template-columns: 1fr; }
.room-directory, .room-console { min-height: 0; }
}
@media (max-width: 560px) {
.rooms-hero { grid-template-columns: 1fr; padding: 18px; }
.listening-room-create, .room-play-form { flex-wrap: wrap; }
.listening-room-create input, .room-play-form input { flex-basis: 100%; }
.room-console-head { flex-direction: column; }
}
/* Watch search (item 20). */
.watch-search { position: relative; margin-bottom: 8px; }
.watch-search-results {
position: absolute; z-index: 30; left: 0; right: 0; top: 100%;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px; margin-top: 4px; max-height: 320px; overflow: auto;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.watch-search-item {
display: flex; align-items: center; gap: 10px; width: 100%;
padding: 6px 10px; background: transparent; border: none; cursor: pointer;
color: inherit; text-align: left; font: inherit;
}
.watch-search-item:hover { background: rgba(255, 255, 255, 0.06); }
.watch-search-item .track-cover { width: 48px; height: 27px; flex: none; border-radius: 4px; }
.watch-search-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* Emoji picker + custom emojis (item 16). */
.emoji-anchor { position: relative; display: inline-flex; }
.emoji-trigger { padding: 6px 8px; }
.emoji-picker {
position: absolute; bottom: 100%; left: 0; z-index: 40; width: 300px;
max-height: 320px; overflow-y: auto; margin-bottom: 6px; padding: 8px;
background: #14141f; border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px; box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
}
.emoji-section { margin-bottom: 8px; }
.emoji-section-label {
font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase;
color: #8a8a98; margin: 4px 2px;
}
.emoji-grid { display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; }
.emoji-btn {
background: transparent; border: none; cursor: pointer; font-size: 20px;
line-height: 1; padding: 4px; border-radius: 6px;
}
.emoji-btn:hover { background: rgba(255, 255, 255, 0.08); }
.emoji-img { width: 20px; height: 20px; vertical-align: middle; object-fit: contain; }
.emoji-img-lg { width: 30px; height: 30px; object-fit: contain; }
.emoji-manage-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-bottom: 12px; }
.emoji-manage-grid { display: flex; flex-wrap: wrap; gap: 12px; }
.emoji-manage-item {
display: flex; align-items: center; gap: 6px;
background: rgba(255, 255, 255, 0.05); border-radius: 8px; padding: 6px 10px;
}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, type CSSProperties } from 'react';
import { appStore, loadFavorites, safeCall, showView, toast } from '../lib/app';
import { useStore } from '../lib/store';
import { PlayerControls } from '../components/PlayerControls';
@@ -15,8 +15,9 @@ import {
SkipPrevIcon,
} from '../components/icons';
import { t, tf } from '../i18n';
import type { PublicDashboardChannel } from '../lib/types';
const VIDEO_PREF_KEY = 'echoion.npVideo';
const DASHBOARD_VIDEO_PREF_KEY = 'echoion.npVideo';
async function togglePlay() {
const st = appStore.get().status || {};
@@ -24,10 +25,62 @@ async function togglePlay() {
else await safeCall('Resume');
}
export function NowView() {
function ChannelNode({
channel,
depth = 0,
}: {
channel: PublicDashboardChannel;
depth?: number;
}) {
return (
<div
className="ts-channel"
style={{ '--tree-depth': depth } as CSSProperties}
>
<div className="ts-channel-row">
<span className="ts-channel-caret" aria-hidden="true">
{channel.channels.length || channel.clients.length ? '⌄' : '·'}
</span>
<span className="ts-channel-name">{channel.name}</span>
{channel.default && <span className="ts-tag">{t('default')}</span>}
{channel.password && (
<span className="ts-tag" title={t('Password protected')}>
{t('locked')}
</span>
)}
<span className="ts-capacity">
{channel.currentClients}/
{channel.maxClients > 0 ? channel.maxClients : '∞'}
</span>
</div>
{channel.clients.map((client, index) => (
<div
className="ts-client-row"
key={`${client.nickname}-${index}`}
>
<span
className={'ts-presence' + (client.talking ? ' talking' : '')}
aria-label={client.talking ? t('Talking') : t('Online')}
/>
<span className="ts-client-name">{client.nickname}</span>
<div className="ts-client-flags">
{client.away && <span title={t('Away')}>away</span>}
{client.muted && <span title={t('Muted')}>mic off</span>}
{client.deafened && <span title={t('Deafened')}>sound off</span>}
</div>
</div>
))}
{channel.channels.map((child) => (
<ChannelNode key={child.id} channel={child} depth={depth + 1} />
))}
</div>
);
}
export function DashboardView() {
const s = useStore(appStore);
const [videoOn, setVideoOn] = useState(
localStorage.getItem(VIDEO_PREF_KEY) === '1'
localStorage.getItem(DASHBOARD_VIDEO_PREF_KEY) === '1'
);
const track = s.current;
const videoId = youtubeIdFromUrl(track?.url);
@@ -50,7 +103,7 @@ export function NowView() {
const needed = st.skipVotesNeeded || 0;
return (
<section className="view" id="view-now">
<section className="view" id="view-dashboard">
<div className="now-grid">
<div className="card np-card">
{showVideo && videoId ? (
@@ -72,7 +125,7 @@ export function NowView() {
const next = !videoOn;
setVideoOn(next);
localStorage.setItem(
VIDEO_PREF_KEY,
DASHBOARD_VIDEO_PREF_KEY,
next ? '1' : '0'
);
}}
@@ -94,7 +147,7 @@ export function NowView() {
playing={playing}
positionMs={s.positionMs}
durationMs={durationMs}
canControl
canControl={!!s.identity}
volumePct={volumePct}
onTogglePlay={togglePlay}
onSeekMs={(ms) =>
@@ -108,7 +161,7 @@ export function NowView() {
? () => safeCall('Skip', { count: 1 })
: undefined
}
extra={
extra={s.identity ? (
<>
<button
className={
@@ -210,8 +263,8 @@ export function NowView() {
</span>
</button>
</>
}
extraLocal={
) : undefined}
extraLocal={s.identity ? (
<label className="toggle-row">
<span className="muted">{t('Radio')}</span>
<button
@@ -251,11 +304,66 @@ export function NowView() {
<span className="knob" />
</button>
</label>
}
) : undefined}
/>
</div>
</div>
<div className="col">
<div className="card ts-directory-card">
<div className="card-head ts-server-head">
<div>
<h2>
{s.publicDashboard?.server.name ||
t('TeamSpeak server')}
</h2>
<span className="muted">
{t('Complete channel directory')}
</span>
</div>
<span
className={
'pill ' +
(s.publicDashboard?.server.connected
? 'ts-connected'
: 'ts-disconnected')
}
>
{s.publicDashboard?.server.connected
? t('Connected')
: t('Disconnected')}
</span>
</div>
<div className="ts-summary">
<div>
<strong>
{s.publicDashboard?.server.clientCount || 0}
</strong>
<span>{t('clients')}</span>
</div>
<div>
<strong>
{s.publicDashboard?.server.channelCount || 0}
</strong>
<span>{t('channels')}</span>
</div>
<div>
<strong>
{s.publicDashboard?.server.maxClients || '∞'}
</strong>
<span>{t('capacity')}</span>
</div>
</div>
<div className="ts-tree">
{s.publicDashboard?.channels.length ? (
s.publicDashboard.channels.map((channel) => (
<ChannelNode key={channel.id} channel={channel} />
))
) : (
<EmptyRow text={t('No channels available')} />
)}
</div>
</div>
{s.identity && (
<div className="card">
<div className="card-head">
<h2>{t('Up Next')}</h2>
@@ -286,7 +394,9 @@ export function NowView() {
})()}
</div>
</div>
<LyricsPanel />
)}
{s.identity && <LyricsPanel />}
{s.identity && (
<div className="card">
<div className="card-head">
<h3>{t('Listening now')}</h3>
@@ -311,6 +421,7 @@ export function NowView() {
)}
</div>
</div>
)}
</div>
</div>
</section>
-244
View File
@@ -1,244 +0,0 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { safeCall, toast } from '../lib/app';
import type {
ListeningRoom,
ListeningRoomList,
QueueEntry,
} from '../lib/types';
import { confirmDialog } from '../lib/dialog';
import {
CloseIcon,
ArrowDownIcon,
ArrowUpIcon,
PauseIcon,
PlayIcon,
PlusIcon,
RefreshIcon,
SkipNextIcon,
} from '../components/icons';
import { EmptyRow, TrackRow } from '../components/TrackRow';
import { t, tf } from '../i18n';
import { rpc } from '../lib/rpc';
export function RoomsView() {
const [rooms, setRooms] = useState<ListeningRoom[]>([]);
const [currentRoom, setCurrentRoom] = useState<string | null>(null);
const [queue, setQueue] = useState<QueueEntry[]>([]);
const [roomName, setRoomName] = useState('');
const [query, setQuery] = useState('');
const [busy, setBusy] = useState(false);
const current = useMemo(
() => rooms.find((room) => room.name === currentRoom) || null,
[rooms, currentRoom]
);
const refresh = useCallback(async () => {
const result = await safeCall<ListeningRoomList>('ListListeningRooms');
if (!result) return;
setRooms(result.rooms || []);
setCurrentRoom(result.currentRoom || null);
if (result.currentRoom) {
const queueResult = await safeCall<{ queue?: QueueEntry[] }>(
'GetListeningRoomQueue',
{ room: result.currentRoom }
);
setQueue(queueResult?.queue || []);
} else {
setQueue([]);
}
}, []);
useEffect(() => {
void refresh();
const unsubscribe = rpc.on('listening_rooms.updated', () => void refresh());
const timer = window.setInterval(refresh, 30000);
return () => {
unsubscribe();
window.clearInterval(timer);
};
}, [refresh]);
const action = async (
method:
| 'JoinListeningRoom'
| 'LeaveListeningRoom'
| 'PauseListeningRoom'
| 'ResumeListeningRoom'
| 'StopListeningRoom'
| 'SkipListeningRoom'
| 'ClearListeningRoomQueue',
room?: string
) => {
setBusy(true);
const result = await safeCall(method, room ? { room } : undefined);
setBusy(false);
if (result) await refresh();
};
return (
<section className="view listening-rooms-view" id="view-rooms">
<div className="rooms-hero">
<div>
<span className="rooms-kicker">{t('MULTI-STREAM')}</span>
<h2>{t('Your channel, split into listening spaces')}</h2>
<p>
{t(
'Each room has its own queue and bot stream. Join one to hear and control it.'
)}
</p>
</div>
<form
className="listening-room-create"
onSubmit={async (event) => {
event.preventDefault();
const name = roomName.trim();
if (!name) return;
setBusy(true);
const result = await safeCall('CreateListeningRoom', {
room: name,
});
setBusy(false);
if (result) {
setRoomName('');
toast(tf('Created room “{0}”', name));
await refresh();
}
}}
>
<input
value={roomName}
onChange={(event) => setRoomName(event.target.value)}
placeholder={t('Room name')}
maxLength={48}
/>
<button className="btn btn-accent" disabled={busy || !roomName.trim()}>
<PlusIcon /> {t('Create room')}
</button>
</form>
</div>
<div className="listening-room-grid">
<div className="card room-directory">
<div className="card-head">
<h2>{t('Live rooms')}</h2>
<button className="icon-btn" onClick={refresh} title={t('Refresh rooms')}>
<RefreshIcon />
</button>
</div>
{rooms.length === 0 ? (
<EmptyRow text={t('No listening rooms yet')} />
) : (
<div className="listening-room-list">
{rooms.map((room) => {
const selected = room.name === currentRoom;
return (
<button
key={room.name}
className={'listening-room-card' + (selected ? ' active' : '')}
disabled={busy}
onClick={() => !selected && action('JoinListeningRoom', room.name)}
>
<span className={'room-signal' + (room.isPlaying ? ' playing' : '')} />
<span className="room-card-copy">
<strong>{room.name}</strong>
<small>
{tf('{0} listeners · {1} queued', room.members.length, room.queueSize)}
</small>
</span>
<span className="room-state">
{selected ? t('JOINED') : room.isPaused ? t('PAUSED') : room.isPlaying ? t('LIVE') : t('IDLE')}
</span>
</button>
);
})}
</div>
)}
</div>
<div className="card room-console">
{!current ? (
<div className="room-console-empty">
<span className="room-console-glyph">04</span>
<h2>{t('Choose a room')}</h2>
<p>{t('Your TeamSpeak audio follows the room you join.')}</p>
</div>
) : (
<>
<div className="room-console-head">
<div>
<span className="rooms-kicker">{t('NOW TUNED')}</span>
<h2>{current.name}</h2>
</div>
<div className="row-gap">
<button className="btn btn-ghost" onClick={() => action('LeaveListeningRoom')} disabled={busy}>
{t('Leave')}
</button>
{current.isOwner && (
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (!(await confirmDialog({ title: t('Delete room'), message: tf('Delete “{0}” for everyone?', current.name), confirmLabel: t('Delete'), danger: true }))) return;
const result = await safeCall('DeleteListeningRoom', { room: current.name });
if (result) await refresh();
}}
>
<CloseIcon /> {t('Delete')}
</button>
)}
</div>
</div>
<div className="room-transport">
<button className="ctrl" title={t('Stop')} onClick={() => action('StopListeningRoom', current.name)}><span className="stop-square" /></button>
<button
className="ctrl ctrl-main"
title={current.isPlaying && !current.isPaused ? t('Pause') : t('Resume')}
onClick={() => action(current.isPlaying && !current.isPaused ? 'PauseListeningRoom' : 'ResumeListeningRoom', current.name)}
>
{current.isPlaying && !current.isPaused ? <PauseIcon /> : <PlayIcon />}
</button>
<button className="ctrl" title={t('Skip')} onClick={() => action('SkipListeningRoom', current.name)}><SkipNextIcon /></button>
<div className="room-transport-copy">
<strong>{current.isPlaying ? (current.isPaused ? t('Paused') : t('Streaming now')) : t('Ready')}</strong>
<small>{tf('{0} people are tuned in', current.members.length)}</small>
</div>
</div>
<form
className="room-play-form"
onSubmit={async (event) => {
event.preventDefault();
const value = query.trim();
if (!value) return;
const result = await safeCall<{ message?: string }>('PlayInListeningRoom', { room: current.name, query: value });
if (result) { setQuery(''); toast(result.message || t('Added to room queue')); await refresh(); }
}}
>
<input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={t('Paste a URL or search for a track…')} />
<button className="btn btn-accent" disabled={!query.trim()}><PlusIcon /> {t('Add')}</button>
</form>
<div className="room-queue-head">
<h3>{t('Room queue')}</h3>
<div className="row-gap">
<span>{tf('{0} tracks', queue.length)}</span>
{!!queue.length && <button className="btn btn-danger-ghost" onClick={() => action('ClearListeningRoomQueue', current.name)}>{t('Clear')}</button>}
</div>
</div>
<div className="tracklist room-tracklist">
{queue.length ? queue.map((entry, index) => (
<TrackRow key={entry.queueId} track={entry.track} num={index + 1} playing={entry.isPlaying} actions={[
index > 0 && { icon: <ArrowUpIcon />, title: t('Move up'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index - 1 }); await refresh(); } },
index + 1 < queue.length && { icon: <ArrowDownIcon />, title: t('Move down'), onClick: async () => { await safeCall('MoveInListeningRoomQueue', { room: current.name, queueId: entry.queueId, newPosition: index + 1 }); await refresh(); } },
{ icon: <CloseIcon />, title: t('Remove'), cls: 'danger', onClick: async () => { await safeCall('RemoveFromListeningRoomQueue', { room: current.name, queueId: entry.queueId }); await refresh(); } },
]} />
)) : <EmptyRow text={t('This room queue is empty')} />}
</div>
</>
)}
</div>
</div>
</section>
);
}
+140 -136
View File
@@ -4,25 +4,36 @@ import { useStore } from '../lib/store';
import { EmptyRow } from '../components/TrackRow';
import { PersonRow } from '../components/PersonRow';
import { AnnounceModal } from '../components/AnnounceModal';
import { EmojiManager } from '../components/EmojiManager';
import { TeamSpeakAdmin } from '../components/TeamSpeakAdmin';
import type { AuditEntry, Subscriber } from '../lib/types';
import { auditMethodName } from '../lib/auditMethods';
import { confirmDialog } from '../lib/dialog';
import { t, tf } from '../i18n';
type AdminTab = 'teamspeak' | 'echoion' | 'subscribers' | 'emojis' | 'audit';
const TABS: Array<{ id: AdminTab; label: string }> = [
{ id: 'teamspeak', label: 'TeamSpeak' },
{ id: 'echoion', label: 'Echoion' },
{ id: 'subscribers', label: 'Subscribers' },
{ id: 'emojis', label: 'Emojis' },
{ id: 'audit', label: 'Audit history' },
];
export function ServerView() {
const s = useStore(appStore);
const [tab, setTab] = useState<AdminTab>('teamspeak');
const [users, setUsers] = useState<Subscriber[]>([]);
const [audit, setAudit] = useState<AuditEntry[]>([]);
const [announceOpen, setAnnounceOpen] = useState(false);
const isAdmin = !!(s.identity && s.identity.isAdmin);
const isAdmin = !!s.identity?.isAdmin;
const loadSubscribers = useCallback(async () => {
if (!isAdmin) return;
const res = await safeCall<{ users?: Subscriber[] }>('ManageUsers', {
action: 'list',
});
const list = (res && res.users) || [];
const list = res?.users || [];
setUsers(list);
appStore.set({ listeners: list });
}, [isAdmin]);
@@ -30,186 +41,179 @@ export function ServerView() {
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());
setAudit((res?.entries || []).slice().reverse());
}, [isAdmin]);
useEffect(() => {
loadSubscribers();
loadAudit();
}, [loadSubscribers, loadAudit]);
if (tab === 'subscribers') void loadSubscribers();
if (tab === 'audit') void loadAudit();
}, [tab, loadSubscribers, loadAudit]);
if (!isAdmin) {
return (
<section className="view" id="view-server">
<div className="card admin-guard">
<h2>{t('Administrator authentication required')}</h2>
<p className="muted">
{t('Sign in with an account in a configured TeamSpeak admin group.')}
</p>
</div>
</section>
);
}
return (
<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)}
>
<div className="admin-tabs" role="tablist" aria-label={t('Administration')}>
{TABS.map((item) => (
<button
key={item.id}
className={'admin-tab' + (tab === item.id ? ' active' : '')}
role="tab"
aria-selected={tab === item.id}
onClick={() => setTab(item.id)}
>
{t(item.label)}
</button>
))}
</div>
{tab === 'teamspeak' && <TeamSpeakAdmin />}
{tab === 'echoion' && (
<div className="card">
<div className="card-head">
<div>
<h2>{t('Echoion service')}</h2>
<p className="muted">{t('Bot messaging and runtime operations')}</p>
</div>
</div>
<div className="admin-action-grid">
<button className="btn btn-ghost" onClick={() => setAnnounceOpen(true)}>
{t('Announce…')}
</button>
<button
className="btn btn-ghost"
onClick={async () => {
await safeCall('ReloadConfig');
toast(t('Configuration reloaded'));
if (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.'
),
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'
)
);
}
) return;
if (await safeCall('RestartWebInterface'))
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) => (
)}
{tab === 'subscribers' && (
<div className="card">
<div className="card-head">
<h2>{t('Subscribers')} <span className="muted">· {users.length}</span></h2>
<div className="row-gap">
<button className="btn btn-ghost" onClick={loadSubscribers}>{t('Refresh')}</button>
<button
className="btn btn-danger-ghost"
onClick={async () => {
if (
!(await confirmDialog({
title: t('Unsub all'),
message: t('Remove ALL subscriptions? This cannot be undone.'),
confirmLabel: t('Remove all'),
danger: true,
}))
) return;
if (await safeCall('ManageUsers', { action: 'clearAll' })) {
toast(t('All subscriptions removed'));
void loadSubscribers();
}
}}
>
{t('Unsub all')}
</button>
</div>
</div>
<div className="people">
{users.length ? users.map((user) => (
<PersonRow
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'}
key={user.uid}
name={user.nickname || user.uid}
uid={user.uid}
sub={user.uid}
status={user.online ? t('Online') : t('Offline')}
statusColor={user.online ? '#5fe094' : '#6a6a78'}
>
<button
className="btn btn-danger-ghost"
onClick={async () => {
const who = u.nickname || u.uid;
const who = user.nickname || user.uid;
if (
!(await confirmDialog({
title: t('Unsubscribe'),
message: tf(
'Unsubscribe {0}?',
who
),
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();
) return;
if (await safeCall('ManageUsers', { action: 'remove', uid: user.uid }))
void loadSubscribers();
}}
>
{t('Unsub')}
</button>
</PersonRow>
))
)}
)) : <EmptyRow text={t('No subscribers')} />}
</div>
</div>
</div>
<div className="card">
<div className="card-head">
<h2>
{t('Audit log')}{' '}
<span className="muted">
{audit.length ? `· ${audit.length}` : ''}
</span>
</h2>
<button className="btn btn-ghost" onClick={loadAudit}>
{t('Refresh')}
</button>
</div>
{/* Cap the rendered rows; the header still shows the full count
and the container scrolls instead of growing endlessly. */}
<div className="tracklist audit-scroll">
{!audit.length ? (
<EmptyRow text={t('No audit entries yet')} />
) : (
audit.slice(0, 200).map((e, i) => (
<div
key={`${e.timestamp}-${i}`}
className="audit-row"
>
<span className="audit-method">
{auditMethodName(e.method)}
</span>
<span className="audit-client muted">
{tf('client #{0}', e.clientId)}
</span>
<span className="audit-time muted">
{new Date(
e.timestamp * 1000
).toLocaleString()}
</span>
</div>
))
)}
</div>
</div>
<EmojiManager />
{announceOpen && (
<AnnounceModal onClose={() => setAnnounceOpen(false)} />
)}
{tab === 'emojis' && (
<div className="card">
<h2>{t('Emojis')}</h2>
<p className="muted">
{t('Room emojis moved to VoidWatch and are managed from its administration page.')}
</p>
{s.watchUrl && (
<a className="btn btn-ghost" href={`${s.watchUrl.replace(/\/$/, '')}/admin.html`}>
{t('Open VoidWatch admin ↗')}
</a>
)}
</div>
)}
{tab === 'audit' && (
<div className="card">
<div className="card-head">
<h2>{t('Audit history')} <span className="muted">· {audit.length}</span></h2>
<button className="btn btn-ghost" onClick={loadAudit}>{t('Refresh')}</button>
</div>
<div className="tracklist audit-scroll">
{audit.length ? audit.slice(0, 200).map((entry, index) => (
<div key={`${entry.timestamp}-${index}`} className="audit-row">
<span className="audit-method">{auditMethodName(entry.method)}</span>
<span className="audit-client muted">{tf('client #{0}', entry.clientId)}</span>
<span className="audit-time muted">{new Date(entry.timestamp * 1000).toLocaleString()}</span>
</div>
)) : <EmptyRow text={t('No audit entries yet')} />}
</div>
</div>
)}
{announceOpen && <AnnounceModal onClose={() => setAnnounceOpen(false)} />}
</section>
);
}
-789
View File
@@ -1,789 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { toast } from '../lib/app';
import { useStore } from '../lib/store';
import {
attachPlayerMount,
applyExtraControl,
applyLocalVolume,
currentPlayerPositionMs,
isHost,
joinRoom,
leaveRoom,
livePositionMs,
playerBufferedFraction,
refreshRooms,
seekRelative,
send,
setRate,
setSourceChoice,
transferHost,
unmuteAutoplay,
voteSkip,
watchStore,
} from '../lib/watch';
import { Avatar } from '../components/Avatar';
import { PlayerControls } from '../components/PlayerControls';
import { PlayerSettingsMenu } from '../components/PlayerSettingsMenu';
import { EmptyRow } from '../components/TrackRow';
import { WatchSearch } from '../components/WatchSearch';
import { EmojiPicker } from '../components/EmojiPicker';
import { renderChatText } from '../lib/emoji';
import { useControlsAutoHide } from '../lib/useControlsAutoHide';
import {
CloseIcon,
CrownIcon,
PlusIcon,
PowerIcon,
RefreshIcon,
SkipNextIcon,
VolumeMuteIcon,
WatchIcon,
} from '../components/icons';
import { t, tf } from '../i18n';
const REACTION_EMOJI = ['🔥', '😂', '👀', '❤️'];
export function WatchView() {
const w = useStore(watchStore);
const playerRef = useRef<HTMLDivElement>(null);
const playerShellRef = useRef<HTMLDivElement>(null);
const chatLogRef = useRef<HTMLDivElement>(null);
const [url, setUrl] = useState('');
const [chatText, setChatText] = useState('');
const [newRoom, setNewRoom] = useState('');
const [chatPicker, setChatPicker] = useState(false);
const [reactPicker, setReactPicker] = useState(false);
// Re-render every 500ms while mounted so the position readout ticks
// (mirrors the old renderPositions interval).
const [, setTick] = useState(0);
useEffect(() => {
const id = setInterval(() => setTick((n) => n + 1), 500);
return () => clearInterval(id);
}, []);
// Re-attach when entering/leaving a room: the player div unmounts in the
// lobby (w.room === null) and remounts on join, so the mount must follow it.
useEffect(() => {
attachPlayerMount(playerRef.current);
return () => attachPlayerMount(null);
}, [w.room]);
useEffect(() => {
const log = chatLogRef.current;
if (log) log.scrollTop = log.scrollHeight;
}, [w.chat.length]);
// "Live" = no position authority / no seek: Twitch, and generic embeds
// unless the embed answered the postMessage handshake (server-confirmed
// via the room's `controllable` flag).
const live =
w.source === 'twitch' ||
(w.source === 'iframe' && !w.embedControlled);
const hosting = isHost();
const canControl = w.authenticated && hosting;
const choice = w.sourceChoice;
const hasPlayer = !!(w.videoId || w.url);
const pos = livePositionMs();
// Idle-hide the overlay controls + cursor while a video plays (windowed
// and fullscreen). Called before the early return below to keep hook order.
const controlsHidden = useControlsAutoHide(playerShellRef, {
playing: !w.paused,
enabled: hasPlayer,
});
// Lobby: no room joined by default. Pick an existing room or create one.
if (w.room == null) {
return (
<WatchLobby
rooms={w.rooms}
newRoom={newRoom}
setNewRoom={setNewRoom}
onRefresh={refreshRooms}
/>
);
}
return (
<section className="view" id="view-watch">
<div className="watch-grid">
<div className="col">
<div className="card">
<div className="card-head">
<div className="row-gap">
<button
className={
'btn src-yt' +
(choice === 'youtube' ? ' active' : '')
}
onClick={() => setSourceChoice('youtube')}
>
YouTube
</button>
<button
className={
'btn src-tw' +
(choice === 'twitch' ? ' active' : '')
}
onClick={() => setSourceChoice('twitch')}
>
Twitch
</button>
<button
className={
'btn src-direct' +
(choice === 'direct' ? ' active' : '')
}
onClick={() => setSourceChoice('direct')}
>
{t('Video URL')}
</button>
<button
className={
'btn src-iframe' +
(choice === 'iframe' ? ' active' : '')
}
onClick={() => setSourceChoice('iframe')}
>
{t('Embed')}
</button>
</div>
<div className="row-gap">
<span className="pill pill-room" title={t('Room')}>
<WatchIcon /> {w.room}
</span>
<span
className={
'pill' + (hosting ? ' pill-yellow' : '')
}
>
{!w.authenticated
? t('Guest — sign in to control')
: hosting
? t('You are hosting')
: t('Viewer')}
</span>
<span className="pill pill-green">
{t('Synced')}
</span>
{w.source === 'iframe' && hasPlayer && (
<span
className={
'pill' +
(w.embedControlled
? ' pill-green'
: '')
}
>
{w.embedControlled
? w.embedProtocol
? `${t('Embed synced')} · ${w.embedProtocol}`
: t('Embed synced')
: t('Embed is view-only')}
</span>
)}
<button
className="btn btn-leave"
title={t('Leave this room')}
onClick={() => leaveRoom()}
>
<PowerIcon /> {t('Leave room')}
</button>
</div>
</div>
<form
className="search-row"
onSubmit={(e) => {
e.preventDefault();
const input = url.trim();
if (!input) return;
if (choice === 'twitch') {
send({
type: 'watch.load',
source: 'twitch',
channel: input,
url: input,
});
} else {
send({
type: 'watch.load',
source: choice,
url: input,
});
}
}}
>
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder={
choice === 'twitch'
? t(
'Twitch channel or URL to watch together'
)
: choice === 'direct'
? t(
'Direct video or .m3u8 URL to watch together'
)
: choice === 'iframe'
? t(
'Embed URL (Kodik, etc.) to watch together'
)
: t(
'YouTube URL to watch together'
)
}
autoComplete="off"
disabled={!w.authenticated}
/>
<button className="btn btn-accent" type="submit">
{t('Load')}
</button>
<button
className="btn btn-ghost"
type="button"
title={t('Add to the watch queue')}
disabled={!w.authenticated}
onClick={async () => {
const input = url.trim();
if (!input) return;
const source = w.sourceChoice;
let title = '';
if (source === 'youtube') {
// Best-effort title so the queue shows
// names instead of URLs.
try {
const res = await fetch(
`https://www.youtube.com/oembed?url=${encodeURIComponent(input)}&format=json`
);
if (res.ok) {
title =
(await res.json()).title ||
'';
}
} catch {
/* offline or blocked */
}
}
send({
type: 'watch.queue.add',
source,
url: input,
title,
});
setUrl('');
}}
>
{t('+ Queue')}
</button>
</form>
{/* The shell (player + custom bar) is what goes
fullscreen, so the controls stay available; the bar
overlays the video and idle-hides during playback. */}
<div
className={
'player-shell' +
(w.source === 'youtube' ? ' youtube-native' : '') +
(controlsHidden ? ' controls-hidden' : '')
}
ref={playerShellRef}
>
<div className="player-box">
<div ref={playerRef} id="watchPlayer" />
{w.playerEmpty && (
<div className="player-empty">
{t(w.playerEmpty)}
</div>
)}
{w.mutedAutoplay && (
<button
className="btn btn-accent unmute-btn"
title={t('Tap to unmute')}
onClick={() => unmuteAutoplay()}
>
<VolumeMuteIcon /> {t('Tap to unmute')}
</button>
)}
<div className="reaction-layer">
{w.reactions.map((r) => (
<span
key={r.id}
className="reaction-fly reaction-fly-abs"
style={{
left: `${10 + ((r.id * 37) % 80)}%`,
}}
>
{/^:[a-z0-9_]+:$/.test(r.emoji) ? (
<img
className="emoji-img-lg"
src={`/emoji/${r.emoji.slice(1, -1)}`}
alt={r.emoji}
/>
) : (
r.emoji
)}
</span>
))}
</div>
</div>
<div className="player-overlay">
<PlayerControls
playing={!w.paused}
positionMs={pos}
durationMs={w.durationMs}
live={live}
canControl={canControl}
bufferedPct={playerBufferedFraction() * 100}
volumePct={w.localVolume}
volumeLive
onTogglePlay={() =>
send({
type: w.paused
? 'watch.play'
: 'watch.pause',
positionMs: currentPlayerPositionMs(),
})
}
onSeekMs={(ms) =>
send({
type: 'watch.seek',
positionMs: ms,
})
}
onSeekBy={seekRelative}
onVolume={(pct) => applyLocalVolume(pct)}
onSkip={() =>
send({ type: 'watch.queue.next' })
}
skipDisabled={!w.queue.length}
settings={
<PlayerSettingsMenu
extras={w.extraControls}
rate={w.rate}
rateOptions={
w.source === 'youtube' ||
w.extraControls.some((c) => c.id === 'speed')
? [0.5, 0.75, 1, 1.25, 1.5, 2]
: undefined
}
canControl={canControl}
onExtra={applyExtraControl}
onRate={setRate}
/>
}
onFullscreen={() => {
if (document.fullscreenElement) {
document.exitFullscreen();
} else {
playerShellRef.current
?.requestFullscreen()
.catch(() =>
toast(
t('Fullscreen unavailable')
)
);
}
}}
showLocal={hasPlayer}
extra={
<button
className="btn btn-ghost"
onClick={() => {
send({ type: 'watch.state' });
toast(t('Resynced to room'));
}}
>
{t('Resync')}
</button>
}
/>
</div>
</div>
<div className="reactions">
{REACTION_EMOJI.map((emoji) => (
<button
key={emoji}
className="reaction"
onClick={() =>
send({ type: 'watch.reaction', emoji })
}
>
{emoji}
</button>
))}
<div className="emoji-anchor">
<button
className="reaction"
onClick={() => setReactPicker((o) => !o)}
>
<PlusIcon />
</button>
{reactPicker && (
<EmojiPicker
onClose={() => setReactPicker(false)}
onPick={(token) => {
send({
type: 'watch.reaction',
emoji: token,
});
setReactPicker(false);
}}
/>
)}
</div>
</div>
</div>
<div className="card">
<div className="card-head">
<h3>
{t('Up Next')}{' '}
<span className="muted">
{w.queue.length
? `· ${w.queue.length}`
: ''}
</span>
</h3>
<div className="row-gap">
{hasPlayer && (
<button
className={
'btn btn-ghost voteskip' +
(w.skipVoted ? ' on' : '')
}
onClick={voteSkip}
>
{w.skipVotes > 0
? tf(
'Vote skip {0}/{1}',
w.skipVotes,
w.skipNeeded
)
: t('Vote skip')}
</button>
)}
<button
className="btn btn-ghost"
title={t('Host only')}
disabled={!canControl || !w.queue.length}
onClick={() =>
send({ type: 'watch.queue.next' })
}
>
{t('Play next')} <SkipNextIcon />
</button>
</div>
</div>
<WatchSearch disabled={!w.authenticated} />
<div className="tracklist">
{!w.queue.length ? (
<EmptyRow
text={t(
'Nothing queued — paste a URL and hit “+ Queue”'
)}
/>
) : (
w.queue.map((item, i) => (
<div key={i} className="track-row">
<span className="track-num">
{String(i + 1).padStart(2, '0')}
</span>
<div
className="track-cover"
style={
item.thumbnailUrl
? {
background: `url("${item.thumbnailUrl}") center/cover`,
}
: undefined
}
/>
<div className="track-main">
<div className="track-title">
{item.title ||
item.url ||
item.videoId}
</div>
<div className="track-sub">
{[
item.source === 'twitch'
? 'Twitch'
: 'YouTube',
item.addedBy
? tf(
'added by {0}',
item.addedBy
)
: '',
]
.filter(Boolean)
.join(' · ')}
</div>
</div>
{w.authenticated && (
<div className="track-actions">
<button
className="icon-btn danger"
title={t(
'Remove from queue'
)}
onClick={() =>
send({
type: 'watch.queue.remove',
index: i,
})
}
>
<CloseIcon />
</button>
</div>
)}
</div>
))
)}
</div>
</div>
</div>
<div className="col">
<div className="card">
<div className="card-head">
<h3>
{t('In the room')}{' '}
<span className="muted">
· {w.participantCount}
</span>
</h3>
</div>
<div className="people">
{w.participants.map((p) => {
let status = '—';
let color = '#6a6a78';
if (p.buffering) {
status = t('Buffering…');
color = '#ffcf4a';
} else if (
p.offsetMs != null &&
p.offsetMs !== -1
) {
const off = Math.round(p.offsetMs);
status =
Math.abs(off) < 200
? t('In sync')
: `${off > 0 ? '+' : ''}${off}ms`;
color =
Math.abs(off) < 200
? '#5fe094'
: Math.abs(off) > 800
? '#ff9090'
: '#8a8a98';
}
return (
<div key={p.id} className="person">
<Avatar name={p.name} uid={p.uid} />
<div className="person-main">
<div className="person-name">
{p.name}
{p.id === w.selfId
? ` ${t('(you)')}`
: ''}
</div>
{p.host && (
<div className="person-sub">
{t('Host')}
</div>
)}
</div>
{hosting &&
p.id !== w.selfId &&
!p.host && (
<button
className="icon-btn"
title={t('Make host')}
onClick={() =>
transferHost(p.id)
}
>
<CrownIcon />
</button>
)}
<span
className="person-status"
style={{ color }}
>
{status}
</span>
</div>
);
})}
</div>
</div>
<div className="card chat-card">
<div className="card-head">
<h3>{t('Room chat')}</h3>
</div>
<div className="chat-log" ref={chatLogRef}>
{w.chat.map((m, i) => (
<div key={i} className="chat-msg">
<Avatar name={m.name} size={26} />
<div className="chat-body">
<span className="chat-name">
{m.name}
</span>
<span className="chat-time">
{new Date(
m.at
).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
})}
</span>
<div className="chat-text">
{renderChatText(m.text).map(
(part, j) =>
typeof part ===
'string' ? (
<span key={j}>
{part}
</span>
) : (
<img
key={j}
className="emoji-img"
src={`/emoji/${part.emojiName}`}
alt={`:${part.emojiName}:`}
/>
)
)}
</div>
</div>
</div>
))}
</div>
<form
className="chat-row"
onSubmit={(e) => {
e.preventDefault();
const text = chatText.trim();
if (!text) return;
send({ type: 'watch.chat', text });
setChatText('');
}}
>
<div className="emoji-anchor">
<button
type="button"
className="btn btn-ghost emoji-trigger"
onClick={() => setChatPicker((o) => !o)}
>
😊
</button>
{chatPicker && (
<EmojiPicker
onClose={() => setChatPicker(false)}
onPick={(token) => {
setChatText(
(prev) =>
prev +
(token.startsWith(':')
? token
: token)
);
setChatPicker(false);
}}
/>
)}
</div>
<input
value={chatText}
onChange={(e) => setChatText(e.target.value)}
placeholder={t('Say something…')}
autoComplete="off"
maxLength={500}
/>
<button className="btn btn-accent" type="submit">
{t('Send')}
</button>
</form>
</div>
</div>
</div>
</section>
);
}
// The lobby shown when no room is joined (the default). Lists active rooms and
// lets the user join one or create a new room by name.
function WatchLobby(props: {
rooms: ReturnType<typeof watchStore.get>['rooms'];
newRoom: string;
setNewRoom: (v: string) => void;
onRefresh: () => void;
}) {
const { rooms, newRoom, setNewRoom, onRefresh } = props;
useEffect(() => {
onRefresh();
}, [onRefresh]);
return (
<section className="view" id="view-watch">
<div className="card watch-lobby">
<div className="card-head">
<h3>{t('Watch together')}</h3>
<button
className="pill"
title={t('Refresh rooms')}
onClick={() => onRefresh()}
>
<RefreshIcon /> {t('Refresh')}
</button>
</div>
<p className="muted">
{t('Join a room to watch in sync, or create your own.')}
</p>
<div className="rooms-list">
{rooms.length === 0 && (
<span className="muted">
{t('No active rooms yet — create one below.')}
</span>
)}
{rooms.map((r) => (
<button
key={r.name}
className="room-chip"
onClick={() => joinRoom(r.name)}
title={r.nowTitle || undefined}
>
<WatchIcon /> {r.name}
<span className="muted">
{' '}
· {tf('{0} watching', r.participants)}
</span>
{r.nowTitle && (
<span className="room-now muted">
{' '}
· {r.nowTitle}
</span>
)}
</button>
))}
</div>
<form
className="rooms-create"
onSubmit={(e) => {
e.preventDefault();
if (!newRoom.trim()) return;
joinRoom(newRoom);
setNewRoom('');
}}
>
<input
value={newRoom}
onChange={(e) => setNewRoom(e.target.value)}
placeholder={t('New room name…')}
maxLength={48}
/>
<button className="btn btn-accent" type="submit">
{t('Create / join')}
</button>
</form>
</div>
</section>
);
}
+1 -1
View File
@@ -17,9 +17,9 @@ export default defineConfig({
server: {
proxy: {
'/config.json': 'http://127.0.0.1:8080',
'/api': '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
},
+27 -49
View File
@@ -1,12 +1,9 @@
#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>
@@ -14,7 +11,6 @@
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <thread>
#include <unordered_map>
@@ -24,12 +20,10 @@ 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.
// Serves the static browser UI over HTTP 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:
@@ -41,6 +35,10 @@ namespace Echoion::Web
// Explicit RPC URL served to the browser; when empty the UI
// derives ws://<page-host>:<rpcPort>.
std::string rpcUrl;
// External VoidWatch deployment used by the temporary
// /watch redirect and exposed to the browser in
// /config.json.
std::string watchUrl;
uint16_t rpcPort = 8765;
// Server-wide switch for the Now Playing video preview,
// surfaced to the browser via /config.json.
@@ -54,19 +52,10 @@ namespace Echoion::Web
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.
// nullopt yields a 404 and the UI falls back to initials. It may be
// installed before or after start() and survives restarts.
struct AvatarImage {
std::string contentType;
std::string bytes;
@@ -79,15 +68,15 @@ namespace Echoion::Web
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)
struct DashboardSnapshot {
std::string body;
std::string etag;
};
using DashboardProvider = std::function<DashboardSnapshot()>;
void setDashboardProvider(DashboardProvider provider)
{
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
emojiProvider_ = std::move(provider);
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
dashboardProvider_ = std::move(provider);
}
private:
@@ -95,9 +84,8 @@ namespace Echoion::Web
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);
void
handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
// 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
@@ -109,10 +97,6 @@ namespace Echoion::Web
// 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_;
@@ -125,29 +109,23 @@ namespace Echoion::Web
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>>>
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).
// Called from pool threads; guarded so Core can (re)install it at
// any time.
AvatarProvider avatarProvider_;
EmojiProvider emojiProvider_;
std::mutex avatarProviderMutex_;
DashboardProvider dashboardProvider_;
std::mutex dashboardProviderMutex_;
};
} // namespace Echoion::Web
@@ -1,200 +0,0 @@
#pragma once
#include <chrono>
#include <cstdint>
#include <deque>
#include <functional>
#include <map>
#include <mutex>
#include <optional>
#include <set>
#include <string>
#include <unordered_map>
namespace Echoion::Web
{
// Authoritative state for synchronized video watching. This is entirely
// independent of the music bot's playback pipeline: browsers play the video
// locally and the server is only the timing authority for each room.
//
// The manager owns room state and participant membership. It never writes to
// sockets directly -- HttpServer installs a `sender` callback and the manager
// asks it to deliver JSON text to individual connections. That keeps all
// Boost.Beast/socket concerns in HttpServer and makes this unit trivially
// testable.
//
// Roles: the first *authenticated* participant to join a room is its host;
// only the host may load/play/pause/seek and advance the queue, and every
// control message additionally requires authentication (guests can watch,
// chat and react but never manipulate). The host role migrates to another
// authenticated participant when the host leaves. Twitch rooms are live:
// there is no position authority, seek is refused, and everyone simply
// embeds the same channel.
//
// Rooms with a loaded video survive everyone leaving: playback is paused
// in place and the next authenticated joiner becomes host, so a page
// refresh does not wipe the session. Abandoned rooms are pruned after
// kEmptyRoomTtl.
class WatchSessionManager
{
public:
// Delivers one JSON text frame to a single connection id.
using Sender = std::function<void(uint64_t connId,
const std::string& json)>;
// Authenticated identity behind an RPC token. The resolver is
// installed by Core (it owns the token database); the manager
// itself never sees credentials storage.
struct Identity {
std::string uid;
std::string nickname;
bool isAdmin = false;
};
using IdentityResolver =
std::function<std::optional<Identity>(const std::string& token)>;
// Best-effort title lookup for a queued video, so the watch queue
// shows real names server-side instead of relying on the browser.
// Installed by Core (which owns the YouTube metadata stack); when
// unset or it returns nullopt, the client-supplied title (or the
// Twitch channel name) is used. Called on the message thread, so
// it must be quick / cached.
using MetadataResolver = std::function<std::optional<std::string>(
const std::string& source, const std::string& videoId,
const std::string& url)>;
void setSender(Sender sender) { sender_ = std::move(sender); }
void setIdentityResolver(IdentityResolver resolver)
{
identityResolver_ = std::move(resolver);
}
void setMetadataResolver(MetadataResolver resolver)
{
metadataResolver_ = std::move(resolver);
}
// A watch WebSocket connected / disconnected. onDisconnect removes
// the connection from whatever room it had joined and notifies the
// remaining participants.
void onConnect(uint64_t connId);
void onDisconnect(uint64_t connId);
// Handle one inbound JSON message from a connection. Unknown or
// malformed messages are ignored.
void onMessage(uint64_t connId, const std::string& json);
// Broadcast a periodic sync heartbeat (position + participants) to
// every room. HttpServer drives this on a timer so drifting
// clients can re-align.
void broadcastSync();
private:
struct Participant {
std::string name;
// TeamSpeak unique id when authenticated (empty for guests),
// so the web UI can fetch the persisted avatar at /avatar.
std::string uid;
// Set when the join/rename carried a valid RPC token;
// required for any control message and for hosting.
bool authenticated = false;
// Last client-reported playback position and the room
// authority position at that moment (for drift display).
long long reportedMs = -1;
long long authorityMs = -1;
bool buffering = false;
};
struct ChatMessage {
std::string name;
std::string text;
long long timestampMs = 0;
};
// One queued-up video waiting to be watched after the current one.
struct QueueEntry {
std::string source; // youtube|twitch|direct|iframe
std::string url;
std::string videoId;
std::string title; // resolved server-side, best effort
std::string thumbnailUrl; // derived from source + id
std::string addedBy;
};
struct Room {
std::string source = "youtube"; // youtube|twitch|direct|iframe
std::string url;
std::string videoId; // YouTube id / Twitch channel; empty
// for direct & iframe (url carries it)
// Host-reported (watch.embed.caps): the iframe embed answered
// a postMessage handshake, so the room has real position
// authority (seek allowed, position freezes when emptied).
// Reset on every load until the host re-handshakes.
bool controllable = false;
bool paused = true;
// Host-selected playback rate (YouTube only); 1.0 = normal.
double rate = 1.0;
// Host-selected provider media settings. Local-only settings
// (volume, quality, subtitles) never enter room state.
std::map<std::string, std::string> embedControls;
// Position (ms) captured at `anchor`. While playing, the
// live position is positionMs + (now - anchor).
long long positionMs = 0;
std::chrono::steady_clock::time_point anchor{
std::chrono::steady_clock::now()};
uint64_t host = 0;
std::map<uint64_t, Participant> participants;
std::deque<ChatMessage> chat; // last kChatBacklog kept
std::deque<QueueEntry> queue; // up-next, kQueueMax cap
// Connection ids that voted to skip the current video;
// cleared whenever the video changes or a voter leaves.
std::set<uint64_t> skipVotes;
// When the room last had participants; drives pruning of
// empty-but-persisted rooms.
std::chrono::steady_clock::time_point lastActive{
std::chrono::steady_clock::now()};
};
static constexpr size_t kChatBacklog = 50;
static constexpr size_t kQueueMax = 100;
static constexpr size_t kEmbedControlsMax = 16;
static constexpr std::chrono::hours kEmptyRoomTtl{24};
[[nodiscard]] long long livePosition(const Room& room) const;
void send(uint64_t connId, const std::string& json) const;
void broadcast(const Room& room, const std::string& json) const;
void sendParticipants(const Room& room) const;
void sendSnapshot(uint64_t connId, const Room& room) const;
void sendDenied(uint64_t connId, const std::string& reason) const;
void sendQueue(const Room& room, uint64_t onlyTo = 0) const;
// Broadcast the vote-skip tally (votes / needed) for the room.
void sendSkipState(const Room& room) const;
// Votes needed to skip in a room: majority of participants.
[[nodiscard]] static std::size_t skipThreshold(const Room& room);
// Reply to watch.rooms.list with the lobby of active rooms.
void sendRoomsList(uint64_t connId) const;
// Deterministic thumbnail URL for a queued/loaded video.
[[nodiscard]] static std::string
thumbnailFor(const std::string& source,
const std::string& videoId);
// Point the room at a new video (shared by watch.load and
// queue advancement) and broadcast watch.loaded.
void loadIntoRoom(Room& room, const std::string& source,
const std::string& url,
const std::string& channel, uint64_t byConnId);
// First authenticated participant, or 0 when only guests remain.
[[nodiscard]] static uint64_t pickHost(const Room& room);
void leaveCurrentRoom(uint64_t connId);
mutable std::mutex mutex_;
std::unordered_map<std::string, Room> rooms_;
// connId -> room name it currently belongs to.
std::unordered_map<uint64_t, std::string> connRoom_;
Sender sender_;
IdentityResolver identityResolver_;
MetadataResolver metadataResolver_;
};
} // namespace Echoion::Web
+44 -348
View File
@@ -2,10 +2,9 @@
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Net/Http.hpp>
#include <boost/beast/websocket.hpp>
#include <array>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <format>
@@ -15,6 +14,8 @@
namespace Echoion::Web
{
namespace websocket = beast::websocket;
namespace
{
std::string_view contentType(const std::filesystem::path& path)
@@ -91,105 +92,6 @@ namespace Echoion::Web
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,
@@ -237,13 +139,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
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.
@@ -285,23 +181,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
}
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_);
@@ -405,22 +284,7 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
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;
}
@@ -508,35 +372,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
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)
{
@@ -545,7 +380,9 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
auto respond = [&](http::status status, std::string_view type,
std::string body, std::string_view cacheControl = {},
std::string_view lastModified = {}) {
std::string_view lastModified = {},
std::string_view etag = {},
std::string_view location = {}) {
http::response<http::string_body> res{status, req.version()};
res.set(http::field::server, "Echoion");
res.set(http::field::content_type, type);
@@ -555,6 +392,12 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
if (!lastModified.empty()) {
res.set(http::field::last_modified, lastModified);
}
if (!etag.empty()) {
res.set(http::field::etag, etag);
}
if (!location.empty()) {
res.set(http::field::location, location);
}
res.keep_alive(req.keep_alive());
// HEAD advertises the real Content-Length but carries no body.
res.content_length(
@@ -589,10 +432,42 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
{{"rpcUrl", Value{rpcUrl}},
{"rpcPort",
Value{static_cast<long long>(config_.rpcPort)}},
{"watchUrl", Value{config_.watchUrl}},
{"nowPlayingVideo", Value{config_.nowPlayingVideo}}})));
return !ec && req.keep_alive();
}
if (target == "/api/public/dashboard") {
DashboardProvider provider;
{
std::lock_guard<std::mutex> lock(dashboardProviderMutex_);
provider = dashboardProvider_;
}
if (!provider) {
respond(http::status::service_unavailable, "application/json",
R"({"error":"Dashboard snapshot unavailable"})",
"no-cache");
return !ec && req.keep_alive();
}
auto snapshot = provider();
if (auto current = req.find(http::field::if_none_match);
current != req.end() && current->value() == snapshot.etag) {
respond(http::status::not_modified, "application/json", "",
"no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
respond(http::status::ok, "application/json",
std::move(snapshot.body), "no-cache", {}, snapshot.etag);
return !ec && req.keep_alive();
}
if ((target == "/watch" || target == "/watch/") &&
!config_.watchUrl.empty()) {
respond(http::status::temporary_redirect, "text/plain", "",
"no-store", {}, {}, config_.watchUrl);
return !ec && req.keep_alive();
}
// User avatar images, resolved through Core's provider (TeamSpeak
// avatar cache). Best-effort: 404 lets the UI fall back to its
// initial-letter avatars; short private caching keeps reloads cheap
@@ -630,28 +505,6 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
return !ec && req.keep_alive();
}
// 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";
}
@@ -699,161 +552,4 @@ new MutationObserver(()=>{bind();scan()}).observe(document.documentElement,{subt
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
@@ -1,849 +0,0 @@
#include "echoion/web/WatchSession.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <format>
#include <string_view>
namespace Echoion::Web
{
namespace
{
using Void::Json::Value;
long long nowMillis()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
// Extract the YouTube video id from common URL shapes so clients that
// use the iframe player get a bare id. Falls back to the whole string.
std::string videoIdFromUrl(const std::string& url)
{
auto pick = [&](std::string_view marker) -> std::string {
auto pos = url.find(marker);
if (pos == std::string::npos) {
return {};
}
pos += marker.size();
auto end = url.find_first_of("&?#", pos);
return url.substr(pos, end == std::string::npos
? std::string::npos
: end - pos);
};
if (auto id = pick("v="); !id.empty()) {
return id;
}
if (auto id = pick("youtu.be/"); !id.empty()) {
return id;
}
if (auto id = pick("/embed/"); !id.empty()) {
return id;
}
return url;
}
// Twitch channel from a URL or a bare channel name.
std::string twitchChannelFrom(const std::string& input)
{
auto pos = input.find("twitch.tv/");
std::string channel =
pos == std::string::npos
? input
: input.substr(pos + std::string_view("twitch.tv/").size());
if (auto end = channel.find_first_of("/&?#");
end != std::string::npos) {
channel = channel.substr(0, end);
}
return channel;
}
// Canonicalize a client-supplied source to one of the known kinds,
// defaulting anything unrecognized to "youtube".
std::string canonicalSource(const std::string& s)
{
if (s == "twitch" || s == "direct" || s == "iframe") {
return s;
}
return "youtube";
}
// Live sources have no position authority and refuse seeks: Twitch
// streams, and generic embeds (Kodik & co.) unless the host's client
// reported the embed as controllable (watch.embed.caps).
bool isLiveSource(const std::string& s, bool controllable)
{
return s == "twitch" || (s == "iframe" && !controllable);
}
Value embedControlsValue(
const std::map<std::string, std::string>& controls)
{
Value::Object_t object;
for (const auto& [id, value] : controls) {
object.emplace_back(id, Value{value});
}
return Value{std::move(object)};
}
} // namespace
long long WatchSessionManager::livePosition(const Room& room) const
{
if (room.paused) {
return room.positionMs;
}
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - room.anchor)
.count();
return room.positionMs + elapsed;
}
void WatchSessionManager::send(uint64_t connId, const std::string& json) const
{
if (sender_) {
sender_(connId, json);
}
}
void WatchSessionManager::broadcast(const Room& room,
const std::string& json) const
{
for (const auto& [id, participant] : room.participants) {
send(id, json);
}
}
void WatchSessionManager::sendDenied(uint64_t connId,
const std::string& reason) const
{
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.denied"}},
{"reason", Value{reason}}})));
}
void WatchSessionManager::sendParticipants(const Room& room) const
{
Value::Array_t list;
list.reserve(room.participants.size());
for (const auto& [id, p] : room.participants) {
// Drift vs the authority at the time of the client's last report;
// -1 while nothing has been reported yet.
long long offsetMs = -1;
if (p.reportedMs >= 0 && p.authorityMs >= 0) {
offsetMs = p.reportedMs - p.authorityMs;
}
list.emplace_back(Void::Json::object(
{{"id", Value{static_cast<long long>(id)}},
{"name", Value{p.name}},
{"uid", Value{p.uid}},
{"host", Value{id == room.host}},
{"offsetMs", Value{offsetMs}},
{"buffering", Value{p.buffering}}}));
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.participants"}},
{"count", Value{static_cast<long long>(room.participants.size())}},
{"host", Value{static_cast<long long>(room.host)}},
{"participants", Value{std::move(list)}}}));
broadcast(room, msg);
}
void WatchSessionManager::sendQueue(const Room& room, uint64_t onlyTo) const
{
Value::Array_t items;
items.reserve(room.queue.size());
for (const auto& e : room.queue) {
items.emplace_back(Void::Json::object(
{{"source", Value{e.source}},
{"url", Value{e.url}},
{"videoId", Value{e.videoId}},
{"title", Value{e.title}},
{"thumbnailUrl", Value{e.thumbnailUrl}},
{"addedBy", Value{e.addedBy}}}));
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.queue"}},
{"items", Value{std::move(items)}}}));
if (onlyTo != 0) {
send(onlyTo, msg);
} else {
broadcast(room, msg);
}
}
std::string WatchSessionManager::thumbnailFor(const std::string& source,
const std::string& videoId)
{
if (videoId.empty()) {
return {};
}
// Direct/iframe sources carry no deterministic thumbnail.
if (source == "direct" || source == "iframe") {
return {};
}
if (source == "twitch") {
// Twitch's live-preview CDN (undocumented but stable); shows a
// placeholder when the channel is offline.
return std::format(
"https://static-cdn.jtvnw.net/previews-ttv/live_user_{}"
"-320x180.jpg",
videoId);
}
return std::format("https://i.ytimg.com/vi/{}/mqdefault.jpg", videoId);
}
std::size_t WatchSessionManager::skipThreshold(const Room& room)
{
// Majority of current participants (ceil(n/2)); at least one.
const std::size_t n = room.participants.size();
return n == 0 ? 1 : (n / 2) + 1;
}
void WatchSessionManager::sendSkipState(const Room& room) const
{
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.skip.updated"}},
{"votes",
Value{static_cast<long long>(room.skipVotes.size())}},
{"needed",
Value{static_cast<long long>(skipThreshold(room))}}}));
broadcast(room, msg);
}
void WatchSessionManager::sendRoomsList(uint64_t connId) const
{
Value::Array_t list;
for (const auto& [name, room] : rooms_) {
list.emplace_back(Void::Json::object(
{{"name", Value{name}},
{"participants",
Value{static_cast<long long>(room.participants.size())}},
{"source", Value{room.source}},
{"videoId", Value{room.videoId}},
{"nowTitle", Value{room.url}},
{"hasHost", Value{room.host != 0}}}));
}
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.rooms"}},
{"rooms", Value{std::move(list)}}})));
}
uint64_t WatchSessionManager::pickHost(const Room& room)
{
for (const auto& [id, p] : room.participants) {
if (p.authenticated) {
return id;
}
}
return 0;
}
void WatchSessionManager::loadIntoRoom(Room& room, const std::string& source,
const std::string& url,
const std::string& channel,
uint64_t byConnId)
{
room.url = url;
const std::string src = canonicalSource(source);
if (src == "twitch") {
room.source = "twitch";
room.videoId = !channel.empty() ? twitchChannelFrom(channel)
: twitchChannelFrom(url);
room.paused = false; // live — always "playing"
} else if (src == "direct" || src == "iframe") {
// The URL carries the whole media/embed; there is no video id.
// `direct` (HTML5 <video>) is seekable; `iframe` (generic embed)
// is live-like (no position authority).
room.source = src;
room.videoId.clear();
room.paused = false;
} else {
room.source = "youtube";
room.videoId = videoIdFromUrl(url);
// Auto-play on load: the room starts playing immediately rather
// than waiting for someone to press play (the client handles the
// browser autoplay policy by starting muted when needed).
room.paused = false;
}
room.positionMs = 0;
room.anchor = std::chrono::steady_clock::now();
// A new video resets any in-flight skip vote, and any embed capability
// until the host's client re-handshakes with the new embed.
room.skipVotes.clear();
room.controllable = false;
room.embedControls.clear();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"by", Value{static_cast<long long>(byConnId)}}}));
broadcast(room, msg);
sendSkipState(room);
}
void WatchSessionManager::sendSnapshot(uint64_t connId, const Room& room) const
{
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.sync"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"paused", Value{room.paused}},
{"rate", Value{room.rate}},
{"embedControls", embedControlsValue(room.embedControls)},
{"positionMs", Value{livePosition(room)}},
{"serverTimeMs", Value{nowMillis()}},
{"host", Value{static_cast<long long>(room.host)}}}));
send(connId, msg);
}
void WatchSessionManager::onConnect(uint64_t connId)
{
Void::Log::debug("WatchSession", "{}",
std::format("watch connection {} opened", connId));
}
void WatchSessionManager::leaveCurrentRoom(uint64_t connId)
{
auto it = connRoom_.find(connId);
if (it == connRoom_.end()) {
return;
}
auto roomIt = rooms_.find(it->second);
connRoom_.erase(it);
if (roomIt == rooms_.end()) {
return;
}
Room& room = roomIt->second;
room.participants.erase(connId);
room.skipVotes.erase(connId);
if (room.participants.empty()) {
// A room with nothing loaded (no video id and no url) is discarded.
if (room.videoId.empty() && room.url.empty()) {
rooms_.erase(roomIt);
return;
}
// Persist the session: freeze playback where it was so the next
// joiner (who becomes host) resumes in place. Live sources
// (Twitch / generic embeds) have no position to freeze.
room.positionMs = livePosition(room);
if (!isLiveSource(room.source, room.controllable)) {
room.paused = true;
}
room.anchor = std::chrono::steady_clock::now();
room.host = 0;
room.lastActive = std::chrono::steady_clock::now();
return;
}
// Host migration: hand the room to the longest-standing authenticated
// participant; guests never host (host stays vacant until an
// authenticated user joins or signs in).
if (room.host == connId) {
room.host = pickHost(room);
}
sendParticipants(room);
// A departure changes the majority threshold and may complete a
// pending skip; re-broadcast the tally so clients stay accurate.
if (!room.videoId.empty() || !room.url.empty()) {
if (!room.skipVotes.empty() &&
room.skipVotes.size() >= skipThreshold(room)) {
room.skipVotes.clear();
if (!room.queue.empty()) {
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId, 0);
sendQueue(room);
}
} else {
sendSkipState(room);
}
}
}
void WatchSessionManager::onDisconnect(uint64_t connId)
{
std::lock_guard<std::mutex> lock(mutex_);
leaveCurrentRoom(connId);
}
void WatchSessionManager::onMessage(uint64_t connId, const std::string& json)
{
auto parsed = Void::Json::parse(json);
if (!parsed || !parsed->is_object()) {
return;
}
const std::string type = parsed->get_str("type");
if (type.empty()) {
return;
}
std::lock_guard<std::mutex> lock(mutex_);
// A valid RPC token upgrades the participant: server-trusted nickname
// and the right to control playback / host the room.
std::optional<Identity> identity;
if (const std::string token = parsed->get_str("token");
!token.empty() && identityResolver_) {
identity = identityResolver_(token);
}
if (type == "watch.join") {
const std::string roomName = parsed->get_str("room", "main");
std::string name = identity ? identity->nickname
: parsed->get_str("name");
if (name.empty()) {
name = std::format("guest-{}", connId);
}
leaveCurrentRoom(connId);
connRoom_[connId] = roomName;
Room& room = rooms_[roomName];
room.participants[connId] =
Participant{.name = name,
.uid = identity ? identity->uid : std::string{},
.authenticated = identity.has_value()};
if (room.host == 0 && identity) {
room.host = connId;
}
// Ack with the caller's own id so the client can recognize
// itself in participant lists and host announcements.
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.joined"}},
{"selfId", Value{static_cast<long long>(connId)}},
{"authenticated", Value{identity.has_value()}},
{"room", Value{roomName}}})));
sendSnapshot(connId, room);
sendQueue(room, connId);
// Replay the recent chat backlog to the newcomer only.
for (const auto& msg : room.chat) {
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.chat"}},
{"name", Value{msg.name}},
{"text", Value{msg.text}},
{"timestampMs", Value{msg.timestampMs}}})));
}
sendParticipants(room);
sendSkipState(room);
return;
}
// Lobby query: list active rooms. Valid without having joined one.
if (type == "watch.rooms.list") {
sendRoomsList(connId);
return;
}
// Leave the current room and return to the lobby without joining
// another one. leaveCurrentRoom migrates/vacates host and prunes an
// empty room; we then ack and refresh the caller's lobby list.
if (type == "watch.leave") {
leaveCurrentRoom(connId);
send(connId, Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.left"}}})));
sendRoomsList(connId);
return;
}
// All remaining messages act on the caller's current room.
auto roomNameIt = connRoom_.find(connId);
if (roomNameIt == connRoom_.end()) {
return;
}
auto roomIt = rooms_.find(roomNameIt->second);
if (roomIt == rooms_.end()) {
return;
}
Room& room = roomIt->second;
auto selfIt = room.participants.find(connId);
if (selfIt == room.participants.end()) {
return;
}
// Manipulation requires an authenticated participant; playback and
// queue advancement additionally require the host role. Guests only
// watch, chat and react.
const bool isHost = (connId == room.host);
const bool isControl =
(type == "watch.load" || type == "watch.play" ||
type == "watch.pause" || type == "watch.seek" ||
type == "watch.rate" || type == "watch.queue.add" ||
type == "watch.queue.remove" || type == "watch.queue.next" ||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
type == "watch.embed.control");
const bool needsHost =
(type == "watch.load" || type == "watch.play" ||
type == "watch.pause" || type == "watch.seek" ||
type == "watch.rate" || type == "watch.queue.next" ||
type == "watch.host.transfer" || type == "watch.embed.caps" ||
type == "watch.embed.control");
if (isControl && !selfIt->second.authenticated) {
sendDenied(connId, "Sign in to control playback");
return;
}
if (needsHost && !isHost) {
sendDenied(connId, "Only the host controls playback");
return;
}
if (type == "watch.load") {
loadIntoRoom(room, parsed->get_str("source", "youtube"),
parsed->get_str("url"), parsed->get_str("channel"),
connId);
sendSnapshot(connId, room);
} else if (type == "watch.queue.add") {
if (room.queue.size() >= kQueueMax) {
sendDenied(connId, "Watch queue is full");
return;
}
const std::string url = parsed->get_str("url");
if (url.empty()) {
return;
}
QueueEntry entry;
entry.source = canonicalSource(parsed->get_str("source", "youtube"));
entry.url = url;
if (entry.source == "twitch") {
entry.videoId = twitchChannelFrom(url);
} else if (entry.source == "youtube") {
entry.videoId = videoIdFromUrl(url);
} else {
entry.videoId.clear(); // direct/iframe carry the whole url
}
entry.thumbnailUrl = thumbnailFor(entry.source, entry.videoId);
// Title: server-side resolver first (real YouTube titles), then
// the client's best-effort title, then a sensible default (the
// Twitch channel name / the bare video id / the url).
if (metadataResolver_) {
if (auto resolved = metadataResolver_(
entry.source, entry.videoId, entry.url)) {
entry.title = *resolved;
}
}
if (entry.title.empty()) {
entry.title = parsed->get_str("title");
}
if (entry.title.empty()) {
entry.title =
entry.videoId.empty() ? entry.url : entry.videoId;
}
if (entry.title.size() > 200) {
entry.title.resize(200);
}
entry.addedBy = selfIt->second.name;
// Nothing playing yet: start this item immediately instead of
// parking it in the queue.
if (room.videoId.empty() && room.url.empty()) {
loadIntoRoom(room, entry.source, entry.url, entry.videoId,
connId);
return;
}
room.queue.push_back(std::move(entry));
sendQueue(room);
} else if (type == "watch.queue.remove") {
const auto index =
static_cast<long long>(parsed->get_num("index", -1));
if (index < 0 ||
index >= static_cast<long long>(room.queue.size())) {
return;
}
room.queue.erase(room.queue.begin() + index);
sendQueue(room);
} else if (type == "watch.queue.next") {
if (room.queue.empty()) {
// End of playback with nothing queued: clear the current video
// so every client shows the empty placeholder. (The manual
// "Play next" button is disabled when the queue is empty, so
// this is reached only by the auto-advance-on-end path.)
room.videoId.clear();
room.url.clear();
room.paused = true;
room.controllable = false;
room.embedControls.clear();
room.skipVotes.clear();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{std::string{}}},
{"videoId", Value{std::string{}}},
{"controllable", Value{false}},
{"by", Value{static_cast<long long>(connId)}}}));
broadcast(room, msg);
sendSkipState(room);
return;
}
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId, connId);
sendQueue(room);
sendSnapshot(connId, room);
} else if (type == "watch.play") {
room.positionMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: livePosition(room);
room.paused = false;
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.play"}},
{"positionMs", Value{room.positionMs}},
{"serverTimeMs", Value{nowMillis()}}}));
broadcast(room, msg);
} else if (type == "watch.pause") {
room.positionMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: livePosition(room);
room.paused = true;
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.pause"}},
{"positionMs", Value{room.positionMs}}}));
broadcast(room, msg);
} else if (type == "watch.seek") {
if (isLiveSource(room.source, room.controllable)) {
sendDenied(connId, "Live stream — cannot seek");
return;
}
room.positionMs = static_cast<long long>(
parsed->get_num("positionMs"));
room.anchor = std::chrono::steady_clock::now();
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.seek"}},
{"positionMs", Value{room.positionMs}},
{"serverTimeMs", Value{nowMillis()}}}));
broadcast(room, msg);
} else if (type == "watch.rate") {
// Host sets the shared playback rate (YouTube only). Clamp to the
// values the YouTube player accepts.
double rate = parsed->get_num("rate", 1.0);
if (rate < 0.25) {
rate = 0.25;
}
if (rate > 2.0) {
rate = 2.0;
}
room.rate = rate;
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.rate"}}, {"rate", Value{room.rate}}}));
broadcast(room, msg);
} else if (type == "watch.embed.control") {
if (room.source != "iframe") {
return;
}
const std::string id = parsed->get_str("id");
const std::string value = parsed->get_str("value");
if (id.empty() || id.size() > 32 || value.size() > 200 ||
id.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_") !=
std::string::npos) {
return;
}
const bool syncedControl =
id == "audiotrack" || id == "episode" || id == "playlist" ||
id == "playlist-next" || id == "playlist-prev" ||
id == "translation";
if (!syncedControl) {
return;
}
if (!room.embedControls.contains(id) &&
room.embedControls.size() >= kEmbedControlsMax) {
return;
}
room.embedControls[id] = value;
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.embed.control"}},
{"id", Value{id}},
{"value", Value{value}}}));
broadcast(room, msg);
} else if (type == "watch.embed.caps") {
// Host's client reports whether the loaded iframe embed answered
// the postMessage handshake; flips the room between view-only
// live and fully seekable. Meaningless for other sources.
if (room.source != "iframe") {
return;
}
const bool controllable = parsed->get_bool("controllable", false);
if (room.controllable == controllable) {
return;
}
room.controllable = controllable;
// Snapshot everyone immediately so timelines flip without waiting
// for the 3s heartbeat.
for (const auto& [pid, p] : room.participants) {
sendSnapshot(pid, room);
}
} else if (type == "watch.state") {
sendSnapshot(connId, room);
} else if (type == "watch.host.transfer") {
// Host hands control to another authenticated participant.
const auto targetId =
static_cast<uint64_t>(parsed->get_num("targetId", 0));
auto targetIt = room.participants.find(targetId);
if (targetIt == room.participants.end()) {
sendDenied(connId, "That viewer is no longer here");
return;
}
if (!targetIt->second.authenticated) {
sendDenied(connId, "Only signed-in viewers can host");
return;
}
room.host = targetId;
sendParticipants(room);
} else if (type == "watch.skip.vote") {
// Any participant may vote to skip the current video; a majority
// advances the queue (or clears the video when the queue is
// empty). Toggling removes the vote.
if (room.videoId.empty() && room.url.empty()) {
return;
}
if (room.skipVotes.count(connId)) {
room.skipVotes.erase(connId);
} else {
room.skipVotes.insert(connId);
}
if (room.skipVotes.size() >= skipThreshold(room)) {
room.skipVotes.clear();
if (!room.queue.empty()) {
QueueEntry next = std::move(room.queue.front());
room.queue.pop_front();
loadIntoRoom(room, next.source, next.url, next.videoId,
connId);
sendQueue(room);
} else {
// Nothing queued: clear the current video.
room.videoId.clear();
room.url.clear();
room.paused = true;
const std::string msg =
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.loaded"}},
{"source", Value{room.source}},
{"url", Value{std::string{}}},
{"videoId", Value{std::string{}}},
{"by", Value{static_cast<long long>(connId)}}}));
broadcast(room, msg);
sendSkipState(room);
}
} else {
sendSkipState(room);
}
} else if (type == "watch.rename") {
// In-place rename (e.g. the user authenticated after joining);
// keeps chat history. A valid token upgrades the participant to
// authenticated and lets them claim a vacant host slot.
std::string name = identity ? identity->nickname
: parsed->get_str("name");
if (name.empty() || name.size() > 64) {
return;
}
selfIt->second.name = name;
if (identity) {
selfIt->second.authenticated = true;
selfIt->second.uid = identity->uid;
if (room.host == 0) {
room.host = connId;
}
}
// Re-ack so the client sees its (possibly upgraded) standing.
send(connId,
Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.joined"}},
{"selfId", Value{static_cast<long long>(connId)}},
{"authenticated",
Value{selfIt->second.authenticated}},
{"room", Value{roomNameIt->second}}})));
sendParticipants(room);
} else if (type == "watch.report") {
// Client progress report (drift display; no authority change).
auto pIt = room.participants.find(connId);
if (pIt == room.participants.end()) {
return;
}
pIt->second.reportedMs = parsed->has("positionMs")
? static_cast<long long>(
parsed->get_num("positionMs"))
: -1;
pIt->second.authorityMs = livePosition(room);
pIt->second.buffering = parsed->get_bool("buffering", false);
} else if (type == "watch.chat") {
const std::string text = parsed->get_str("text");
if (text.empty() || text.size() > 500) {
return;
}
auto pIt = room.participants.find(connId);
const std::string name = pIt != room.participants.end()
? pIt->second.name
: std::format("guest-{}", connId);
room.chat.push_back(ChatMessage{
.name = name, .text = text, .timestampMs = nowMillis()});
while (room.chat.size() > kChatBacklog) {
room.chat.pop_front();
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.chat"}},
{"name", Value{name}},
{"text", Value{text}},
{"timestampMs", Value{room.chat.back().timestampMs}}}));
broadcast(room, msg);
} else if (type == "watch.reaction") {
// Unicode emoji (a few bytes) or a :custom-emoji: shortcode.
const std::string emoji = parsed->get_str("emoji");
if (emoji.empty() || emoji.size() > 48) {
return;
}
auto pIt = room.participants.find(connId);
const std::string name = pIt != room.participants.end()
? pIt->second.name
: std::format("guest-{}", connId);
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.reaction"}},
{"name", Value{name}},
{"emoji", Value{emoji}}}));
broadcast(room, msg);
}
}
void WatchSessionManager::broadcastSync()
{
std::lock_guard<std::mutex> lock(mutex_);
// Prune persisted-but-abandoned rooms that nobody rejoined.
const auto now = std::chrono::steady_clock::now();
for (auto it = rooms_.begin(); it != rooms_.end();) {
if (it->second.participants.empty() &&
now - it->second.lastActive > kEmptyRoomTtl) {
it = rooms_.erase(it);
} else {
++it;
}
}
for (const auto& [name, room] : rooms_) {
if (room.participants.empty()) {
continue;
}
const std::string msg = Void::Json::serialize(Void::Json::object(
{{"type", Value{"watch.sync"}},
{"source", Value{room.source}},
{"url", Value{room.url}},
{"videoId", Value{room.videoId}},
{"controllable", Value{room.controllable}},
{"paused", Value{room.paused}},
{"rate", Value{room.rate}},
{"embedControls", embedControlsValue(room.embedControls)},
{"positionMs", Value{livePosition(room)}},
{"serverTimeMs", Value{nowMillis()}},
{"host", Value{static_cast<long long>(room.host)}}}));
broadcast(room, msg);
// Participants ride the same 3s heartbeat so drift/buffering
// badges stay fresh without per-report broadcasts.
sendParticipants(room);
}
}
} // namespace Echoion::Web
+19 -9
View File
@@ -14,14 +14,16 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist supp
- ⭐ **History & Favorites** - `!history`, `!stats`, `!fav add|list|play` backed by SQLite
- 📋 **Playlist Support** - Queue management with shuffle, repeat, and skip functionality
- 🎧 **High Quality Audio** - 192kHz stereo internal pipeline
- 🎚️ **Named Listening Rooms** - Independent queues and playback engines can
whisper different music to different user groups simultaneously
- 🔄 **Transactional Updates** - Validate a complete daemon/Core/protocol
release, checkpoint every room, re-exec, reconnect, and restore playback
release, checkpoint playback, re-exec, reconnect, and restore playback
- ⚙️ **Configurable** - JSON-based configuration system
- 🔊 **TeamSpeak Native** - Uses TeamSpeak's native audio system for best quality
- 🧩 **VoidTeamspeak SDK** - Native protocol support is an independently
consumable modern C++ library rather than an Echoion-internal component
- 🌐 **Public Dashboard** - Current playback plus the complete sanitized
TeamSpeak channel/client tree, with authenticated administration for admins
- 🎬 **VoidWatch Link** - Watch Together is deployed independently from the
`EchoionWatch` repository and linked through `web.watchUrl`
## Building
@@ -132,9 +134,14 @@ The supported runtime consists of four main components:
3. **VoidTeamspeak** - Reusable native TeamSpeak SDK-compatible client library
4. **EchoionStandalone** - Daemon host and Core API adapter
`EchoionPlugin` is archived compatibility code. It is excluded from normal
builds and packages; use `-DBUILD_PLUGIN=ON` only when maintaining the legacy
TeamSpeak client integration.
The legacy TeamSpeak client plugin was removed. TeamSpeak protocol behavior is
implemented once in `VoidTeamspeak`; `EchoionStandalone` is Echoion's only host
adapter.
Watch Together is the independent **VoidWatch** product in the sibling
`EchoionWatch` repository. Echoion has no Watch runtime, WebSocket session,
provider resolver, or extra TeamSpeak identity; it only exposes the configured
external link and a temporary `/watch` redirect.
### Audio Flow
@@ -145,8 +152,8 @@ query → SourceRouter (innertube → Yandex → direct URL → yt-dlp) → Play
```
Audio is decoded using FFmpeg at 192kHz stereo and emitted in 20ms chunks to
TeamSpeak's Opus voice protocol by a single real-time engine thread. See
`docs/09-audio-pipeline.md` for details.
TeamSpeak's Opus voice protocol through the bot's single playback engine and
visible TeamSpeak identity.
## Development
@@ -168,7 +175,7 @@ scripts/stage-release.sh "$HOME/echoion/releases" 1.2.3 \
The staging command rejects unsafe version names and existing release
directories, copies complete artifacts first, calculates SHA-256 hashes, then
renames `pending-release.json` into place. The running daemon validates it in a
child process, checkpoints Core and room state, disconnects cleanly, and
child process, checkpoints Core state, disconnects cleanly, and
re-execs the staged binary.
### Adding Commands
@@ -192,6 +199,9 @@ public:
};
```
For independently reloadable native extensions, use the trusted plugin ABI
instead of compiling commands into Core. See [Native plugins](docs/plugins.md).
## Packaging and Distribution
### Using CPack
+7 -7
View File
@@ -1,6 +1,6 @@
# VoidLibrary — work needed to fully migrate Echoion (+ upgrade ideas)
## STATUS (round 2 complete)
## STATUS (migration complete)
Almost everything below has now landed. Echoion uses Void for **Json, Logging,
Process, Retry, Configuration, EventBus (async), ThreadPool, Cache, Resilience,
@@ -20,11 +20,11 @@ implemented in VoidLibrary as universal primitives and consumed by Echoion:
- **A6 done** — `Void::BufferPool::BufferPool<T>` added; AudioBufferPool wraps it;
bespoke MemoryPool deleted. New `Void::System` metrics (process_memory/cpu) added.
**Remaining (one item):** the plugin loader is still Echoion's dylib-based
`CoreLoader`, not `Void::Plugin`. This is **not** a Void gap — it's an
Echoion-side rewrite gated on a live hot-reload test (impedance mismatch: Core
implements `ICoreInterface`, `Void::Plugin::Loader` hands back `IPlugin*`). See
section B.
**Remaining:** none from the migration list. `CoreLoader` now uses
`Void::Plugin::PluginManager` with pinned handles, host-side interface
validation, explicit activation readiness, state checkpoint/restore, and
rollback to a reactivated previous Core. Successful and rejected replacement
paths are covered by an end-to-end reload test.
The historical analysis below is retained for reference.
@@ -111,7 +111,7 @@ high-water stats), or confirm `Pool<std::vector<int16_t>>` is an acceptable fit.
## B. Already replaceable — no VoidLibrary change needed (Echoion-side work only)
- **Plugin loader → `Void::Plugin`.** `Loader::reload()` + `Manager` (FileWatcher,
- **Plugin loader → `Void::Plugin` (done).** `Loader::reload()` + `Manager` (FileWatcher,
RCU-pinned handles so "work never stops for a reload") + the v2
`serialize_state`/`deserialize_state` C-ABI protocol already cover — and improve
on — Echoion's `CoreLoader`/dylib/`FileWatcher`. The "defer reload until the
+3 -1
View File
@@ -49,7 +49,7 @@
},
"web": {
"_section": "Browser web interface (EchoionWeb): serves the UI, the sync-watch WebSocket (/ws), and bridges browser RPC through /rpc — only this port needs to be reachable; the RPC server can stay on 127.0.0.1.",
"_section": "Browser web interface (EchoionWeb): serves the public dashboard and bridges authenticated browser RPC through /rpc — only this port needs to be reachable; the RPC server can stay on 127.0.0.1.",
"enabled": false,
"port": 8080,
"_bindAddress": "Use 0.0.0.0 to allow access from other machines.",
@@ -59,6 +59,8 @@
"rpcUrl": "",
"_publicUrl": "Public address users reach the web interface at, e.g. https://bot.example.com. When set (and the web interface is enabled), !help links to it.",
"publicUrl": "",
"_watchUrl": "External VoidWatch deployment linked from Echoion. The retired /watch path redirects here when set.",
"watchUrl": "",
"_nowPlayingVideo": "Allow the Now Playing view to show the current song's video (muted, synced). Users can still disable it locally; set false to turn it off for everyone.",
"nowPlayingVideo": true
},
-149
View File
@@ -1,149 +0,0 @@
#!/bin/bash
# Debug script for TeamSpeak Echoion service issues
set -e
USER_NAME="${USER_NAME:-bot}"
RDP_PORT="${RDP_PORT:-3390}"
echo "TeamSpeak Echoion - Diagnostic Tool"
echo "=================================="
echo ""
# Check user
echo "1. Checking user..."
echo " Current user: $(whoami)"
echo " Target user: $USER_NAME"
if [ "$(whoami)" != "$USER_NAME" ]; then
echo " ⚠️ Warning: Running as different user"
fi
echo ""
# Check environment
echo "2. Checking environment..."
echo " XDG_RUNTIME_DIR: ${XDG_RUNTIME_DIR:-not set}"
echo " HOME: ${HOME:-not set}"
echo " USER: ${USER:-not set}"
echo " DBUS_SESSION_BUS_ADDRESS: ${DBUS_SESSION_BUS_ADDRESS:-not set}"
echo ""
# Check directories
echo "3. Checking directories..."
TS3_DIR="/home/$USER_NAME/TeamSpeak3-Client-linux_amd64"
if [ -d "$TS3_DIR" ]; then
echo " ✓ TeamSpeak dir: $TS3_DIR"
ls -la "$TS3_DIR" | head -5
else
echo " ✗ TeamSpeak dir not found: $TS3_DIR"
fi
echo ""
# Check certificates
echo "4. Checking certificates..."
CERT_FILE="/home/$USER_NAME/.config/EchoionTsBot.crt"
KEY_FILE="/home/$USER_NAME/.config/EchoionTsBot.key"
if [ -f "$CERT_FILE" ]; then
echo " ✓ Certificate: $CERT_FILE"
ls -la "$CERT_FILE"
else
echo " ✗ Certificate not found: $CERT_FILE"
fi
if [ -f "$KEY_FILE" ]; then
echo " ✓ Key: $KEY_FILE"
ls -la "$KEY_FILE"
else
echo " ✗ Key not found: $KEY_FILE"
fi
echo ""
# Check port
echo "5. Checking port $RDP_PORT..."
if ss -tlnp | grep -q ":$RDP_PORT "; then
echo " ✗ Port $RDP_PORT is in use:"
ss -tlnp | grep ":$RDP_PORT "
else
echo " ✓ Port $RDP_PORT is available"
fi
echo ""
# Check weston
echo "6. Checking weston..."
if command -v weston &> /dev/null; then
echo " ✓ Weston found: $(which weston)"
weston --version 2>/dev/null || echo " Version: unknown"
else
echo " ✗ Weston not found"
fi
echo ""
# Check dbus
echo "7. Checking dbus..."
if command -v dbus-run-session &> /dev/null; then
echo " ✓ dbus-run-session found: $(which dbus-run-session)"
else
echo " ✗ dbus-run-session not found"
fi
echo ""
# Check capabilities
echo "8. Checking capabilities..."
if command -v getcap &> /dev/null; then
WESTON_BIN=$(which weston 2>/dev/null || echo "")
if [ -n "$WESTON_BIN" ]; then
getcap "$WESTON_BIN" 2>/dev/null || echo " No special capabilities"
fi
else
echo " getcap not available"
fi
echo ""
# Check systemd
echo "9. Checking systemd..."
if systemctl --user is-system-running &>/dev/null; then
echo " ✓ Systemd user session is running"
else
echo " ⚠️ Systemd user session not available (this is OK)"
fi
echo ""
# Check runtime directory
echo "10. Checking runtime directory..."
RUNTIME_DIR="/tmp/.ts3bot-display-$USER_NAME"
if [ -d "$RUNTIME_DIR" ]; then
echo " ✓ Runtime dir exists: $RUNTIME_DIR"
ls -la "$RUNTIME_DIR"
else
echo " Runtime dir doesn't exist (will be created): $RUNTIME_DIR"
fi
echo ""
# Test weston directly
echo "11. Testing weston startup..."
echo " Attempting to start weston for 2 seconds..."
TEST_DIR="/tmp/.weston-test-$$"
mkdir -p "$TEST_DIR"
chmod 700 "$TEST_DIR"
export XDG_RUNTIME_DIR="$TEST_DIR"
timeout 2 dbus-run-session -- weston --backend=rdp --rdp-port=3391 2>&1 | head -20 || true
rm -rf "$TEST_DIR"
echo ""
echo "Diagnostic complete!"
echo ""
echo "Common issues and solutions:"
echo ""
echo "1. If weston fails to bind to port:"
echo " - Try a different port: export RDP_PORT=3391"
echo " - Check if another process is using the port"
echo ""
echo "2. If certificates are not found:"
echo " Generate them with:"
echo " openssl req -x509 -newkey rsa:4096 -keyout ~/.config/EchoionTsBot.key -out ~/.config/EchoionTsBot.crt -days 365 -nodes"
echo ""
echo "3. If systemd user session is not available:"
echo " - Use system service instead: sudo ~/echoion/scripts/install-service.sh system"
echo " - Or start manually: ~/echoion/scripts/run-teamspeak-headless.sh"
echo ""
echo "4. To test weston directly:"
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
-191
View File
@@ -1,191 +0,0 @@
#!/bin/bash
# Installation script for TeamSpeak Echoion systemd service
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
USER_NAME="${USER_NAME:-bot}"
INSTALL_TYPE="${1:-user}" # 'user' or 'system'
echo -e "${GREEN}TeamSpeak Echoion Bot - Service Installer${NC}"
echo "=========================================="
echo ""
# Show usage for user without proper session
if [ "$INSTALL_TYPE" == "user" ] && [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
echo -e "${YELLOW}Note: Running without a full user session${NC}"
echo "This is OK - the script will install the service files."
echo "You may need to manually reload systemd after installation."
echo ""
fi
# Check if running as root for system install
if [ "$INSTALL_TYPE" == "system" ] && [ "$EUID" -ne 0 ]; then
echo -e "${RED}Error: System installation requires root privileges${NC}"
echo "Run: sudo $0 system"
exit 1
fi
# Check if user is correct
if [ "$INSTALL_TYPE" == "user" ] && [ "$(whoami)" != "$USER_NAME" ]; then
echo -e "${YELLOW}Warning: You are running as '$(whoami)' but USER_NAME is set to '$USER_NAME'${NC}"
echo "This is OK if you're installing for another user."
echo "To install for current user, run: USER_NAME=$(whoami) $0"
echo ""
read -p "Continue anyway? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
exit 1
fi
fi
# Verify bot user exists
if ! id "$USER_NAME" &>/dev/null; then
echo -e "${RED}Error: User '$USER_NAME' does not exist${NC}"
echo "Create the user first: sudo useradd -m -s /bin/bash $USER_NAME"
exit 1
fi
echo "Installation type: $INSTALL_TYPE"
echo "Bot user: $USER_NAME"
echo ""
# Check prerequisites
echo -e "${YELLOW}Checking prerequisites...${NC}"
# Check if weston is installed
if ! command -v weston &> /dev/null; then
echo -e "${RED}Error: weston is not installed${NC}"
echo "Install it with: sudo pacman -S weston"
exit 1
fi
# Check if dbus-run-session is available
if ! command -v dbus-run-session &> /dev/null; then
echo -e "${RED}Error: dbus-run-session is not available${NC}"
echo "Install it with: sudo pacman -S dbus"
exit 1
fi
# Check TeamSpeak directory
TS3_DIR="/home/$USER_NAME/TeamSpeak3-Client-linux_amd64"
if [ ! -d "$TS3_DIR" ]; then
echo -e "${YELLOW}Warning: TeamSpeak directory not found at: $TS3_DIR${NC}"
echo "Make sure to install TeamSpeak client there before starting the service"
fi
# Check certificates
CERT_FILE="/home/$USER_NAME/.config/EchoionTsBot.crt"
KEY_FILE="/home/$USER_NAME/.config/EchoionTsBot.key"
if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
echo -e "${YELLOW}Warning: TLS certificates not found${NC}"
echo " Cert: $CERT_FILE"
echo " Key: $KEY_FILE"
echo "You can generate self-signed certificates with:"
echo " openssl req -x509 -newkey rsa:4096 -keyout $KEY_FILE -out $CERT_FILE -days 365 -nodes"
fi
echo -e "${GREEN}Prerequisites check passed!${NC}"
echo ""
# Copy wrapper script
echo -e "${YELLOW}Installing wrapper script...${NC}"
mkdir -p "/home/$USER_NAME/echoion/scripts"
cp "$SCRIPT_DIR/../scripts/run-teamspeak-headless.sh" "/home/$USER_NAME/echoion/scripts/"
chown -R "$USER_NAME:$USER_NAME" "/home/$USER_NAME/echoion"
chmod +x "/home/$USER_NAME/echoion/scripts/run-teamspeak-headless.sh"
echo -e "${GREEN}Wrapper script installed${NC}"
echo ""
# Function to check if we have a working user systemd session
has_user_systemd_session() {
local user="$1"
# Check if we can communicate with the user systemd
if sudo -u "$user" systemctl --user --quiet is-system-running 2>/dev/null || \
sudo -u "$user" systemctl --user daemon-reload 2>/dev/null; then
return 0
fi
return 1
}
# Install systemd service
if [ "$INSTALL_TYPE" == "system" ]; then
echo -e "${YELLOW}Installing system service...${NC}"
cp "$SCRIPT_DIR/../systemd/teamspeak-echoion.service" /etc/systemd/system/
# Update user in service file
sed -i "s/User=bot/User=$USER_NAME/g" /etc/systemd/system/teamspeak-echoion.service
sed -i "s/Group=bot/Group=$USER_NAME/g" /etc/systemd/system/teamspeak-echoion.service
sed -i "s|/home/bot|/home/$USER_NAME|g" /etc/systemd/system/teamspeak-echoion.service
systemctl daemon-reload
echo -e "${GREEN}System service installed${NC}"
echo ""
echo "To start the service:"
echo " sudo systemctl start teamspeak-echoion"
echo ""
echo "To enable on boot:"
echo " sudo systemctl enable teamspeak-echoion"
echo ""
echo "To check status:"
echo " sudo systemctl status teamspeak-echoion"
else
echo -e "${YELLOW}Installing user service...${NC}"
# Create user systemd directory
sudo -u "$USER_NAME" mkdir -p "/home/$USER_NAME/.config/systemd/user"
# Copy service file
cp "$SCRIPT_DIR/../systemd/teamspeak-echoion-user.service" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
# Update paths in service file
sed -i "s|/home/bot|/home/$USER_NAME|g" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
chown "$USER_NAME:$USER_NAME" "/home/$USER_NAME/.config/systemd/user/teamspeak-echoion.service"
# Try to reload user systemd, but don't fail if not in a session
echo -e "${YELLOW}Attempting to reload systemd user daemon...${NC}"
if has_user_systemd_session "$USER_NAME"; then
echo -e "${GREEN}Systemd user session found, reloading daemon${NC}"
sudo -u "$USER_NAME" systemctl --user daemon-reload
echo ""
echo "To start the service:"
echo " systemctl --user start teamspeak-echoion"
echo ""
echo "To enable on login:"
echo " systemctl --user enable teamspeak-echoion"
echo ""
echo "To check status:"
echo " systemctl --user status teamspeak-echoion"
else
echo -e "${YELLOW}Note: No active systemd user session detected${NC}"
echo "This is normal when running via SSH without X11 or from a minimal shell"
echo ""
echo "The service file has been installed. To complete setup, run these commands"
echo "from a proper user session (e.g., after logging in via SSH with a PTY):"
echo ""
echo " systemctl --user daemon-reload"
echo " systemctl --user start teamspeak-echoion"
echo " systemctl --user enable teamspeak-echoion"
echo ""
echo "Or start it manually with:"
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
fi
echo ""
echo "To enable lingering (start on boot without login):"
echo " sudo loginctl enable-linger $USER_NAME"
fi
echo ""
echo -e "${GREEN}Installation complete!${NC}"
echo ""
echo "View logs with:"
if [ "$INSTALL_TYPE" == "system" ]; then
echo " sudo journalctl -u teamspeak-echoion -f"
else
echo " sudo -u $USER_NAME journalctl --user -u teamspeak-echoion -f"
fi
-83
View File
@@ -1,83 +0,0 @@
#!/bin/bash
# TeamSpeak 3 Headless Runner with Echoion Bot
# This script sets up the environment and starts TeamSpeak with Weston compositor
set -e
# Configuration
USER_NAME="${USER_NAME:-bot}"
HOME_DIR="/home/${USER_NAME}"
TS3_DIR="${HOME_DIR}/TeamSpeak3-Client-linux_amd64"
CONFIG_DIR="${HOME_DIR}/.config"
RUNTIME_DIR="/tmp/.ts3bot-display-${USER_NAME}"
CERT_FILE="${CONFIG_DIR}/EchoionTsBot.crt"
KEY_FILE="${CONFIG_DIR}/EchoionTsBot.key"
RDP_PORT="${RDP_PORT:-3390}"
# Check if running as root
if [ "$EUID" -eq 0 ]; then
echo "Please do not run this script as root"
echo "Run as the bot user: sudo -u ${USER_NAME} $0"
exit 1
fi
# Create runtime directory
mkdir -p "${RUNTIME_DIR}"
chmod 700 "${RUNTIME_DIR}"
# Export environment variables
export XDG_RUNTIME_DIR="${RUNTIME_DIR}"
export HOME="${HOME_DIR}"
export USER="${USER_NAME}"
# Check if port is already in use
if ss -tlnp | grep -q ":${RDP_PORT} "; then
echo "Error: Port ${RDP_PORT} is already in use"
echo "Choose a different port by setting RDP_PORT environment variable"
echo "Example: RDP_PORT=3391 $0"
exit 1
fi
# Check if certificates exist and have correct permissions
if [ ! -f "${CERT_FILE}" ] || [ ! -f "${KEY_FILE}" ]; then
echo "Warning: TLS certificates not found at:"
echo " Cert: ${CERT_FILE}"
echo " Key: ${KEY_FILE}"
echo "RDP connections may not work without certificates"
sleep 2
else
# Check permissions - key should be readable by user
if [ ! -r "${KEY_FILE}" ]; then
echo "Error: Cannot read key file: ${KEY_FILE}"
echo "Fix permissions: chmod 600 ${KEY_FILE}"
exit 1
fi
fi
# Check if TeamSpeak directory exists
if [ ! -d "${TS3_DIR}" ]; then
echo "Error: TeamSpeak directory not found at: ${TS3_DIR}"
exit 1
fi
cd "${TS3_DIR}"
echo "Starting TeamSpeak 3 with Echoion Bot..."
echo " User: ${USER_NAME}"
echo " Runtime Dir: ${RUNTIME_DIR}"
echo " Weston Backend: RDP"
echo " RDP Port: ${RDP_PORT}"
echo " TLS Cert: ${CERT_FILE}"
echo ""
# Start dbus-run-session with weston and TeamSpeak
# Using explicit IP binding and port
exec dbus-run-session -- \
weston \
--backend=rdp \
--xwayland \
--rdp-tls-cert="${CERT_FILE}" \
--rdp-tls-key="${KEY_FILE}" \
--rdp-address=0.0.0.0 \
--rdp-port=${RDP_PORT} \
-- ./ts3client_runscript.sh "$@"
-85
View File
@@ -1,85 +0,0 @@
#!/bin/bash
# Quick start script for TeamSpeak Echoion when systemd user session is not available
# This script can be used as a fallback when systemctl --user doesn't work
set -e
USER_NAME="${USER_NAME:-$(whoami)}"
SERVICE_NAME="teamspeak-echoion"
echo "TeamSpeak Echoion - Quick Start"
echo "==============================="
echo ""
# Check if we're in a systemd user session
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] || [ -z "$XDG_RUNTIME_DIR" ]; then
echo "No systemd user session detected."
echo ""
echo "You have three options:"
echo ""
echo "1. Start via systemd (requires session bus - see below)"
echo "2. Start manually with the wrapper script"
echo "3. Use a tmux/screen session"
echo ""
echo -e "\033[1;33mOption 1: Using systemd (recommended for production)\033[0m"
echo " First, start a proper user session:"
echo " - Log in via SSH with a pseudo-terminal: ssh -t user@host bash"
echo " - Or enable lingering and reboot:"
echo " sudo loginctl enable-linger $USER_NAME"
echo " Then:"
echo " systemctl --user daemon-reload"
echo " systemctl --user start $SERVICE_NAME"
echo ""
echo -e "\033[1;33mOption 2: Manual start (for testing)\033[0m"
echo " ~/echoion/scripts/run-teamspeak-headless.sh"
echo ""
echo -e "\033[1;33mOption 3: Using tmux\033[0m"
echo " tmux new-session -d -s teamspeak '~/echoion/scripts/run-teamspeak-headless.sh'"
echo " tmux attach -t teamspeak"
echo ""
read -p "Would you like to start manually now? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "Starting TeamSpeak..."
exec ~/echoion/scripts/run-teamspeak-headless.sh
else
exit 0
fi
else
# We have a session, try systemd
echo "Systemd user session detected!"
echo ""
# Check if service file exists
if [ ! -f "$HOME/.config/systemd/user/$SERVICE_NAME.service" ]; then
echo "Service file not found. Please run the install script first:"
echo " ~/echoion/scripts/install-service.sh user"
exit 1
fi
# Check if service is running
if systemctl --user is-active --quiet $SERVICE_NAME; then
echo "Service is already running!"
echo "View status: systemctl --user status $SERVICE_NAME"
echo "View logs: journalctl --user -u $SERVICE_NAME -f"
else
echo "Starting service..."
systemctl --user daemon-reload
systemctl --user start $SERVICE_NAME
sleep 2
if systemctl --user is-active --quiet $SERVICE_NAME; then
echo -e "\033[0;32mService started successfully!\033[0m"
echo ""
echo "Status: systemctl --user status $SERVICE_NAME"
echo "Logs: journalctl --user -u $SERVICE_NAME -f"
echo "Stop: systemctl --user stop $SERVICE_NAME"
else
echo -e "\033[0;31mService failed to start. Check logs:\033[0m"
echo "journalctl --user -u $SERVICE_NAME --no-pager -n 50"
exit 1
fi
fi
fi
-66
View File
@@ -1,66 +0,0 @@
#!/bin/bash
# Alternative start script using tmux for persistence
# This is useful when systemd user session is not available
set -e
USER_NAME="${USER_NAME:-$(whoami)}"
SESSION_NAME="teamspeak-echoion"
echo "TeamSpeak Echoion - Tmux Session Starter"
echo "========================================"
echo ""
# Check if tmux is installed
if ! command -v tmux &> /dev/null; then
echo "Error: tmux is not installed"
echo "Install it with: sudo pacman -S tmux"
exit 1
fi
# Check if session already exists
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Session '$SESSION_NAME' already exists!"
echo ""
echo "Options:"
echo " 1. Attach to existing session: tmux attach -t $SESSION_NAME"
echo " 2. Kill existing session: tmux kill-session -t $SESSION_NAME"
echo " 3. View logs: tmux capture-pane -t $SESSION_NAME -p | tail -50"
echo ""
read -p "Kill existing session and start new? (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
tmux kill-session -t "$SESSION_NAME"
echo "Killed existing session"
else
echo "Exiting..."
exit 0
fi
fi
echo "Starting new tmux session: $SESSION_NAME"
echo ""
# Create new detached session
tmux new-session -d -s "$SESSION_NAME" -n "teamspeak" "bash -c 'cd ~ && echo \"Starting TeamSpeak Echoion...\" && ~/echoion/scripts/run-teamspeak-headless.sh'"
# Optional: Create additional windows for monitoring
tmux new-window -t "$SESSION_NAME" -n "logs" "bash -c 'echo \"Waiting for logs...\" && sleep 5 && journalctl --user -u teamspeak-echoion -f 2>/dev/null || tail -f /tmp/.ts3bot-display-$USER_NAME/*.log 2>/dev/null || echo \"No logs available\"'"
echo -e "\033[0;32mTmux session started successfully!\033[0m"
echo ""
echo "To attach to the session:"
echo " tmux attach -t $SESSION_NAME"
echo ""
echo "To view logs without attaching:"
echo " tmux capture-pane -t $SESSION_NAME:0 -p"
echo ""
echo "To detach from session (when attached):"
echo " Press Ctrl+B then D"
echo ""
echo "To kill the session:"
echo " tmux kill-session -t $SESSION_NAME"
echo ""
echo "Switch between windows (when attached):"
echo " Ctrl+B then 0 (for TeamSpeak)"
echo " Ctrl+B then 1 (for logs)"
+23 -407
View File
@@ -1,427 +1,43 @@
# Echoion Standalone - Systemd Service
# Echoion Standalone systemd service
The supported service is `echoion-standalone.service`. It runs `echoiond`
directly; no graphical TeamSpeak client, Weston session, or plugin directory is
required.
Echoion is deployed as the `echoiond` standalone daemon. The legacy TeamSpeak
client plugin and its graphical/headless TeamSpeak client services are no
longer supported.
## Supported service
## Install
- `echoion-standalone.service` - User service for the standalone daemon.
Build and install Echoion, then copy the user service:
The `teamspeak-echoion*.service` files and GUI/headless helper scripts remain
only as archived compatibility material for `BUILD_PLUGIN=ON` deployments.
## Prerequisites
1. **Weston** - Wayland compositor
```bash
sudo pacman -S weston
```
2. **DBus** - For session management
```bash
sudo pacman -S dbus
```
3. **TeamSpeak 3 Client** - Installed in `/home/bot/TeamSpeak3-Client-linux_amd64`
4. **TLS Certificates** - For RDP connections
```bash
# Generate self-signed certificates
openssl req -x509 -newkey rsa:4096 \
-keyout ~/.config/EchoionTsBot.key \
-out ~/.config/EchoionTsBot.crt \
-days 365 -nodes
```
## Quick Install
### Option 1: User Service (Recommended)
Run as your bot user:
```bash
cd ~/echoion/scripts
./install-service.sh user
```
This creates a user service that runs as the bot user.
**⚠️ Important: DBus Session Error**
If you get an error like:
```
Failed to connect to user scope bus via local transport: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined
```
This happens when running from a minimal shell without a full user session. This is **normal** and the service files are still installed correctly. See the [DBus Session section](#dbus-session-setup) below for solutions.
### Option 2: System Service
Run as root:
```bash
cd /path/to/echoion/scripts
sudo ./install-service.sh system
```
## Manual Installation
### User Service
1. Copy service file:
```bash
mkdir -p ~/.config/systemd/user
cp teamspeak-echoion-user.service ~/.config/systemd/user/teamspeak-echoion.service
```
2. Copy wrapper script:
```bash
mkdir -p ~/echoion/scripts
cp run-teamspeak-headless.sh ~/echoion/scripts/
chmod +x ~/echoion/scripts/run-teamspeak-headless.sh
```
3. Reload systemd:
```bash
systemctl --user daemon-reload
```
4. Start service:
```bash
systemctl --user start teamspeak-echoion
```
5. Enable on login:
```bash
systemctl --user enable teamspeak-echoion
```
6. Enable on boot (without login):
```bash
sudo loginctl enable-linger $(whoami)
```
### System Service
1. Copy service file:
```bash
sudo cp teamspeak-echoion.service /etc/systemd/system/
```
2. Edit service file to match your user:
```bash
sudo systemctl edit --full teamspeak-echoion
```
3. Reload systemd:
```bash
sudo systemctl daemon-reload
```
4. Start service:
```bash
sudo systemctl start teamspeak-echoion
```
5. Enable on boot:
```bash
sudo systemctl enable teamspeak-echoion
```
## DBus Session Setup
When running the install script or systemd commands via SSH or a minimal shell, you may encounter:
```
Failed to connect to user scope bus via local transport: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined
```
This is normal and the service files are still installed correctly. Here are the solutions:
### Solution 1: Use SSH with PTY (Easiest)
Connect with a pseudo-terminal allocation:
```bash
ssh -t bot@your-server bash
```
Then run systemd commands normally:
```bash
mkdir -p ~/.config/systemd/user
cp systemd/echoion-standalone.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user start teamspeak-echoion
systemctl --user enable --now echoion-standalone.service
```
### Solution 2: Enable Lingering and Reboot
Enable lingering so the user services start on boot without needing a login session:
```bash
sudo loginctl enable-linger bot
```
Then reboot the server. After reboot, the service will start automatically.
### Solution 3: Manual Start (No systemd)
If you just want to test or can't get systemd working:
```bash
~/echoion/scripts/run-teamspeak-headless.sh
```
Or use the helper script:
```bash
~/echoion/scripts/start-echoion.sh
```
### Solution 4: Use tmux/screen
Run in a persistent terminal session:
```bash
tmux new-session -d -s teamspeak '~/echoion/scripts/run-teamspeak-headless.sh'
```
To view: `tmux attach -t teamspeak`
To detach: Press `Ctrl+B` then `D`
### Solution 5: System Service (No DBus needed)
Install as a system service instead (requires root):
```bash
sudo ~/echoion/scripts/install-service.sh system
```
## Usage
### Check Service Status
**User service:**
```bash
systemctl --user status teamspeak-echoion
```
**System service:**
```bash
sudo systemctl status teamspeak-echoion
```
### View Logs
**User service:**
```bash
journalctl --user -u teamspeak-echoion -f
```
**System service:**
```bash
sudo journalctl -u teamspeak-echoion -f
```
### Stop Service
**User service:**
```bash
systemctl --user stop teamspeak-echoion
```
**System service:**
```bash
sudo systemctl stop teamspeak-echoion
```
### Restart Service
**User service:**
```bash
systemctl --user restart teamspeak-echoion
```
**System service:**
```bash
sudo systemctl restart teamspeak-echoion
```
## RDP Connection
Once the service is running, you can connect via RDP to manage TeamSpeak:
**Default port is now 3390** (changed from 3389 to avoid conflicts):
For a service that starts before interactive login, enable lingering for the
service account:
```bash
xfreerdp3 /v:localhost:3390 /u:bot /p: /cert:ignore
sudo loginctl enable-linger "$USER"
```
Or use any RDP client with:
- **Host**: Your server IP or localhost
- **Port**: 3390 (default, or change in service file)
- **Username**: bot (or your configured user)
- **TLS**: Enabled (uses the certificates you provided)
The service expects the installed `echoiond` executable, configuration, and
release manifest paths documented in `echoion-standalone.service`. Override
them without editing the tracked unit:
**To use a different port**, edit the service:
```bash
systemctl --user edit --full teamspeak-echoion
systemctl --user edit echoion-standalone.service
```
Change `RDP_PORT=3390` to your preferred port.
## Operations
## Configuration
Edit the service file to customize:
- **User/Group**: Change `bot` to your bot user
- **Paths**: Update paths to TeamSpeak, certificates, and scripts
- **Environment**: Add or modify environment variables
- **Resources**: Adjust `LimitNOFILE` and `LimitNPROC`
- **Restart policy**: Change `Restart` and `RestartSec` values
## Troubleshooting
### Service fails to start
1. Check logs:
```bash
journalctl -u teamspeak-echoion --no-pager -n 50
```
2. Verify certificates exist:
```bash
ls -la ~/.config/EchoionTsBot.*
```
3. Test wrapper script manually:
```bash
~/echoion/scripts/run-teamspeak-headless.sh
```
### Weston/RDP issues
#### Error: "RDP unable to bind socket"
This is the most common error. Several things can cause this:
**1. Port already in use or permission denied**
```bash
# Check if port is in use
sudo ss -tlnp | grep 3389
# Try a different port (edit service file to use port 3390 or higher)
export RDP_PORT=3390
~/echoion/scripts/run-teamspeak-headless.sh
systemctl --user status echoion-standalone.service
journalctl --user -u echoion-standalone.service -f
systemctl --user restart echoion-standalone.service
```
**2. Certificate issues**
```bash
# Check certificates exist and are readable
ls -la ~/.config/EchoionTsBot.*
# Generate new certificates if needed
openssl req -x509 -newkey rsa:4096 \
-keyout ~/.config/EchoionTsBot.key \
-out ~/.config/EchoionTsBot.crt \
-days 365 -nodes
# Fix permissions
chmod 600 ~/.config/EchoionTsBot.key
chmod 644 ~/.config/EchoionTsBot.crt
```
**3. Missing weston RDP backend**
```bash
# Check if RDP backend is installed
ls -la /usr/lib/libweston-*/rdp-backend.so
# If missing, install weston properly
sudo pacman -S weston
```
**4. Test weston without TeamSpeak**
```bash
# Create test directory
mkdir -p /tmp/test-weston
export XDG_RUNTIME_DIR=/tmp/test-weston
# Test weston only
dbus-run-session -- weston --backend=rdp --rdp-port=3390
# If this works, the issue is with the full setup
```
**5. Use alternative port (3390 instead of 3389)**
The service now defaults to port 3390 to avoid conflicts. To change the port:
Edit the service file:
```bash
systemctl --user edit --full teamspeak-echoion
```
Change:
```ini
Environment="RDP_PORT=3390"
```
To your preferred port (e.g., 3391, 3392, etc.)
#### Other RDP issues
1. Check weston configuration:
```bash
cat ~/.config/weston.ini
```
2. Run diagnostic script:
```bash
~/echoion/scripts/diagnose-echoion.sh
```
3. Check weston logs:
```bash
journalctl --user -u teamspeak-echoion --no-pager -n 100
```
### Permission issues
1. Check file ownership:
```bash
ls -la ~/TeamSpeak3-Client-linux_amd64/
ls -la ~/.config/EchoionTsBot.*
```
2. Fix permissions:
```bash
sudo chown -R bot:bot ~/TeamSpeak3-Client-linux_amd64/
sudo chown bot:bot ~/.config/EchoionTsBot.*
```
## Security Notes
1. **Firewall**: Restrict RDP port (3389) access to trusted IPs only
```bash
sudo ufw allow from 192.168.1.0/24 to any port 3389
```
2. **Certificates**: Use proper TLS certificates in production, not self-signed
3. **User permissions**: Run as non-root user with minimal privileges
4. **Network isolation**: Consider running in a container or VM for isolation
## Uninstallation
### User Service
```bash
systemctl --user stop teamspeak-echoion
systemctl --user disable teamspeak-echoion
rm ~/.config/systemd/user/teamspeak-echoion.service
systemctl --user daemon-reload
```
### System Service
```bash
sudo systemctl stop teamspeak-echoion
sudo systemctl disable teamspeak-echoion
sudo rm /etc/systemd/system/teamspeak-echoion.service
sudo systemctl daemon-reload
```
## See Also
- [Weston Documentation](https://wayland.freedesktop.org/weston.html)
- [systemd Documentation](https://www.freedesktop.org/software/systemd/man/)
- [TeamSpeak 3 Client](https://www.teamspeak.com/)
- [Echoion Bot Documentation](../README.md)
TeamSpeak protocol, query transport, identity, and typed administration are
provided by VoidTeamspeak. EchoionStandalone only adapts those APIs to the
Echoion core contracts.
+2 -4
View File
@@ -1,7 +1,5 @@
# Echoion standalone daemon — connects to a TeamSpeak 3/6 server as its own
# client over the native UDP protocol. Replaces the old
# teamspeak-echoion.service, which had to run a full GUI TeamSpeak client under
# Weston + RDP just to host the plugin. None of that is needed anymore.
# Echoion standalone daemon. TeamSpeak transport and protocol behavior are
# provided by VoidTeamspeak; this process hosts the Echoion adapter and core.
#
# Install: copy `echoiond` and `Echoion.ts` (the Core library) somewhere on
# disk, put config.json in ~/.config/echoion/ (or pass --config), then:
-52
View File
@@ -1,52 +0,0 @@
[Unit]
Description=TeamSpeak 3 Client with Echoion Music Bot
After=network.target sound.target
Wants=network.target sound.target
[Service]
Type=simple
# Environment setup
Environment="XDG_RUNTIME_DIR=/tmp/.ts3bot-display-%u"
Environment="HOME=%h"
Environment="USER=%u"
Environment="RDP_PORT=3390"
Environment="WESTON_DEBUG=1"
# Working directory
WorkingDirectory=%h/TeamSpeak3-Client-linux_amd64
# Create runtime directory
ExecStartPre=/bin/mkdir -p /tmp/.ts3bot-display-%u
ExecStartPre=/bin/chmod 700 /tmp/.ts3bot-display-%u
# Check if port is available
ExecStartPre=-/bin/sh -c 'ss -tlnp | grep -q ":3390 " && echo "Port 3390 in use, trying alternative" && exit 1 || exit 0'
# Main command using the wrapper script
ExecStart=/home/bot/echoion/scripts/run-teamspeak-headless.sh
# Restart policy
Restart=always
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3
# Resource limits
LimitNOFILE=65536
LimitNPROC=4096
# Security settings - allow binding to ports
PrivateNetwork=no
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
# Ensure we have proper socket permissions
UMask=0077
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=teamspeak-echoion
[Install]
WantedBy=default.target
-55
View File
@@ -1,55 +0,0 @@
[Unit]
Description=TeamSpeak 3 Client with Echoion Music Bot
After=network.target sound.target
Wants=network.target sound.target
[Service]
Type=simple
User=bot
Group=bot
# Working directory where TeamSpeak client is installed
WorkingDirectory=/home/bot/TeamSpeak3-Client-linux_amd64
# Environment setup
Environment="XDG_RUNTIME_DIR=/tmp/.ts3bot-display"
Environment="HOME=/home/bot"
Environment="USER=bot"
Environment="DISPLAY=:1"
# Create runtime directory and start the service
ExecStartPre=/bin/mkdir -p /tmp/.ts3bot-display
ExecStartPre=/bin/chmod 700 /tmp/.ts3bot-display
# Main command - runs dbus, weston with RDP backend, and TeamSpeak
ExecStart=/bin/bash -c 'cd /home/bot/TeamSpeak3-Client-linux_amd64 && \
dbus-run-session -- \
weston \
--backend=rdp \
--xwayland \
--rdp-tls-cert=/home/bot/.config/EchoionTsBot.crt \
--rdp-tls-key=/home/bot/.config/EchoionTsBot.key \
-- ./ts3client_runscript.sh'
# Restart policy
Restart=always
RestartSec=10
StartLimitInterval=60
StartLimitBurst=3
# Resource limits
LimitNOFILE=65536
LimitNPROC=4096
# Security settings
NoNewPrivileges=false
ProtectSystem=no
ProtectHome=no
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=teamspeak-echoion
[Install]
WantedBy=multi-user.target