Older/Server/SharedState.h
2023-07-21 16:17:01 +08:00

66 lines
1.9 KiB
C++

#ifndef SHAREDSTATE_H
#define SHAREDSTATE_H
#include "TemplateMatchs.h"
#include "UrlRouter.h"
#include <boost/asio/io_context.hpp>
#include <boost/beast/http/string_body.hpp>
#include <boost/smart_ptr.hpp>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_set>
class HttpSession;
class WebSocketSession;
// Represents the shared server state
class SharedState:public std::enable_shared_from_this<SharedState> {
// This mutex synchronizes all access to sessions_
std::mutex mutex_;
// Keep a list of all the connected clients
std::unordered_set<WebSocketSession *> sessions_;
public:
using Request = boost::beast::http::request<boost::beast::http::string_body>;
using Handler = std::function<void(HttpSession &, const Request &, const TemplateMatches &)>;
SharedState(boost::asio::io_context &ioContext,std::string doc_root);
const Handler *find(boost::urls::segments_encoded_view path, TemplateMatchStorageBase &matches) const noexcept ;
inline std::string_view docRoot() const noexcept {
return m_docRoot;
}
std::string_view galleryRoot() const noexcept;
inline std::string_view fileRoot() const {
return m_fileRoot;
}
void setFileRoot(const std::string_view &root);
std::string_view notebookRoot() const;
void setNotebookRoot(const std::string_view &root);
void join(WebSocketSession *session);
void leave(WebSocketSession *session);
/**
* @brief Broadcast a message to all websocket client sessions
*/
void send(std::string message);
private:
boost::asio::io_context &m_ioContext;
std::shared_ptr <UrlRouter<Handler>> m_router;
std::string m_docRoot;
std::string m_galleryRoot = "/root/photos";
std::string m_fileRoot;
std::string m_notebookRoot;
};
using SharedStatePtr = std::shared_ptr<SharedState>;
#endif // SHAREDSTATE_H