/* obs-websocket Copyright (C) 2016-2021 Stephane Lepin Copyright (C) 2020-2021 Kyle Manning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see */ #pragma once #include #include #include #include #include #include #include #include "rpc/WebSocketSession.h" #include "types/WebSocketCloseCode.h" #include "types/WebSocketOpCode.h" #include "../utils/Json.h" #include "../requesthandler/rpc/Request.h" #include "plugin-macros.generated.h" class WebSocketServer : QObject { Q_OBJECT public: enum WebSocketEncoding { Json, MsgPack }; struct WebSocketSessionState { websocketpp::connection_hdl hdl; std::string remoteAddress; uint64_t connectedAt; uint64_t incomingMessages; uint64_t outgoingMessages; bool isIdentified; }; WebSocketServer(); ~WebSocketServer(); void Start(); void Stop(); void InvalidateSession(websocketpp::connection_hdl hdl); void BroadcastEvent(uint64_t requiredIntent, const std::string &eventType, const json &eventData = nullptr, uint8_t rpcVersion = 0); bool IsListening() { return _server.is_listening(); } std::vector GetWebSocketSessions(); QThreadPool *GetThreadPool() { return &_threadPool; } signals: void ClientConnected(WebSocketSessionState state); void ClientDisconnected(WebSocketSessionState state, uint16_t closeCode); private: struct ProcessResult { WebSocketCloseCode::WebSocketCloseCode closeCode = WebSocketCloseCode::DontClose; std::string closeReason; json result; }; void ServerRunner(); void onObsReady(bool loaded); bool onValidate(websocketpp::connection_hdl hdl); void onOpen(websocketpp::connection_hdl hdl); void onClose(websocketpp::connection_hdl hdl); void onMessage(websocketpp::connection_hdl hdl, websocketpp::server::message_ptr message); static void SetSessionParameters(SessionPtr session, WebSocketServer::ProcessResult &ret, const json &payloadData); void ProcessMessage(SessionPtr session, ProcessResult &ret, WebSocketOpCode::WebSocketOpCode opCode, json &payloadData); QThreadPool _threadPool; std::thread _serverThread; websocketpp::server _server; std::string _authenticationSecret; std::string _authenticationSalt; std::mutex _sessionMutex; std::map> _sessions; std::atomic _obsReady = false; };