diff --git a/src/server.cpp b/src/server.cpp index b103bcc..75ff7aa 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -1,11 +1,76 @@ #include "message-buffer.hpp" #include "utils.hpp" #include +#include #include #include #include #include +class ServerdService : public RoutineService { + const char* m_host; + int m_port; + + httplib::Server svr; + MessagesBuffer m_buffer; + +public: + explicit ServerdService(const char* host, const int port, std::string serviceId) + : RoutineService { serviceId } + , m_host { host } + , m_port { port } + , m_buffer { 10 } + { + } + + const DBusHandler::Path m_requestPath { + "zfkd.dbus.serverd", + "/zfkd/dbus/serverd", + "zfkd.dbus.serverd", + "request" + }; + + void setup() override + { + + svr.Post("/", [&](const httplib::Request& req, httplib::Response& res) { + nlohmann::json receivedJson; + receivedJson = nlohmann::json::parse(req.body); + + int id = receivedJson["equipe"]; + nlohmann::json payload = receivedJson["payload"]; + + m_buffer.write(id, payload); + utils::saveJson(receivedJson, std::to_string(id)); + + res.set_content("received message", "text/plain"); + }); + + svr.set_error_handler([](const httplib::Request&, httplib::Response& res) { + std::string error = "Error:" + std::to_string(res.status); + res.set_content(error, "text/plain"); + }); + + svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception& e) { + std::cout << e.what() << std::endl; + res.set_content("exception raised", "text/plain"); + }); + + DBusHandler::registerMethod(m_requestPath, [&](nlohmann::json req) { + return m_buffer.getCurrMessage(); + }); + } + + void routine() override + { + svr.listen(m_host, m_port); + } + + void destroy() override + { + } +}; + auto main(int argc, char* argv[]) -> int { const char* host; @@ -21,31 +86,10 @@ auto main(int argc, char* argv[]) -> int throw std::invalid_argument("invalid number of arguments"); } - httplib::Server svr; - MessagesBuffer buffer(10); - - svr.Post("/", [&buffer](const httplib::Request& req, httplib::Response& res) { - nlohmann::json receivedJson; - receivedJson = nlohmann::json::parse(req.body); - - int id = receivedJson["equipe"]; - nlohmann::json payload = receivedJson["payload"]; - - buffer.write(id, payload); - utils::saveJson(receivedJson, std::to_string(id)); - - res.set_content("received message", "text/plain"); - }); - - svr.set_error_handler([](const httplib::Request&, httplib::Response& res) { - std::string error = "Error:" + std::to_string(res.status); - res.set_content(error, "text/plain"); - }); - - svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res, std::exception& e) { - std::cout << e.what() << std::endl; - res.set_content("exception raised", "text/plain"); - }); + Daemon serverd("serverd.json"); + ServerdService serverdService(host, port, "serverd"); + serverd.deploy(serverdService); + serverd.run(); - svr.listen(host, port); + return 0; }