-
Notifications
You must be signed in to change notification settings - Fork 1
/
ClientList.cpp
635 lines (575 loc) · 17.5 KB
/
ClientList.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#include "ClientList.h"
QString &ChatClient::username()
{
return m_username;
}
void ChatClient::setUsername(QString name)
{
m_username = name;
}
QString &ChatClient::userInfo()
{
return m_userInfo;
}
void ChatClient::setUserInfo(QString info)
{
m_userInfo = info;
}
QString &ChatClient::password()
{
return m_userPassword;
}
QString &ChatClient::userState()
{
return m_userState;
}
void ChatClient::setPassword(QString pass)
{
m_userPassword = pass;
}
void ChatClient::setUserState(QString state)
{
m_userState = state;
}
QTcpSocket *ChatClient::userSocket() const
{
return m_userSocket;
}
void ChatClient::setUserSocket(QTcpSocket *socket)
{
m_userSocket = socket;
}
QString &ChatChannel::name()
{
return m_name;
}
void ChatChannel::setName(QString name)
{
m_name = name;
}
QString &ChatChannel::description()
{
return m_description;
}
void ChatChannel::setDescription(QString desc)
{
m_description = desc;
}
void ChatChannel::addClient(QString username)
{
userList.append(username);
}
void ChatChannel::deleteClient(QString username)
{
userList.removeAll(username);
}
bool ChatChannel::hasClient(QString username)
{
return userList.contains(username);
}
void ChatChannel::deleteAllClients()
{
userList.clear();
}
QString &ChatChannel::topic()
{
return m_topic;
}
void ChatChannel::setTopic(QString topic)
{
m_topic = topic;
}
DBManager::DBManager(QObject *parent) :
QObject(parent),
m_clientTableName("clients"),
m_channelTableName("channels"),
m_membershipTableName("membership"),
m_DBFileName("chat.db")
{
connectToDB();
}
DBManager::~DBManager()
{
disconnectDB();
}
void DBManager::connectToDB()
{
QString msg;
QFile file;
file.setFileName(m_DBFileName);
m_DB = QSqlDatabase::addDatabase("QSQLITE");
if(file.exists())
{
m_DB.setDatabaseName(m_DBFileName);
if(!m_DB.open())
{
msg = m_DB.lastError().text();
emit logMessage(esFatal, msg);
}
else
{
msg = "DataBase opened.";
emit logMessage(esNotify, msg);
}
}
else
{
m_DB.setDatabaseName(m_DBFileName);
if(!m_DB.open())
{
msg = m_DB.lastError().text();
emit logMessage(esFatal, msg);
}
else
{
msg = "DataBase not found, creating new DataBase";
emit logMessage(esNotify, msg);
}
createDB();
}
}
void DBManager::disconnectDB()
{
m_DB.close();
}
bool DBManager::createClientsTable()
{
QSqlQuery query;
QString str = "CREATE TABLE " + m_clientTableName + " ( "
"name VARCHAR(25) PRIMARY KEY ASC, "
"password VARCHAR(20), "
"info VARCHAR(200), "
"status VARCHAR(140) "
");";
return query.exec(str);
}
bool DBManager::createChannelsTable()
{
QString msg;
QSqlQuery query;
QString str = "CREATE TABLE " + m_channelTableName+ " ( "
"name VARCHAR(25) PRIMARY KEY ASC, "
"topic VARCHAR(200), "
"description VARCHAR(200)"
");";
return query.exec(str);
}
bool DBManager::createMembershipTable()
{
QSqlQuery query;
QString str = "CREATE TABLE " + m_membershipTableName + " ( "
"channel VARCHAR(25), "
"client VARCHAR(25) "
");";
return query.exec(str);
}
void DBManager::createDB()
{
QString msg;
if (!createClientsTable() ||
!createChannelsTable() ||
!createMembershipTable())
{
msg = "Error creating tables";
emit logMessage(esFatal, msg);
}
else
{
msg = "Tables 'clients', 'channels', 'membership' created succesfully";
emit logMessage(esNotify, msg);
}
ChatChannel channel;
channel.setName("main");
channel.setDescription("Main channel, contains all users");
channel.setTopic("Gimme fu, gimme fai, gimme dabajabazza");
setChannel(channel);
}
bool DBManager::hasClient(QString username)
{
QSqlQuery query;
QString str = QString("SELECT * FROM '%1' WHERE name = '%2';")
.arg(m_clientTableName)
.arg(username);
if (!query.exec(str))
{
QString msg("SQL query error in getting client: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
else
return query.next();
return false;
}
ChatClient DBManager::getClient(QString username)
{
ChatClient client;
QSqlQuery query;
QString str = QString("SELECT name, password, info, status FROM '%1' WHERE name = '%2';")
.arg(m_clientTableName)
.arg(username);
if (!query.exec(str) || !query.next())
{
QString msg("SQL query error in getting client: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
else
{
// create new client and fill it with results of query
// maybe we should use smart pointer here
client.setUsername(query.value(0).toString());
client.setPassword(query.value(1).toString());
client.setUserInfo(query.value(2).toString());
client.setUserState(query.value(3).toString());
}
return client;
}
//"REPLACE INTO dummies (rowid, name, info)"
//"VALUES (null, '%1', '%2');"
void DBManager::setClient(ChatClient &client)
{
QSqlQuery query;
QString q = QString("REPLACE INTO %1 (rowid, name, password, info, status) "
"VALUES (null, '%2', '%3', '%4', \"%5\");")
.arg(m_clientTableName)
.arg(client.username())
.arg(client.password())
.arg(client.userInfo())
.arg(client.userState());
if (!query.exec(q))
{
QString msg("SQL query error in setting client: \"%1\"");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
}
bool DBManager::hasChannel(QString channelName)
{
QSqlQuery query;
QString str = QString("SELECT * FROM '%1' WHERE name = '%2';")
.arg(m_channelTableName)
.arg(channelName);
if (!query.exec(str))
{
QString msg("SQL query error in getting channel: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
return false;
}
else
return query.next();
}
ChatChannel DBManager::getChannel(QString channelName)
{
ChatChannel channel;
QSqlQuery query;
QString str = QString("SELECT name, topic, description FROM '%1' WHERE name = '%2';")
.arg(m_channelTableName)
.arg(channelName);
if (!query.exec(str) || !query.next())
{
QString msg("SQL query error in getting channel: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
else
{
// create new client and fill it with results of query
// maybe we should use smart pointer here
channel.setName(query.value(0).toString());
channel.setTopic(query.value(1).toString());
channel.setDescription(query.value(2).toString());
}
return channel;
}
void DBManager::setChannel(ChatChannel &channel)
{
QSqlQuery query;
QString q = QString("REPLACE INTO %1 (rowid, name, topic, description) "
"VALUES (null, '%2', '%3', '%4')")
.arg(m_channelTableName)
.arg(channel.name())
.arg(channel.topic())
.arg(channel.description());
if (!query.exec(q))
{
QString msg("SQL query error in setting channel: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
}
bool DBManager::isMembership(QString username, QString channelName)
{
QSqlQuery query;
QString q = QString("SELECT * FROM %1 WHERE channel = '%2' AND client = '%3'")
.arg(m_membershipTableName)
.arg(channelName)
.arg(username);
if (!query.exec(q))
{
QString msg("SQL query error in getting membership: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
return false;
}
else
return query.next();
}
void DBManager::addMembership(QString username, QString channelName)
{
QSqlQuery query;
QString q = QString("INSERT INTO %1 (rowid, client, channel) "
"VALUES (null, '%2', '%3')")
.arg(m_membershipTableName)
.arg(username)
.arg(channelName);
if (!query.exec(q))
{
QString msg("SQL query error in adding membership: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
}
void DBManager::deleteMembership(QString username, QString channel)
{
QSqlQuery query;
QString q = QString("DELETE FROM '%1' WHERE client = '%3' AND channel = '%4';")
.arg(m_membershipTableName)
.arg(username)
.arg(channel);
if (!query.exec(q))
{
QString msg("SQL query error in deleting membership: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
}
}
QVector<ChatChannel> DBManager::getChannelList()
{
QVector<ChatChannel> channels;
ChatChannel tempChannel;
QSqlQuery query;
QString q = QString("SELECT name, description, topic FROM %1")
.arg(m_channelTableName);
if (!query.exec(q) || !(query.next()))
{
QString msg("SQL query error in getting channel list: %1");
msg.arg(query.lastError().text());
emit logMessage(esWarning, msg);
// return channels;
}
do
{
tempChannel.setName(query.value(0).toString());
tempChannel.setDescription(query.value(1).toString());
tempChannel.setTopic(query.value(2).toString());
channels.append(tempChannel);
} while (query.next());
return channels;
}
ChatChannel GeneralClientList::getChannel(QString &channelName)
{
ChatChannel result;
for (int i = 0; i < m_channelList.count(); ++i)
if (m_channelList[i].name() == channelName)
result = m_channelList[i];
return result;
}
bool GeneralClientList::hasChannel(QString channelName)
{
bool found = false;
for (int i = 0; i < m_channelList.count(); ++i)
if (m_channelList[i].name() == channelName)
{
found = true;
break;
}
return found;
}
ChatClient GeneralClientList::getClient(const QString &username)
{
return m_generalClientList.value(username);
}
bool GeneralClientList::hasClient(QString username)
{
return m_generalClientList.contains(username);
}
QMap<QString, QString> GeneralClientList::getChannelsForClient(QString username)
{
QMap<QString, QString> channels;
for (int i = 0; i < m_channelList.count(); ++i)
if (m_DB.isMembership(username, m_channelList[i].name()))
channels.insert(m_channelList[i].name(), m_channelList[i].description());
return channels;
}
QStringList GeneralClientList::getClientsForChannel(QString channelName)
{
QStringList result;
for (int i = 0; i < m_channelList.count(); i++)
if (m_channelList[i].name() == channelName)
{
result = m_channelList[i].userList;
break;
}
return result;
}
QMap<QString, QString> GeneralClientList::getAllChanells()
{
QMap<QString, QString> channels;
for (int i = 0; i < m_channelList.count(); ++i)
channels.insert(m_channelList[i].name(), m_channelList[i].description());
return channels;
}
GeneralClientList::RegResult GeneralClientList::registrate(QString username, QString password)
{
if (m_DB.hasClient(username))
return GeneralClientList::rrOccupiedUsername;
//check username for not conflicting with our architecture
//if conflicts - return GeneralClientList::rrBadUsername
ChatClient newClient;
newClient.setUsername(username);
newClient.setPassword(password);
newClient.setUserInfo("Default userinfo for user " + username + "."); //default userinfo
newClient.setUserState("Offline");
m_DB.setClient(newClient);
m_DB.addMembership(username, "main");
return GeneralClientList::rrRegSuccess;
}
GeneralClientList::GeneralClientList(QObject *parent): QObject(parent)
{
//readChannelsFromDB();
connect(&m_DB, SIGNAL(logMessage(ErrorStatus, QString &)), this, SLOT(replyLog(ErrorStatus, QString&)));
}
GeneralClientList::AuthResult GeneralClientList::authorize(QString username, QString password, QTcpSocket *socket)
{
//comparing authorization data
//if the client doesn't exists in our DB - abort
if (!m_DB.hasClient(username))
return GeneralClientList::arWrongAuthData;
//if password is incorrect - abort
ChatClient authClient = m_DB.getClient(username);
if (password != authClient.password())
return GeneralClientList::arWrongAuthData;
//if client is allready authorized - abort
if (this->hasClient(username))
return GeneralClientList::arAllreadyAuthorized;
//ok, authorization tests passed
//setting his socket ans status
authClient.setUserSocket(socket);
//add client to general list
m_generalClientList.insert(username, authClient);
//and add him to channel lists
for (int i = 0; i < m_channelList.count(); ++i)
if (m_DB.isMembership(username, m_channelList[i].name()))
m_channelList[i].addClient(username);
//ok, thats all
return GeneralClientList::arAuthSuccess;
}
void GeneralClientList::disconnect(QString username)
{
if (!this->hasClient(username))
return;
ChatClient client = getClient(username);
client.setUserState("Offline");
updateClient(client);
client.userSocket()->close();
//socket->close();
//delete client from channels
for (int i = 0; i < m_channelList.count(); ++i)
if (m_channelList[i].hasClient(username))
m_channelList[i].deleteClient(username);
//delete client from general list
m_generalClientList.remove(username);
}
void GeneralClientList::disconnectAll()
{
QMutableVectorIterator<ChatChannel> itr(m_channelList);
while(itr.hasNext())
itr.next().deleteAllClients();
m_generalClientList.clear();
}
GeneralClientList::userSocketsList_t *GeneralClientList::getAllSockets()
{
GeneralClientList::userSocketsList_t *result = new userSocketsList_t;
foreach(const ChatClient &itr, m_generalClientList.values())
result->append(itr.userSocket());
return result;
}
void GeneralClientList::joinChannel(QString username, QString channelName)
{
/*if (!hasClient(username)) //joining channel supported only for connected clients
return;*/
if (m_DB.isMembership(username, channelName)) // we dont need to join channel if we are allready in it
return;
m_DB.addMembership(username, channelName);
for (int i = 0; i < m_channelList.count(); ++i)
if (channelName == m_channelList[i].name())
{
m_channelList[i].addClient(username);
break;
}
//we need to refresh list of channel membership on client-part
}
void GeneralClientList::leaveChannel(QString username, QString channelName)
{
if (channelName == "main" || !m_DB.isMembership(username, channelName))
return;
for (int i = 0; i < m_channelList.count(); i++)
{
if (m_channelList[i].name() == channelName)
{
m_channelList[i].userList.removeAll(username);
m_DB.deleteMembership(username, channelName);
break;
}
}
}
GeneralClientList::CreateChannelResult GeneralClientList::createChannel(QString channelName,
QString description,
QString topic)
{
int maxChannelCount = 50;
if (m_channelList.count() >= maxChannelCount)
return ccrTooManyChannels;
for (int i = 0; i < m_channelList.count(); i++)
if (m_channelList[i].name() == channelName)
return ccrBadName;
ChatChannel newChannel;
newChannel.setDescription(description);
newChannel.setName(channelName);
newChannel.setTopic(topic);
m_DB.setChannel(newChannel);
m_channelList.append(newChannel);
return ccrSuccess;
}
void GeneralClientList::updateClient(ChatClient &client)
{
//update client entry in DB
m_DB.setClient(client);
//remove current client from clientlist
m_generalClientList.remove(client.username());
//insert new client to clientlist
m_generalClientList.insert(client.username(), client);
}
void GeneralClientList::updateChannel(ChatChannel &channel)
{
//update channel info in DB
m_DB.setChannel(channel);
//remove channel info in channel list
for (int i = 0; i < m_channelList.count(); i++)
if (m_channelList[i].name() == channel.name())
{
m_channelList.remove(i);
break;
}
//insert new channel into channel list
m_channelList.push_back(channel);
}
void GeneralClientList::replyLog(ErrorStatus status, QString ¶m)
{
emit logMessage(status, param);
}
void GeneralClientList::readChannelsFromDB()
{
m_channelList = m_DB.getChannelList();
}