commit
9574aa8a23
87 files changed
+14884
No files matched your search
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#include "echoion/web/WatchSession.hpp"
|
||||
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
#include <boost/beast.hpp>
|
||||
#include <boost/beast/http.hpp>
|
||||
#include <boost/beast/websocket.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
namespace asio = boost::asio;
|
||||
namespace beast = boost::beast;
|
||||
namespace http = beast::http;
|
||||
namespace websocket = beast::websocket;
|
||||
|
||||
// Serves the static browser UI over HTTP, hosts the independent
|
||||
// sync-watch WebSocket at GET /ws, and tunnels GET /rpc upgrades to the
|
||||
// local RPC server so only the web port ever needs to be exposed. It has
|
||||
// no handle on the music bot itself.
|
||||
class HttpServer
|
||||
{
|
||||
public:
|
||||
|
||||
struct Config {
|
||||
uint16_t port = 8080;
|
||||
std::string bindAddress = "127.0.0.1";
|
||||
std::string webRoot = "./web";
|
||||
// Explicit RPC URL served to the browser; when empty the UI
|
||||
// derives ws://<page-host>:<rpcPort>.
|
||||
std::string rpcUrl;
|
||||
uint16_t rpcPort = 8765;
|
||||
// Server-wide switch for the Now Playing video preview,
|
||||
// surfaced to the browser via /config.json.
|
||||
bool nowPlayingVideo = true;
|
||||
};
|
||||
|
||||
HttpServer();
|
||||
~HttpServer();
|
||||
|
||||
bool start(const Config& config);
|
||||
void stop();
|
||||
[[nodiscard]] bool isRunning() const { return running_; }
|
||||
|
||||
// Token → identity lookup for the watch feature; installed by
|
||||
// Core, which owns the credential store. May be set before or
|
||||
// after start() and survives stop()/start() cycles.
|
||||
void setIdentityResolver(
|
||||
WatchSessionManager::IdentityResolver resolver)
|
||||
{
|
||||
watch_.setIdentityResolver(std::move(resolver));
|
||||
}
|
||||
|
||||
// A user's avatar image, served at GET /avatar/<uid>. Installed
|
||||
// by Core (which owns the TeamSpeak plugin handle); best-effort —
|
||||
// nullopt yields a 404 and the UI falls back to initials. Same
|
||||
// lifetime rules as the identity resolver.
|
||||
struct AvatarImage {
|
||||
std::string contentType;
|
||||
std::string bytes;
|
||||
};
|
||||
using AvatarProvider = std::function<std::optional<AvatarImage>(
|
||||
const std::string& uid)>;
|
||||
void setAvatarProvider(AvatarProvider provider)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
|
||||
avatarProvider_ = std::move(provider);
|
||||
}
|
||||
|
||||
// A custom emoji image, served at GET /emoji/<name>. Same shape
|
||||
// and lifetime rules as the avatar provider; installed by Core
|
||||
// (which owns the emoji database).
|
||||
using EmojiProvider = std::function<std::optional<AvatarImage>(
|
||||
const std::string& name)>;
|
||||
void setEmojiProvider(EmojiProvider provider)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(avatarProviderMutex_);
|
||||
emojiProvider_ = std::move(provider);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
void acceptLoop();
|
||||
void doAccept();
|
||||
void onAccept(asio::ip::tcp::socket socket);
|
||||
void handleConnection(std::shared_ptr<asio::ip::tcp::socket> socket);
|
||||
void handleWatch(
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>> ws);
|
||||
// Tunnel a browser WebSocket upgrade at /rpc to the local RPC
|
||||
// server as raw TCP: the original upgrade request is replayed
|
||||
// upstream and bytes are pumped in both directions, so the real
|
||||
// handshake/auth all happen against the RPC server itself.
|
||||
void bridgeRpc(std::shared_ptr<asio::ip::tcp::socket> browser,
|
||||
http::request<http::string_body>& req,
|
||||
beast::flat_buffer& residual);
|
||||
// Serves one request; returns true when the connection should be
|
||||
// kept open for the next request (HTTP keep-alive).
|
||||
bool serveHttp(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req);
|
||||
bool serveWatchProxy(asio::ip::tcp::socket& socket,
|
||||
const http::request<http::string_body>& req);
|
||||
void sendToWatcher(uint64_t connId, const std::string& json);
|
||||
void syncLoop(std::stop_token stopToken);
|
||||
|
||||
Config config_;
|
||||
asio::io_context ioContext_;
|
||||
std::optional<asio::ip::tcp::acceptor> acceptor_;
|
||||
std::thread serverThread_;
|
||||
std::atomic<bool> running_{false};
|
||||
|
||||
// Per-connection handlers run on a worker pool; ~ThreadPool drains
|
||||
// and joins them on stop.
|
||||
static constexpr std::size_t POOL_SIZE = 32;
|
||||
std::unique_ptr<Void::Concurrency::ThreadPool> pool_;
|
||||
|
||||
std::unordered_map<
|
||||
uint64_t,
|
||||
std::shared_ptr<websocket::stream<asio::ip::tcp::socket>>>
|
||||
watchers_;
|
||||
std::mutex watchersMutex_;
|
||||
std::atomic<uint64_t> nextConnId_{1};
|
||||
|
||||
// Live /rpc bridges (browser, upstream); shut down on stop() so
|
||||
// the blocking pump loops unblock and the pool can join.
|
||||
std::unordered_map<uint64_t,
|
||||
std::pair<std::shared_ptr<asio::ip::tcp::socket>,
|
||||
std::shared_ptr<asio::ip::tcp::socket>>>
|
||||
bridges_;
|
||||
std::mutex bridgesMutex_;
|
||||
|
||||
WatchSessionManager watch_;
|
||||
std::jthread syncThread_;
|
||||
|
||||
// Called from pool threads; guarded so Core can (re)install them
|
||||
// at any time. Both share one mutex (installed together at start).
|
||||
AvatarProvider avatarProvider_;
|
||||
EmojiProvider emojiProvider_;
|
||||
std::mutex avatarProviderMutex_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web
|
||||
@@ -0,0 +1,200 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Echoion::Web
|
||||
{
|
||||
|
||||
// Authoritative state for synchronized video watching. This is entirely
|
||||
// independent of the music bot's playback pipeline: browsers play the video
|
||||
// locally and the server is only the timing authority for each room.
|
||||
//
|
||||
// The manager owns room state and participant membership. It never writes to
|
||||
// sockets directly -- HttpServer installs a `sender` callback and the manager
|
||||
// asks it to deliver JSON text to individual connections. That keeps all
|
||||
// Boost.Beast/socket concerns in HttpServer and makes this unit trivially
|
||||
// testable.
|
||||
//
|
||||
// Roles: the first *authenticated* participant to join a room is its host;
|
||||
// only the host may load/play/pause/seek and advance the queue, and every
|
||||
// control message additionally requires authentication (guests can watch,
|
||||
// chat and react but never manipulate). The host role migrates to another
|
||||
// authenticated participant when the host leaves. Twitch rooms are live:
|
||||
// there is no position authority, seek is refused, and everyone simply
|
||||
// embeds the same channel.
|
||||
//
|
||||
// Rooms with a loaded video survive everyone leaving: playback is paused
|
||||
// in place and the next authenticated joiner becomes host, so a page
|
||||
// refresh does not wipe the session. Abandoned rooms are pruned after
|
||||
// kEmptyRoomTtl.
|
||||
class WatchSessionManager
|
||||
{
|
||||
public:
|
||||
|
||||
// Delivers one JSON text frame to a single connection id.
|
||||
using Sender = std::function<void(uint64_t connId,
|
||||
const std::string& json)>;
|
||||
|
||||
// Authenticated identity behind an RPC token. The resolver is
|
||||
// installed by Core (it owns the token database); the manager
|
||||
// itself never sees credentials storage.
|
||||
struct Identity {
|
||||
std::string uid;
|
||||
std::string nickname;
|
||||
bool isAdmin = false;
|
||||
};
|
||||
using IdentityResolver =
|
||||
std::function<std::optional<Identity>(const std::string& token)>;
|
||||
|
||||
// Best-effort title lookup for a queued video, so the watch queue
|
||||
// shows real names server-side instead of relying on the browser.
|
||||
// Installed by Core (which owns the YouTube metadata stack); when
|
||||
// unset or it returns nullopt, the client-supplied title (or the
|
||||
// Twitch channel name) is used. Called on the message thread, so
|
||||
// it must be quick / cached.
|
||||
using MetadataResolver = std::function<std::optional<std::string>(
|
||||
const std::string& source, const std::string& videoId,
|
||||
const std::string& url)>;
|
||||
|
||||
void setSender(Sender sender) { sender_ = std::move(sender); }
|
||||
void setIdentityResolver(IdentityResolver resolver)
|
||||
{
|
||||
identityResolver_ = std::move(resolver);
|
||||
}
|
||||
void setMetadataResolver(MetadataResolver resolver)
|
||||
{
|
||||
metadataResolver_ = std::move(resolver);
|
||||
}
|
||||
|
||||
// A watch WebSocket connected / disconnected. onDisconnect removes
|
||||
// the connection from whatever room it had joined and notifies the
|
||||
// remaining participants.
|
||||
void onConnect(uint64_t connId);
|
||||
void onDisconnect(uint64_t connId);
|
||||
|
||||
// Handle one inbound JSON message from a connection. Unknown or
|
||||
// malformed messages are ignored.
|
||||
void onMessage(uint64_t connId, const std::string& json);
|
||||
|
||||
// Broadcast a periodic sync heartbeat (position + participants) to
|
||||
// every room. HttpServer drives this on a timer so drifting
|
||||
// clients can re-align.
|
||||
void broadcastSync();
|
||||
|
||||
private:
|
||||
|
||||
struct Participant {
|
||||
std::string name;
|
||||
// TeamSpeak unique id when authenticated (empty for guests),
|
||||
// so the web UI can fetch the persisted avatar at /avatar.
|
||||
std::string uid;
|
||||
// Set when the join/rename carried a valid RPC token;
|
||||
// required for any control message and for hosting.
|
||||
bool authenticated = false;
|
||||
// Last client-reported playback position and the room
|
||||
// authority position at that moment (for drift display).
|
||||
long long reportedMs = -1;
|
||||
long long authorityMs = -1;
|
||||
bool buffering = false;
|
||||
};
|
||||
|
||||
struct ChatMessage {
|
||||
std::string name;
|
||||
std::string text;
|
||||
long long timestampMs = 0;
|
||||
};
|
||||
|
||||
// One queued-up video waiting to be watched after the current one.
|
||||
struct QueueEntry {
|
||||
std::string source; // youtube|twitch|direct|iframe
|
||||
std::string url;
|
||||
std::string videoId;
|
||||
std::string title; // resolved server-side, best effort
|
||||
std::string thumbnailUrl; // derived from source + id
|
||||
std::string addedBy;
|
||||
};
|
||||
|
||||
struct Room {
|
||||
std::string source = "youtube"; // youtube|twitch|direct|iframe
|
||||
std::string url;
|
||||
std::string videoId; // YouTube id / Twitch channel; empty
|
||||
// for direct & iframe (url carries it)
|
||||
// Host-reported (watch.embed.caps): the iframe embed answered
|
||||
// a postMessage handshake, so the room has real position
|
||||
// authority (seek allowed, position freezes when emptied).
|
||||
// Reset on every load until the host re-handshakes.
|
||||
bool controllable = false;
|
||||
bool paused = true;
|
||||
// Host-selected playback rate (YouTube only); 1.0 = normal.
|
||||
double rate = 1.0;
|
||||
// Host-selected provider media settings. Local-only settings
|
||||
// (volume, quality, subtitles) never enter room state.
|
||||
std::map<std::string, std::string> embedControls;
|
||||
// Position (ms) captured at `anchor`. While playing, the
|
||||
// live position is positionMs + (now - anchor).
|
||||
long long positionMs = 0;
|
||||
std::chrono::steady_clock::time_point anchor{
|
||||
std::chrono::steady_clock::now()};
|
||||
uint64_t host = 0;
|
||||
std::map<uint64_t, Participant> participants;
|
||||
std::deque<ChatMessage> chat; // last kChatBacklog kept
|
||||
std::deque<QueueEntry> queue; // up-next, kQueueMax cap
|
||||
// Connection ids that voted to skip the current video;
|
||||
// cleared whenever the video changes or a voter leaves.
|
||||
std::set<uint64_t> skipVotes;
|
||||
// When the room last had participants; drives pruning of
|
||||
// empty-but-persisted rooms.
|
||||
std::chrono::steady_clock::time_point lastActive{
|
||||
std::chrono::steady_clock::now()};
|
||||
};
|
||||
|
||||
static constexpr size_t kChatBacklog = 50;
|
||||
static constexpr size_t kQueueMax = 100;
|
||||
static constexpr size_t kEmbedControlsMax = 16;
|
||||
static constexpr std::chrono::hours kEmptyRoomTtl{24};
|
||||
|
||||
[[nodiscard]] long long livePosition(const Room& room) const;
|
||||
void send(uint64_t connId, const std::string& json) const;
|
||||
void broadcast(const Room& room, const std::string& json) const;
|
||||
void sendParticipants(const Room& room) const;
|
||||
void sendSnapshot(uint64_t connId, const Room& room) const;
|
||||
void sendDenied(uint64_t connId, const std::string& reason) const;
|
||||
void sendQueue(const Room& room, uint64_t onlyTo = 0) const;
|
||||
// Broadcast the vote-skip tally (votes / needed) for the room.
|
||||
void sendSkipState(const Room& room) const;
|
||||
// Votes needed to skip in a room: majority of participants.
|
||||
[[nodiscard]] static std::size_t skipThreshold(const Room& room);
|
||||
// Reply to watch.rooms.list with the lobby of active rooms.
|
||||
void sendRoomsList(uint64_t connId) const;
|
||||
// Deterministic thumbnail URL for a queued/loaded video.
|
||||
[[nodiscard]] static std::string
|
||||
thumbnailFor(const std::string& source,
|
||||
const std::string& videoId);
|
||||
// Point the room at a new video (shared by watch.load and
|
||||
// queue advancement) and broadcast watch.loaded.
|
||||
void loadIntoRoom(Room& room, const std::string& source,
|
||||
const std::string& url,
|
||||
const std::string& channel, uint64_t byConnId);
|
||||
// First authenticated participant, or 0 when only guests remain.
|
||||
[[nodiscard]] static uint64_t pickHost(const Room& room);
|
||||
void leaveCurrentRoom(uint64_t connId);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_map<std::string, Room> rooms_;
|
||||
// connId -> room name it currently belongs to.
|
||||
std::unordered_map<uint64_t, std::string> connRoom_;
|
||||
Sender sender_;
|
||||
IdentityResolver identityResolver_;
|
||||
MetadataResolver metadataResolver_;
|
||||
};
|
||||
|
||||
} // namespace Echoion::Web
|
||||
Reference in new issue
Block a user