summaryrefslogtreecommitdiff
path: root/src/session.hpp
blob: 77687f98f12edb571609e02a25589f3ae1c5fbd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#pragma once

#include "FileDescriptor.hpp"
#include "format.hpp"
#include <memory>
#include <netinet/in.h>
#include <string>
#include <thread>

class CSession {
  public:
	CSession();
	~CSession();

	struct SRecvData {
		std::string data;
		bool        good = true;
	};

	std::string getName();
	void        setSelf(std::pair<std::jthread, std::shared_ptr<CSession>> *self);

	std::unique_ptr<SRecvData> read();
	std::unique_ptr<SRecvData> read(const std::string &msg);
	bool	  write(const std::string &msg);
	template <typename... Args>
	bool write(std::format_string<Args...> fmt, Args &&...args);
  template <typename... Args>
  bool write(eFormatType type, std::format_string<Args...> fmt, Args &&...args);

	void run();

	bool isValid();

  private:
	enum eEventType : std::uint8_t {
		READ,
		WRITE
	};

	std::pair<std::jthread, std::shared_ptr<CSession>> *self;
	Hyprutils::OS::CFileDescriptor						m_sockfd;
	sockaddr_in											m_addr;
	socklen_t											m_addrLen = sizeof(m_addr);
	std::string											m_name;
	char												m_ip[INET_ADDRSTRLEN];
	int													m_port;

	bool m_isReading = false;

	void recvLoop();
	bool registerSession();

	void onConnect();
	void onDisconnect();
	void onErrno(eEventType);
	void onRecv(const SRecvData &data);
	void onSend(const std::string &msg);
	void onShutdown();

	friend class CSessionManager;
};