#pragma once #include #include #include #include #include #include #include #include #include #include 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; // 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(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( 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 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 participants; std::deque chat; // last kChatBacklog kept std::deque 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 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 rooms_; // connId -> room name it currently belongs to. std::unordered_map connRoom_; Sender sender_; IdentityResolver identityResolver_; MetadataResolver metadataResolver_; }; } // namespace Echoion::Web