diff --git a/toREST/include/ws.hpp b/toREST/include/ws.hpp index 3a5e724..5318017 100644 --- a/toREST/include/ws.hpp +++ b/toREST/include/ws.hpp @@ -3,6 +3,7 @@ #include #include +#include namespace tr { namespace ws { @@ -32,6 +33,15 @@ void on_open(Server &server, Session &session, Connection con) { template void on_message(Session &session, Connection con, Message message) { + nlohmann::json obj = util::json::parse(*message); + if (!obj.is_null() && obj.is_object()) { + auto type = util::json::get("type", obj, std::string()); + if (!type.empty()) { + if (type == "POST_TORRENT_UPDATES") { + session.post_torrent_updates(); + } + } + } } } } diff --git a/toREST/tests/ws_test.cpp b/toREST/tests/ws_test.cpp index 422c2fc..ac69cab 100644 --- a/toREST/tests/ws_test.cpp +++ b/toREST/tests/ws_test.cpp @@ -12,6 +12,12 @@ struct TestConnection { int status_ = 0; }; +struct TestMessage : public std::stringstream { + std::string string() { + return str(); + } +}; + struct TestWsServer { void send_close(std::shared_ptr con, int status, const std::string &reason) { send_close_calls_++; @@ -44,4 +50,39 @@ SCENARIO("we have a websocket resource") { } } } + auto message = std::make_shared(); + GIVEN("we recive an json request") { + WHEN("the json isn't valid") { + *message << "Not valid"; + THEN("the server should reject the action") { + tr::ws::on_message(session, connection, message); + REQUIRE(server.send_close_calls_ == 0); + REQUIRE(session.post_torrent_updates_calls_ == 0); + } + } + WHEN("the json is valid but doesn't have any of the required fields") { + *message << "{}"; + THEN("the server should reject the action") { + tr::ws::on_message(session, connection, message); + REQUIRE(server.send_close_calls_ == 0); + REQUIRE(session.post_torrent_updates_calls_ == 0); + } + } + WHEN("the json is valid and have the required fields but not of valid type") { + *message << nlohmann::json({{"type", "N/A"}}); + THEN("the server should reject the action") { + tr::ws::on_message(session, connection, message); + REQUIRE(server.send_close_calls_ == 0); + REQUIRE(session.post_torrent_updates_calls_ == 0); + } + } + WHEN("the json is valid and have the required fields") { + *message << nlohmann::json({{"type", "POST_TORRENT_UPDATES"}}); + THEN("the server should post torrent updates") { + tr::ws::on_message(session, connection, message); + REQUIRE(server.send_close_calls_ == 0); + REQUIRE(session.post_torrent_updates_calls_ == 1); + } + } + } } \ No newline at end of file