1 #pragma once 2 3 #include "baserule.hpp" 4 #include "http_request.hpp" 5 #include "http_response.hpp" 6 #include "server_sent_event.hpp" 7 8 #include <boost/beast/http/verb.hpp> 9 10 #include <functional> 11 #include <memory> 12 #include <string> 13 14 namespace crow 15 { 16 17 class SseSocketRule : public BaseRule 18 { 19 using self_t = SseSocketRule; 20 21 public: 22 explicit SseSocketRule(const std::string& ruleIn) : BaseRule(ruleIn) 23 { 24 isUpgrade = true; 25 // Clear GET handler 26 methodsBitfield = 0; 27 } 28 29 void validate() override {} 30 31 void handle(const Request& /*req*/, 32 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 33 const std::vector<std::string>& /*params*/) override 34 { 35 BMCWEB_LOG_ERROR( 36 "Handle called on websocket rule. This should never happen"); 37 asyncResp->res.result( 38 boost::beast::http::status::internal_server_error); 39 } 40 41 void handleUpgrade(const Request& req, 42 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/, 43 boost::asio::ip::tcp::socket&& adaptor) override 44 { 45 std::shared_ptr< 46 crow::sse_socket::ConnectionImpl<boost::asio::ip::tcp::socket>> 47 myConnection = std::make_shared< 48 crow::sse_socket::ConnectionImpl<boost::asio::ip::tcp::socket>>( 49 std::move(adaptor), openHandler, closeHandler); 50 myConnection->start(req); 51 } 52 void handleUpgrade(const Request& req, 53 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/, 54 boost::asio::ssl::stream<boost::asio::ip::tcp::socket>&& 55 adaptor) override 56 { 57 std::shared_ptr<crow::sse_socket::ConnectionImpl< 58 boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>> 59 myConnection = std::make_shared<crow::sse_socket::ConnectionImpl< 60 boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>>( 61 std::move(adaptor), openHandler, closeHandler); 62 myConnection->start(req); 63 } 64 65 template <typename Func> 66 self_t& onopen(Func f) 67 { 68 openHandler = f; 69 return *this; 70 } 71 72 template <typename Func> 73 self_t& onclose(Func f) 74 { 75 closeHandler = f; 76 return *this; 77 } 78 79 private: 80 std::function<void(crow::sse_socket::Connection&, const crow::Request&)> 81 openHandler; 82 std::function<void(crow::sse_socket::Connection&)> closeHandler; 83 }; 84 85 } // namespace crow 86