summaryrefslogtreecommitdiff
path: root/src/session.hpp
blob: 235870c3a05500d831030022e96291f308e84c62 (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
#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 {
		char	data[1024] = {0};
		ssize_t dataSize   = sizeof(data);
		bool	good	   = true;
	};

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

	SRecvData	read();
	SRecvData	read(const std::string &msg);
	bool		write(const std::string &msg, eFormatType type);
	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;

	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;
};