forked from CPP-Final-Project/Chat_Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageController.cpp
463 lines (409 loc) · 20.9 KB
/
MessageController.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
#include "MessageController.h"
#include "DBUser.h"
#include "MediaSaver_Service.h"
#include "UserRepository.h"
MessageController::MessageController(QObject* object_) : QObject(object_) {}
MessageController::~MessageController() {}
QSharedPointer<MessageController> MessageController::instance()
{
if (!shp_instance)
{
shp_instance = QSharedPointer<MessageController>(new MessageController());
connect(shp_instance.get(), &MessageController::userEntrySignal, RoomController::instance().get(), &RoomController::userEntry);
connect(shp_instance.get(), &MessageController::userLeaveSignal, RoomController::instance().get(), &RoomController::userLeave);
connect(shp_instance.get(), &MessageController::messageToRoom, RoomController::instance().get(), &RoomController::jsonMsgReceived);
connect(shp_instance.get(), &MessageController::roomListRequestSignal, RoomController::instance().get(), &RoomController::roomListRequest);
connect(shp_instance.get(), &MessageController::messageHystoryRequestSignal, RoomController::instance().get(), &RoomController::messageHystoryRequest);
connect(shp_instance.get(), &MessageController::createRoomSignal, RoomController::instance().get(), &RoomController::createRoom);
}
return shp_instance;
}
//MessageController* MessageController::instance(QObject* parent)
//{
// static MessageController inst(parent);
// return &inst;
//}
//User_Message MessageController::createMessage(const QString& nickname_, const QString& text_)
//{
// Message msg;
// msg.nickname = nickname_;
// msg.text = text_;
// msg.room_id = 0;
// msg.deleted = false;
// return User_Message(msg);
// //return User_Message(QUuid::createUuid().toString(), 0, QDateTime::currentDateTime(), _nickname, _text);
//}
//void MessageController::broadcastSend(QSharedPointer<User_Message> spr_srv_msg, const QSharedPointer<SrvRoom> shp_room_, const QSharedPointer<SrvUser> exclude_)
//{
// for (UserConnection* user : shp_room_->getConnectedUsers()) {
// Q_ASSERT(user);
// if (user == exclude_)
// continue;
// sendJson(user, message_);
// }
//}
void MessageController::sendJson(QSharedPointer<SrvUser> destination_, const QJsonObject& message_)
{
Q_ASSERT(destination_);
destination_->sendJson(message_);
}
void MessageController::sendMedia(QSharedPointer<SrvUser> destination_, const QByteArray& data_)
{
Q_ASSERT(destination_);
destination_->sendMedia(data_);
}
void MessageController::jsonReceived(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_)
{
Q_ASSERT(sender_);
PLOGI << QLatin1String("JSON received: ") + QJsonDocument(doc_).toJson(QJsonDocument::Compact);
if (sender_->getUserName().isEmpty())
return jsonFromLoggedOut(sender_, doc_);
if (sender_->getRoomId() == 0)
return jsonFromLoggedWoRoom(sender_, doc_);
jsonFromLoggedIn(sender_, doc_);
}
void MessageController::jsonWMediaReceived(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_, const QByteArray& data_)
{
Q_ASSERT(sender_);
PLOGI << QLatin1String("JSON received: ") + QJsonDocument(doc_).toJson(QJsonDocument::Compact);
if (sender_->getUserName().isEmpty())
return jsonFromLoggedOut(sender_, doc_);
if (sender_->getRoomId() == 0)
return jsonFromLoggedWoRoom(sender_, doc_);
jsonFromLoggedIn(sender_, doc_, data_);
}
void MessageController::jsonMediaRequest(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_)
{
Q_ASSERT(sender_);
const auto media_id = QUuid::fromString(doc_.value(QLatin1String("mediaid")).toString());
auto future = MediaSaver_Service::getInstance()->getMedia(sender_->getUserName(), media_id, sender_->getRoomId());
QFutureWatcher<decltype(future.result())> watcher;
connect(&watcher, &QFutureWatcher<decltype(future.result())>::finished, [&]() {
sendMedia(sender_, future.result());
});
}
void MessageController::jsonFromLoggedOut(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_obj_)
{
Q_ASSERT(sender_);
const QJsonValue type_val = doc_obj_.value(QLatin1String("type"));
if (type_val.isNull() || !type_val.isString())
return;
if (type_val.toString().compare(QLatin1String("signin"), Qt::CaseInsensitive) == 0)
{
const QJsonValue username_val = doc_obj_.value(QLatin1String("username"));
if (username_val.isNull() || !username_val.isString())
return;
const QString new_user_name = username_val.toString().simplified();
if (new_user_name.isEmpty())
return;
const QJsonValue password_val = doc_obj_.value(QLatin1String("password"));
if (password_val.isNull() || !password_val.isString())
return;
const QString password_str = password_val.toString().simplified();
if (password_str.isEmpty())
return;
const QJsonValue userpic_val = doc_obj_.value(QLatin1String("userpic"));
const QString userpic_str = userpic_val.toString();
DBEntity::DBUser user(new_user_name, password_str, userpic_str.toUtf8(), 0);
auto createUserResult = DBService::UserRepository::createUser(user);
createUserResult.waitForFinished();
auto result = createUserResult.result();
if (result) {
QJsonObject userinfo;
QByteArray userpicData = userpic_str.toUtf8();
QString base64Userpic = QString::fromLatin1(userpicData.toBase64());
userinfo[QStringLiteral("username")] = sender_->getUserName();
userinfo[QStringLiteral("userpic")] = base64Userpic;
userinfo[QStringLiteral("rating")] = double(sender_->getRating());
QJsonObject success_message;
success_message[QStringLiteral("type")] = QStringLiteral("login");
success_message[QStringLiteral("success")] = true;
success_message[QStringLiteral("userinfo")] = userinfo;
sendJson(sender_, success_message);
}
//userpic
//Б логика записи в БД
//вместо ответа передавать успешный логин
}
if (type_val.toString().compare(QLatin1String("login"), Qt::CaseInsensitive) == 0)
{
const QJsonValue username_val = doc_obj_.value(QLatin1String("username"));
const QJsonValue password_val = doc_obj_.value(QLatin1String("password"));
if (username_val.isNull() || !username_val.isString())
return;
const QString new_user_name = username_val.toString().simplified();
if (new_user_name.isEmpty())
return;
if (password_val.isNull() || !password_val.isString())
return;
const QString password_str = password_val.toString().simplified();
if (password_str.isEmpty())
return;
//QFuture<QSharedPointer<DBEntity::DBUser>> future_user_info = QtConcurrent::run(&DBService::UserRepository::getUserByLogin, new_user_name); //ask to db for user info
QFuture<QSharedPointer<DBEntity::DBUser>> future_user_info = DBService::UserRepository::getUserByLogin(new_user_name); //ask to DB for user info
for (const QSharedPointer<SrvUser> user : UserController::instance()->getUsersList()) { //Find duplicat username //qAsConst(server.getUsersList()))
if (user == sender_)
continue;
if (user->getUserName().compare(new_user_name, Qt::CaseInsensitive) == 0) {
PLOGI << "duplicate username or allrady loggin" + new_user_name;
QJsonObject message;
message[QStringLiteral("type")] = QStringLiteral("login");
message[QStringLiteral("success")] = false;
message[QStringLiteral("reason")] = QStringLiteral("duplicate username or allrady loggin");
sendJson(sender_, message);
return;
}
}
QCryptographicHash hash(QCryptographicHash::Sha256);
hash.addData(password_str.toUtf8());
future_user_info.waitForFinished(); //wait for DB responce
QSharedPointer<DBEntity::DBUser> user_info = future_user_info.result();
//check login and password
if (new_user_name != user_info->getLogin() || QString(hash.result().toHex()) != user_info->getPassword())
{
PLOGI << "wrong loggin or password" + new_user_name;
QJsonObject message;
message[QStringLiteral("type")] = QStringLiteral("login");
message[QStringLiteral("success")] = false;
message[QStringLiteral("reason")] = QStringLiteral("wrong loggin or password");
sendJson(sender_, message);
return;
}
//{ // Query to DB
// QSet<QString> username = { "User01","User02","User03" };
// QSet<QString> password = { "Pass01","Pass02","Pass03" };
// if (!username.contains(new_user_name)|| !password.contains(password_str)) {
// PLOGI << "wrong loggin or password" + new_user_name;
// QJsonObject message;
// message[QStringLiteral("type")] = QStringLiteral("login");
// message[QStringLiteral("success")] = false;
// message[QStringLiteral("reason")] = QStringLiteral("wrong loggin or password");
// sendJson(sender_, message);
// return;
// }
//}
//sinchronise with DB user
sender_->setUserName(user_info->getLogin());
sender_->setPassword(user_info->getPassword());
sender_->setUserpic(user_info->getUserpic());
sender_->setRating(user_info->getRating());
QByteArray userpicData = user_info->getUserpic();
QString base64Userpic = QString::fromLatin1(userpicData.toBase64());
//send loggin success + user info
QJsonObject userinfo;
userinfo[QStringLiteral("username")] = sender_->getUserName();
userinfo[QStringLiteral("userpic")] = base64Userpic;
userinfo[QStringLiteral("rating")] = double(sender_->getRating());
QJsonObject success_message;
success_message[QStringLiteral("type")] = QStringLiteral("login");
success_message[QStringLiteral("success")] = true;
success_message[QStringLiteral("userinfo")] = userinfo; //Send DTO User
sendJson(sender_, success_message);
}
}
void MessageController::jsonFromLoggedIn(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_obj_)
{
Q_ASSERT(sender_);
const QJsonValue type_val = doc_obj_.value(QLatin1String("type"));
if (type_val.isNull() || !type_val.isString())
return;
if (type_val.toString().compare(QLatin1String("roomOut"), Qt::CaseInsensitive) == 0)
{
emit userLeaveSignal(sender_);
}
if (type_val.toString().compare(QLatin1String("messageHystoryRequest"), Qt::CaseInsensitive) == 0)
{
const QJsonValue message_time_val = doc_obj_.value(QLatin1String("messagetime"));
if (message_time_val.isNull() || !message_time_val.isString())
return;
const QDateTime message_time = QDateTime::fromString(message_time_val.toString());
if (!message_time.isValid())
return;
const QJsonValue pool_size_val = doc_obj_.value(QLatin1String("poolsize"));
if (pool_size_val.isNull() || !pool_size_val.isDouble())
return;
const quint32 pool_size = pool_size_val.toInt();
emit messageHystoryRequestSignal(sender_->getRoomId(), sender_, message_time, pool_size);
}
if (type_val.toString().compare(QLatin1String("message"), Qt::CaseInsensitive) == 0)
{
if (sender_->isFloodLimit()) //implementation of flood protection mechanism
{
PLOGD << "flood protection, wait..."; //notify the server of invalid data
return;
}
sender_->setFloodLimit();
const QJsonObject messagebody_val = doc_obj_.value(QLatin1String("messagebody")).toObject();
//if (messagebody_val.isEmpty())
// return;
DTOModel::DTOMessage tempDTO;
if (!DTOModel::DTOMessage::toDTOMessageFromJson(tempDTO, messagebody_val))
return;
QSharedPointer<User_Message> spr_srv_msg = DTOModel::DTOMessage::createSrvFromDTO(QSharedPointer<DTOModel::DTOMessage>::create(tempDTO));
RoomStorage_Service::getInstance()->addMessageToRoom(sender_->getRoomId(), spr_srv_msg); //archive message
if (Helper::SwearHelper::checkForbiddenWords(spr_srv_msg->getText())) {
PLOG_INFO << "User " << spr_srv_msg->getNickname() << "uses forbidden words in room id: " << sender_->getRoomId();
return;
}
else {
emit messageToRoom(sender_->getRoomId(), sender_, messagebody_val); //Send message to all members in room
return;
}
}
if (type_val.toString().compare(QLatin1String("messageHystoryRequest"), Qt::CaseInsensitive) == 0)
{
const QJsonValue message_time_val = doc_obj_.value(QLatin1String("messagetime"));
if (message_time_val.isNull() || !message_time_val.isString())
return;
const QDateTime message_time = QDateTime::fromString(message_time_val.toString());
if (!message_time.isValid())
return;
const QJsonValue pool_size_val = doc_obj_.value(QLatin1String("poolsize"));
if (pool_size_val.isNull() || !pool_size_val.isDouble())
return;
const quint32 pool_size = pool_size_val.toInt();
emit messageHystoryRequestSignal(sender_->getRoomId(), sender_, message_time, pool_size);
}
}
void MessageController::jsonFromLoggedIn(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_obj_, const QByteArray& data_)
{
Q_ASSERT(sender_);
const QJsonValue type_val = doc_obj_.value(QLatin1String("type"));
if (type_val.isNull() || !type_val.isString())
return;
if (type_val.toString().compare(QLatin1String("exitRoom"), Qt::CaseInsensitive) == 0)
{
emit userLeaveSignal(sender_);
}
if (type_val.toString().compare(QLatin1String("message"), Qt::CaseInsensitive) == 0)
{
if (sender_->isFloodLimit()) //implementation of flood protection mechanism
{
PLOGD << "flood protection, wait..."; //notify the server of invalid data
return;
}
sender_->setFloodLimit();
QUuid media_id = QUuid::createUuid();
QJsonObject messagebody_val = doc_obj_.value(QLatin1String("messagebody")).toObject();
messagebody_val["mediaid"] = media_id.toString();
//if (messagebody_val.isEmpty())
// return;
DTOModel::DTOMessage tempDTO;
if (!DTOModel::DTOMessage::toDTOMessageFromJson(tempDTO, messagebody_val))
return;
MediaSaver_Service::getInstance()->saveMedia(sender_->getRoomId(), sender_->getUserName(), media_id, data_);
QSharedPointer<User_Message> spr_srv_msg = DTOModel::DTOMessage::createSrvFromDTO(QSharedPointer<DTOModel::DTOMessage>(&tempDTO));
RoomStorage_Service::getInstance()->addMessageToRoom(sender_->getRoomId(), spr_srv_msg); //archive message
emit messageToRoom(sender_->getRoomId(), sender_, messagebody_val); //Send message to all members in room
return;
}
}
void MessageController::jsonFromLoggedWoRoom(QSharedPointer<SrvUser> sender_, const QJsonObject& doc_obj_)
{
Q_ASSERT(sender_);
const QJsonValue type_val = doc_obj_.value(QLatin1String("type"));
if (type_val.isNull() || !type_val.isString())
return;
if (type_val.toString().compare(QLatin1String("roomListRequest"), Qt::CaseInsensitive) == 0)
{
emit roomListRequestSignal(sender_);
}
if (type_val.toString().compare(QLatin1String("createRoom"), Qt::CaseInsensitive) == 0)
{
const QJsonObject roombody_val = doc_obj_.value(QLatin1String("chatbody")).toObject();
emit createRoomSignal(sender_, roombody_val);
}
if (type_val.toString().compare(QLatin1String("roomEntry"), Qt::CaseInsensitive) == 0)
{
const QJsonValue room_val = doc_obj_.value(QLatin1String("room"));
if (room_val.isNull() || !room_val.isDouble())
return;
const quint32 room_id = room_val.toInt();
if (!room_id)
return;
emit userEntrySignal(room_id, sender_);
}
if (type_val.toString().compare(QLatin1String("changeUserPic"), Qt::CaseInsensitive) == 0) {
const QJsonValue nickname = doc_obj_.value(QLatin1String("nickname"));
if (nickname.isNull()) {
return;
}
const QJsonValue userpic = doc_obj_.value(QLatin1String("userpic"));
if (userpic.isNull()) {
return;
}
QString userpic_str = userpic.toString();
PLOGF << nickname.toString();
auto updateUserpicRes = DBService::UserRepository::updateUserPasswordUserpic(nickname.toString(), "", userpic_str.toUtf8());
updateUserpicRes.waitForFinished();
if (updateUserpicRes.result()) {
auto getUser = DBService::UserRepository::getUserByLogin(nickname.toString());
getUser.waitForFinished();
auto userFromDB = getUser.result();
QByteArray userpicData = userFromDB->getUserpic();
QString base64Userpic = QString::fromLatin1(userpicData.toBase64());
//send loggin success + user info
QJsonObject userinfo;
userinfo[QStringLiteral("username")] = sender_->getUserName();
userinfo[QStringLiteral("userpic")] = base64Userpic;
userinfo[QStringLiteral("rating")] = double(sender_->getRating());
QJsonObject success_message;
success_message[QStringLiteral("type")] = QStringLiteral("userpicChanged");
success_message[QStringLiteral("success")] = true;
success_message[QStringLiteral("userinfo")] = userinfo;
sendJson(sender_, success_message);
}
}
if (type_val.toString().compare(QLatin1String("changePassword"), Qt::CaseInsensitive) == 0) {
const QJsonValue nickname = doc_obj_.value(QLatin1String("nickname"));
if (nickname.isNull()) {
return;
}
const QJsonValue password = doc_obj_.value(QLatin1String("password"));
if (password.isNull()) {
return;
}
QString password_str = password.toString();
auto updatePasswordRes = DBService::UserRepository::updateUserPasswordUserpic(nickname.toString(), password_str, "");
updatePasswordRes.waitForFinished();
if (updatePasswordRes.result()) {
auto getUser = DBService::UserRepository::getUserByLogin(nickname.toString());
getUser.waitForFinished();
auto userFromDB = getUser.result();
QByteArray userpicData = userFromDB->getUserpic();
QString base64Userpic = QString::fromLatin1(userpicData.toBase64());
//send loggin success + user info
QJsonObject userinfo;
userinfo[QStringLiteral("username")] = sender_->getUserName();
userinfo[QStringLiteral("userpic")] = base64Userpic;
userinfo[QStringLiteral("rating")] = double(sender_->getRating());
QJsonObject success_message;
success_message[QStringLiteral("type")] = QStringLiteral("passwordChanged");
success_message[QStringLiteral("success")] = true;
success_message[QStringLiteral("userinfo")] = userinfo;
sendJson(sender_, success_message);
}
}
if (type_val.toString().compare(QLatin1String("askCurrentUser"), Qt::CaseInsensitive) == 0) {
const QJsonValue nickname = doc_obj_.value(QLatin1String("nickname"));
if (nickname.isNull()) {
return;
}
auto a = nickname.toString();
auto future = DBService::UserRepository::getUserByLogin(nickname.toString());
future.waitForFinished();
auto userFromDB = future.result();
QByteArray userpicData = userFromDB->getUserpic();
QString base64Userpic = QString::fromLatin1(userpicData.toBase64());
//send loggin success + user info
QJsonObject userinfo;
userinfo[QStringLiteral("username")] = sender_->getUserName();
userinfo[QStringLiteral("userpic")] = base64Userpic;
userinfo[QStringLiteral("rating")] = double(sender_->getRating());
QJsonObject success_message;
success_message[QStringLiteral("type")] = QStringLiteral("myUserData");
success_message[QStringLiteral("success")] = true;
success_message[QStringLiteral("userinfo")] = userinfo;
sendJson(sender_, success_message);
}
}