1 parent
1c96d5973b
commit
e80dbc2fda
38 files changed
+1352
-6335
No files matched your search
+44
-348
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user