-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat_db.cpp
63 lines (54 loc) · 1.32 KB
/
chat_db.cpp
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
63
#ifndef CHAT_DB
#define CHAT_DB
#include <map>
#include <mutex>
#include <vector>
#include <functional>
#include "chat.hpp"
class ChatDB {
private:
std::mutex mtx;
std::map<std::string,std::vector<Chat*>> db; // [groupId] -> [list of chats]
std::function<void(Chat,std::string)>* listener;
ChatDB(){
}
public:
ChatDB(const ChatDB&) = delete;
ChatDB& operator=(const ChatDB&) = delete;
static ChatDB* getChatDB(){
static ChatDB chatDb;
return &chatDb;
}
void addListener(std::function<void(Chat,std::string)>* listener){
mtx.lock();
this->listener = listener;
mtx.unlock();
}
void removeListener(){
mtx.lock();
listener = NULL;
mtx.unlock();
}
void saveChat(Chat* chat, const std::string groupId){
mtx.lock();
db[groupId].push_back(chat);
if(listener != NULL){
(*listener)(*chat, groupId);
}
mtx.unlock();
}
std::vector<Chat> fetchChats(const std::string groupId){
std::vector<Chat> res;
mtx.lock();
if(db.count(groupId) == 0) {
mtx.unlock();
return res;
}
for(auto &chat: db[groupId]){
res.push_back(*chat);
}
mtx.unlock();
return res;
}
};
#endif