summaryrefslogtreecommitdiff
path: root/include/libsock/server/clients.hpp
blob: 4b67c23b1298414e6d9826c6c14c9fd9619d13ad (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
#pragma once

#include "../types.hpp"
#include "server.hpp"
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <thread>
#include <vector>

namespace LibSock {
namespace Server {

class Client;

struct SData {
	std::string				  msg;
	std::optional<WP<Client>> sender = std::nullopt;
};

class Clients : public std::enable_shared_from_this<Clients> {
  public:
	static SP<Clients> create(WP<Server> server);
	~Clients();

	SP<Client> newClient(std::function<void(SP<Client> &)> cb = [](SP<Client>) {}, bool track = true, bool wait = false);

	void broadcast(const std::string &msg, std::optional<WP<Client>> self = std::nullopt); // second param only specified when we
																						   // want to exclude the sender
	void kick(WP<Client> client, const bool kill = false, const std::string &reason = "", std::optional<std::function<bool(const std::vector<std::pair<std::jthread, SP<Client>>>::iterator &)>> cb = std::nullopt);
	void addClient(const Client &client);

	void shutdownClients(std::optional<std::function<bool(const std::vector<std::pair<std::jthread, SP<Client>>> &)>> cb = std::nullopt);

	SP<Client>				getByIp(const std::string &ip) const;
	std::vector<SP<Client>> getClients() const;
	std::vector<SData>		getDatas() const;

  private:
	Clients();
	void broadcast(const SData &msg);

	std::vector<std::pair<std::jthread, SP<Client>>> m_vClients;
	std::vector<SData>								 m_vDatas;

	WP<Clients> get();

	WP<Clients> m_self;
	WP<Server>	m_wpServer;

	friend class Client;
};
inline std::vector<WP<Clients>> vpClients;
} // namespace Server
} // namespace LibSock