-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.cpp
More file actions
3430 lines (2757 loc) · 108 KB
/
Copy pathuser.cpp
File metadata and controls
3430 lines (2757 loc) · 108 KB
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "user.h"
#include "logging/loggingcategories.h"
User::User(ChannelModel *channelModel, ChatModel *chatModel,
ParticipantModel* currentChannelParticipant, ConnectedUsersModel *connectedUsersModel, MyServersModel* myServersModel,
SoundManager* sounderManager, SettingsManager* settingsManager,
ClientUserManager *clientuserManager, IdentityManager *identityManager,
RelationshipManager* relationshipManager, Database* database,
AttachmentImageProvider* attachmentImageProvider,
CameraCapture* cam, AudioCapture *mic, AudioSpeaker* speaker,
QObject *parent)
: QObject{parent}, m_channelModel(channelModel), m_voiceChatModel(chatModel),
m_currentChannelParticipant(currentChannelParticipant), m_connectedUsersModel(connectedUsersModel),
m_myServersModel(myServersModel),
m_soundManager(sounderManager), m_settingsManager(settingsManager),
m_clientUserManager(clientuserManager), m_identityManager(identityManager),
m_relationshipManager(relationshipManager), m_database(database),
m_attachmentImageProvider(attachmentImageProvider),
m_cam(cam), m_mic(mic), m_speaker(speaker)
{
qCInfo(_app) << "starting app";
qCInfo(_app) << "using BeanChatCommon version " << BeanChatCommon::Protocol::Version;
//read or generate identitiy if not exsit
if(!m_identityManager->load())
{
qCFatal(_identity) << "failed to load and generate default identity.";
}
qCInfo(_identity) << "Loaded identities count= " << m_identityManager->identities().count();
qCDebug(_identity) << "found identities:";
for(auto& identity : m_identityManager->identities())
{
qCDebug(_identity) << "name= " <<identity.name
<< " pub:" <<identity.publicKeyBase64()
<< "created at=" <<identity.createdAt;
}
//notify QML identity loaded/changed
emit myIdentityChanged();
if (!m_opus.initialize(OPUS_DEFAULT_SAMPLE_RATE,
OPUS_DEFAULT_CHANNELS,
OPUS_DEFAULT_BITRATE))
{
qCFatal(_opus) << "Failed to initialize Opus";
}
//video decoder
m_videoDecoder.open();
connect(
&m_videoDecoder,
&FFmpegDecoder::imageReady,
this,
[this](const QImage &image)
{
if(m_decodeQueue.isEmpty())
return;
quint64 senderId = m_decodeQueue.dequeue();
ClientUser *sender = m_currentChannelParticipant->findUser(senderId);
if(!sender)
{
qCWarning(_app) << "sender of video not found, id=" << senderId;
return;
}
VideoSink *sink = m_currentChannelParticipant->videoSink(sender->id());
if(!sink)
{
qCWarning(_app) << "video sink of current participant not found for senderid="<<sender->id();
return;
}
sink->setImage(image);
});
//settings
initOrLoadSettings();
//load all saved servers from database.
qCInfo(_app) << "loading all saved servers.";
QVariantList servers = m_database->getAll("MyServers");
for (const QVariant &v : servers)
{
QVariantMap row = v.toMap();
qCInfo(_database)
<< row["id"]
<< row["name"]
<< row["avatarPath"]
<< row["ip"]
<< row["port"];
//add to myServers model
m_myServersModel->addServer(row["name"].toString(),
row["avatarPath"].toString(),
row["ip"].toString(),
row["port"].toString(),
false, //set IsActive FALSE
row["id"].toUInt()); //set server index
}
//connect clientUserManager to models when user removed, models obey
connect(m_clientUserManager, &ClientUserManager::userRemoved, m_channelModel, &ChannelModel::removeUser);
connect(m_clientUserManager, &ClientUserManager::userRemoved, m_currentChannelParticipant, &ParticipantModel::removeUser);
//we dont remove user even they went offline for now (due to server sends offline users)
// connect(m_clientUserManager, &ClientUserManager::userRemoved, m_connectedUsersModel, &ConnectedUsersModel::removeUser);
connect(m_clientUserManager, &ClientUserManager::cleared, m_channelModel, &ChannelModel::clear);
connect(m_clientUserManager, &ClientUserManager::cleared, m_connectedUsersModel, &ConnectedUsersModel::clear);
connect(m_clientUserManager, &ClientUserManager::cleared, m_currentChannelParticipant, &ParticipantModel::clear);
//setup TCP socket
connect(&socket,
&QTcpSocket::readyRead,
this,
&User::onTcpReadyRead);
connect(&socket, &QTcpSocket::connected,
this, [&]()
{
LoginRequestPacket login;
if(m_myUsername=="")
{
//do a default and random name..
setMyUsername("BeanUser"+QString::number(QRandomGenerator::global()->bounded(100)));
}
login.username = myUsername();
login.status =myStatus();
if(!m_identityManager->currentIdentity())
{
qCInfo(_app) << "connect failed. no identity selected... create one";
if(m_identityManager->createIdentity("Default"+QString::number(QRandomGenerator::global()->bounded(100))))
{
qCInfo(_app) << "we create one new identity for you";
}
else
{
qCWarning(_app) << "you didnt have an identity and sadly we couldn't create one for you!";
return;
}
}
login.publicKey = m_identityManager->currentIdentity()->publicKey;
//system info.
login.appVersion = myAppVersion();
login.appProtocolVersion = BeanChatCommon::Protocol::Version;
login.buildType = buildType();
login.machineId = QString(QSysInfo::machineUniqueId().toHex());
login.machineName = QSysInfo::machineHostName();
login.osName = platformName();
login.osVersion = QSysInfo::prettyProductName();
//stop reconnect timer
if(m_reconnectTimer.isActive())
{
m_reconnectTimer.stop();
//re-join to previous channel.
qCInfo(_app) << "reconnected lets do login.";
if(m_lastChannelId>0)
{
qCInfo(_app) << "rejoin old channel, filling login request with previous voice channel id="<<m_lastChannelId;
login.joinChannelId=m_lastChannelId;
login.joinChannelPassword=m_lastChannelPassword;
}
}
qCInfo(_tcp) << "sending login request.. will wait for response.. connecting server is "
<< m_serverIp << ":" << m_serverPort << " name=" << myUsername() << " identity=" << myIdentity() ;
sendPacket(PacketType::LoginRequest,login);
});
connect(&socket, &QTcpSocket::disconnected,
this, &User::disconnect);
connect(&socket, &QTcpSocket::errorOccurred,
this, &User::onSocketError);
//try to bind for udp with several attemps if failed do qFatal
bool bound = false;
for (int i = 0; i < 3; ++i)
{
if (m_udpSocket.bind())
{
bound = true;
break;
}
qCWarning(_udp) << "Bind attempt " << (i + 1)
<< " failed: " << m_udpSocket.errorString();
}
if (!bound)
qCFatal(_udp) << "Failed to bind UDP socket after 3 attempts.";
connect(&m_udpSocket,
&QUdpSocket::readyRead,
this,
&User::onUdpReadyRead);
//reconnect when connection lost
m_reconnectTimer.setInterval(TRY_RECONNECT_TIMER_INTERVAL);
connect(&m_reconnectTimer, &QTimer::timeout, this, [&]()
{
if(connectionStatus()==UserConnectionStatus::Disconnected)
{
if(m_reconnectTryCount<TRY_RECONNECT_MAX_COUNT)
{
m_reconnectTryCount++;
qCInfo(_app) << "================== RE-CONNECTING ================";
qCInfo(_app) << "trying to re-connect lost connection... try number=" << m_reconnectTryCount;
connectToServer(false,m_lastServerIp,m_lastServerPort);
}
else
{
qCInfo(_app) << "reconnect hit max count, stopping reconnet timer.";
m_reconnectTimer.stop();
}
}
});
//when request register sent to to udp server, would check evey xSeconds for last activty time, when it exceed from an amount (didn't receive any UDP packet voice/video/ping) assuming server is down or connection is lost.
m_udpConnectionTimeout.setInterval(UDP_CONNECTION_LOST_TIMER_INTERVAL);
connect(&m_udpConnectionTimeout, &QTimer::timeout,
this, [&]()
{
if(isConnectedToServer() && (m_lastUdpActivity.elapsed()>14000 || m_lastTcpActivity.elapsed()>270000)) //max is 14s for udp AND 4.5minutes for tcp
{
qCInfo(_udp) << "server didn't send ping request for a while, so assuming connection has lost lastUdpActivity=" << m_lastUdpActivity.elapsed() << " lastTcpActivity="<<m_lastTcpActivity.elapsed();
emit notificationRequested(NotificationType::Error,
"Connection Lost",
NotificationId::ConnectionLost,
NotificationDuration::Long);
emit youConnectionLost();
//close connection, sometimes user may stuck in middle of connecting and connection lost
//so here we make sure close connection even we dont show connection lost messag to them
disconnect(); //make sure tcp disconnects and ui show disconnected elemnts
//try to reconnect
m_reconnectTimer.start();
m_reconnectTryCount=0;
}
});
/*
* make a connection between channelmodel to participantModel (center of screen [those rectangles]) sync with channelModel user's talking status
* channelModel -> (which contineusly check users of current channel to find out who stopped talking due to last talking time)
*/
connect(m_channelModel,
&ChannelModel::userTalkingStatus,
this,
[this](quint64 userId, bool talking)
{
if (ClientUser *user = m_clientUserManager->user(userId))
user->setIsTalking(talking);
});
//setup update checker
m_updateChecker = new UpdateChecker(&m_badgeManager,this);
if(m_updateChecker)
{
connect(m_updateChecker,
&UpdateChecker::updateAvailable,
this,
[this](const LatestResponse &response)
{
qCInfo(_app) << "update available, update to " << response.latestVersion().toString() << "current version = " << myAppVersion();
emit showImportantNotifierBar("Update "+ response.latestVersion().toString() + " is available",
ImportantNotificationColor::Blue);
});
connect(m_updateChecker,
&UpdateChecker::noUpdateAvailable,
this,
[]()
{
qCInfo(_app) << "Already up to date.";
});
connect(m_updateChecker,
&UpdateChecker::errorOccurred,
this,
[this](const QString &err)
{
qCWarning(_app) << "error to check for update err=" << err;
// emit showImportantNotifierBar("Failed to check for update, "+err,
// ImportantNotificationColor::Red);
});
connect(m_updateChecker,
&UpdateChecker::errorLoadingBadges,
this,
[this](const QString &err)
{
qCWarning(_app) << "error to load badges err=" << err;
});
connect(m_updateChecker,
&UpdateChecker::badgesDownloaded,
this,
[]()
{
qCInfo(_app) << "badges downloaded";
});
//check for update at startup
QString targetPlatform = platformName();
if(targetPlatform=="Windows") targetPlatform="windows-x64";
else if(targetPlatform=="Linux") targetPlatform="linux-x64";
else if(targetPlatform=="Android") targetPlatform="android-arm8";
m_updateChecker->checkForUpdates(targetPlatform, myAppVersion()); //check for updates and get badges
}
else
qCCritical(_app) << "failed to setup update manager.";
}
void User::joinChannel(quint64 channelId, const QString& password, bool isTextChannel)
{
if(isTextChannel)
qCInfo(_tcp) << "sending joinTextChannel request";
else
qCInfo(_tcp) << "sending join channel request";
JoinChannelPacket join;
join.channelId = channelId;
join.password = password;
if(isTextChannel)
{
sendPacket(PacketType::JoinTextChannel,join);
}
else
{
sendPacket(PacketType::JoinChannel,join);
m_lastChannelId=channelId;
m_lastChannelPassword=password;
}
}
int User::isChannelLocked(quint64 channelId)
{
ChannelItem* channel = m_channelModel->findChannel(channelId);
if(channel)
return channel->isLocked;
else
qCWarning(_app) << "invalid channel id to check isLocked.";
return -1;
}
QString User::serverName() const
{
return m_receivedServerInfo.name;
}
QString User::serverWebsite() const
{
return m_receivedServerInfo.website;
}
QString User::serverAvatarHash() const
{
return m_receivedServerInfo.avatarHash;
}
QString User::serverMaxUsers() const
{
return QString::number(m_receivedServerInfo.maxUsers);
}
QString User::serverVersion() const
{
return m_receivedServerInfo.version;
}
QString User::serverUptime() const
{
qint64 seconds = m_receivedServerInfo.startTime.secsTo(QDateTime::currentDateTimeUtc());
qint64 days = seconds / 86400;
seconds %= 86400;
if (days > 0)
return QString("%1 day%2").arg(days).arg(days == 1 ? "" : "s");
qint64 hours = seconds / 3600;
seconds %= 3600;
if (hours > 0)
return QString("%1 hour%2").arg(hours).arg(hours == 1 ? "" : "s");
qint64 minutes = seconds / 60;
seconds %= 60;
if (minutes > 0)
return QString("%1 minute%2").arg(minutes).arg(minutes == 1 ? "" : "s");
if (seconds > 0)
return QString("%1 second%2").arg(seconds).arg(seconds == 1 ? "" : "s");
return QString();
}
void User::moveUser(quint64 userId, quint64 channelId, const QString& password)
{
qCInfo(_tcp) << "sending move user request";
MoveUserPacket mv;
mv.channelId=channelId;
mv.userId=userId;
mv.channelPassword=password;
sendPacket(PacketType::MoveUser,mv);
}
void User::connectToServer(bool saveThisConnection, const QString& serverIp, const QString& str_serverPort)
{
setConnectionStatus(UserConnectionStatus::Connecting);
qCInfo(_app) << "connect to server.";
//if user is connected to somewhere, disconnect before new connection
if(isConnectedToServer())
disconnect();
//check is server saved or is temporary?
if(m_connectedServerId_onDb==-1) //server is temporary
{
qCInfo(_app) << "server connection is termporary. connectedServerId DB=" << m_connectedServerId_onDb;
}
//convert ports to quint64
bool ok = false;
quint64 serverPort = str_serverPort.toULongLong(&ok);
if(!ok)
{
qCWarning(_app) << "Invalid port number, port=" << str_serverPort;
emit notificationRequested(NotificationType::Error,
"Invalid port number.");
return;
}
//for reonnect when connection lost
m_lastServerIp=serverIp;
m_lastServerPort=str_serverPort;
//validate entered ip and ports
//code here
//save this server if was not in myServers
int serverId = m_myServersModel->doesServerExists(serverIp, str_serverPort);
if(serverId==-1) //server doesnt exist on list
{
QString serverName= USER_DEFAULT_SERVER_NAME;
int serverDbIndex = -1;
if(saveThisConnection)
{
//save server into local storage
bool result = m_database->insert("MyServers",
{
{"name", serverName},
{"ip", serverIp},
{"port", str_serverPort}
});
if(result)
{
qCInfo(_app) << "server saved to myServers";
QVariantMap serverInfo = m_database->getServer(serverIp,str_serverPort);
if (serverInfo.isEmpty())
{
qCWarning(_app) << "while reading data from recently added server got: Server not found";
return;
}
serverDbIndex = serverInfo["id"].toInt();
m_connectedServerId_onDb =serverDbIndex;
serverName = serverInfo["name"].toString();
setMyServerName(serverName);
}
else
qCCritical(_app) << "failed to save server to myServers.";
}
//add to myServers model and set isActive to TRUE
m_myServersModel->addServer(serverName,
"", //avatarPath, we haven't server's avatar
serverIp,
str_serverPort,
true, //is Active
serverDbIndex);
}
else //server exists, so just set server active
m_myServersModel->setIsActive(serverId);
//update servername for QML
if(serverId!=-1) //server exists just try to read server name from myServers table. otherwise when adding server would setServerName.
{
QVariantMap serverInfo = m_database->getServer(serverIp,str_serverPort);
if (!serverInfo.isEmpty())
setMyServerName(serverInfo["name"].toString());
else
setMyServerName("The Server");
}
//store in variables for different parts of app
m_serverIp=serverIp;
m_serverPort=serverPort;
//connect to TCP
socket.connectToHost(
m_serverIp,
m_serverPort);
//reset flag for next use.
m_switchingServer=false;
}
void User::updateSavedServer(quint64 serverId, quint64 dbIndex, const QString& name, const QString& ip, const QString& port)
{
qCInfo(_app) << "update saved server.";
bool res = m_database->update("MyServers",
dbIndex,
{
{"name", name},
{"ip", ip},
{"port", port.toInt()}
});
if(res)
{
emit notificationRequested(NotificationType::Success,
"MyServer updated.");
qCInfo(_app) << "myserver updated.";
//update model data.
m_myServersModel->updateServer(serverId,name,ip,port);
//update servername on local variable too
setMyServerName(name);
}
else
{
qCWarning(_app) << "failed to update MyServer.";
emit notificationRequested(NotificationType::Error,
"Failed to update MyServer.");
}
}
void User::deleteSavedServer(quint64 serverId, quint64 serverDbIndex)
{
qCInfo(_app) << "delete saved server.";
if(serverDbIndex!=-1) //server is not saved in database. just delete it from model.
{
bool res = m_database->remove("MyServers",serverDbIndex);
if(res)
{
qCInfo(_app) << "server deleted from MyServers.";
emit notificationRequested(NotificationType::Success,
"Server deleted from MyServers.");
//delete saved avatars in that server's avatar directory
qCInfo(_app) << "trying to delete avatars of that server: target path = " << SAVE_AVATAR_PATH+QString::number(serverDbIndex);
QDir dir(SAVE_AVATAR_PATH+QString::number(serverDbIndex));
if (dir.exists())
{
if (!dir.removeRecursively())
qCWarning(_app) << "Failed to remove avatar.";
}
else
qCInfo(_app) << "that path avatar doesn't exists.";
}
else
{
qCWarning(_app) << "Failed to delete server from MyServers.";
emit notificationRequested(NotificationType::Error,
"Failed to delete server from MyServers.");
}
}
//anyway delete from model
m_myServersModel->removeServer(serverId);
}
bool User::hasBadge(quint64 userId, BadgeManager::Badge badge) const
{
ClientUser* usr = m_clientUserManager->user(userId);
if(!usr)
{
qCWarning(_app) << "user not found to check badge";
return false;
}
bool result= m_badgeManager.hasBadge(usr->identity(), static_cast<quint32>(badge));
qCInfo(_app) << usr->id() << " has badge : " << static_cast<int>(badge) << " has: " << result;
return result;
}
void User::switchOrConnectToServer(const QString &serverIp, const QString &str_serverPort, int serverId)
{
qCInfo(_app) << "switch OR connectToServer server-id: " << serverId;
//tell myServers model im connected to this server.
m_myServersModel->setIsActive(serverId);
m_switchingServer=true;
//do normal connectToServer things
connectToServer(false, serverIp,str_serverPort);
}
void User::disconnect()
{
// Already completely disconnected. (to prevent multiple call for disconnect while is not connected)
if (socket.state() == QAbstractSocket::UnconnectedState &&
m_udpSocket.state() == QAbstractSocket::UnconnectedState)
{
qCWarning(_app) << " disconnect called but we aren't connected anywhere.";
return;
}
qCInfo(_app) << "disconnect.";
setConnectionStatus(UserConnectionStatus::Disconnecting);
emit notificationRequested(NotificationType::Error,
"Disconnected",
NotificationId::Disconnected,
NotificationDuration::Short);
emit youDisconnected();
//disocnnect sockets.
socket.disconnectFromHost();
m_udpSocket.disconnectFromHost();
resetVariables();
}
void User::createChannel(QString channelName, QString password, bool saveMessages, bool isVoiceChannel)
{
qCInfo(_tcp) << "sending create channel request";
CreateChannelPacket cc;
cc.name = channelName;
cc.password= password;
cc.saveChats=saveMessages;
cc.type= isVoiceChannel ? BeanChatCommon::ChannelType::Type::Voice
: BeanChatCommon::ChannelType::Type::Text;
sendPacket(PacketType::CreateChannel,cc);
}
void User::sendVoicePcm(
const QByteArray& pcm)
{
if(!isConnectedToServer() || myChannelId()==0)
return;
if(muteMicrophone() || muteHeadphone())
{
// qCCritical(_app) << "microphone or headphone is muted, send voice abort..";
return;
}
if(m_myId < 0)
{
qCCritical(_app) << "myId is invalid.";
return;
}
// Accumulate microphone PCM
m_sendPcmBuffer.append(pcm);
bool sentPacket = false;
constexpr int FRAME_BYTES = 960 * sizeof(qint16);
// Encode every complete 20ms frame
while (m_sendPcmBuffer.size() >= FRAME_BYTES)
{
QByteArray frame = m_sendPcmBuffer.left(FRAME_BYTES);
m_sendPcmBuffer.remove(0, FRAME_BYTES);
VoicePacket voice;
voice.senderId =
static_cast<quint64>(myId());
voice.sequence =
++m_sequence;
voice.audioData = m_opus.encode(frame);
if (voice.audioData.isEmpty())
continue;
#if D_PRINT_VOICE_INFO
qDebug() << "sending Opus:" << voice.audioData.size()
<< "frame:" << frame.size()
<< "pcm raw " << pcm.size();
#endif
QByteArray data;
QDataStream out(
&data,
QIODevice::WriteOnly);
out << PacketType::UdpVoiceData;
out << voice;
sendUdp(data);
sentPacket = true;
}
if (!sentPacket)
return;
//update isTalking ourself
ClientUser *senderUser = m_channelModel->getUser(m_myChannelId, myId());
if(!senderUser)
return;
if (!senderUser->isTalking())
senderUser->setIsTalking(true);
m_channelModel->restartVoiceTimer(myId());
}
void User::sendMessage(const QString& message, quint64 channelId)
{
qCInfo(_tcp) << "sending simple message ";
SendMessagePacket sm;
sm.text = message;
if(channelId==0) //this messag sent for voice channel's chat
sm.targetTextChannelId=0;
else //it's for textChannel chat
sm.targetTextChannelId = channelId; //if id is a voice channel id server would ignore it and just check user's current channel
sm.type = Msg::Type::Text;
sm.attachmentId=0;
sendPacket(PacketType::ChatMessage, sm);
}
void User::sendMessage(const QString& message,quint64 attachId, const QUrl &url, quint64 channelId)
{
qCInfo(_tcp) << "sending message request with attachid="<<attachId;
SendMessagePacket sm;
sm.text = message;
sm.targetTextChannelId = channelId; //if id is a voice channel id server would ignore it and just check user's current channel
QMimeDatabase db;
QString name = db.mimeTypeForFile(url.toLocalFile()).name();
if (name.startsWith("image/"))
{
if(name.contains("gif"))
sm.type=Msg::Type::AnimatedImage;
else
sm.type = Msg::Type::Image;
}
else if (name.startsWith("video/"))
{
sm.type = Msg::Type::Video;
}
else if (name.startsWith("audio/"))
{
sm.type = Msg::Type::Audio;
}
else
{
sm.type = Msg::Type::File;
}
sm.attachmentId=attachId;
sendPacket(PacketType::ChatMessage,sm);
}
void User::sendFile(const QString &filePath, quint64 channelId)
{
if (m_uploadFile.isOpen())
{
qWarning() << "Already uploading a file.";
emit sendFileResult(false, "Alread uploading a file... try later",0);
return;
}
QString localPath = QUrl(filePath).toLocalFile();
QFile file(localPath);
if (!file.open(QIODevice::ReadOnly))
{
qWarning() << "Cannot open file:" << localPath;
emit sendFileResult(false, "cannot open file: "+localPath,0);
return;
}
QCryptographicHash hash(QCryptographicHash::Sha256);
while (!file.atEnd())
hash.addData(file.read(64 * 1024));
QByteArray sha256 = hash.result();
file.seek(0);
m_uploadFile.setFileName(localPath);
if (!m_uploadFile.open(QIODevice::ReadOnly))
{
qWarning() << "Cannot reopen file.";
emit sendFileResult(false, "cannot reopen file",0);
return;
}
QFileInfo info(localPath);
QMimeDatabase db;
UploadFileBeginPacket up;
up.filename = info.fileName();
up.channelId =channelId;
up.fileSize = m_uploadFile.size();
up.mimeType = db.mimeTypeForFile(localPath).name();
up.sha256 = sha256;
qDebug()
<< "Beginning upload:"
<< up.filename
<< up.fileSize
<< up.mimeType;
qCInfo(_tcp) << "sending UploadFileBegin to server.";
sendPacket(PacketType::UploadFileBegin, up);
}
void User::downloadAttachment(quint64 attachId)
{
DownloadAttachmentPacket packet;
packet.attachmentId = attachId;
qCInfo(_tcp) << "Sending DownloadAttachment request. attachId =" << attachId;
sendPacket(PacketType::DownloadAttachment, packet);
}
bool User::hasAttachmentImage(quint64 attachmentId) const
{
return m_attachmentImageProvider->hasImage(attachmentId);
}
QUrl User::attachmentUrl(quint64 id)
{
QString path = m_attachmentImageProvider->imagePath(id);
if (path.isEmpty())
return {};
return QUrl::fromLocalFile(path);
}
void User::updateChannel(quint64 channelId, const QString &name, const QString &pass, bool saveMessages)
{
qCInfo(_tcp) << "sending update channel request";
UpdateChannelPacket uc;
uc.channelId =channelId;
uc.name = name;
uc.password = pass;
uc.saveChats = saveMessages;
sendPacket(PacketType::UpdateChannel,uc);
}
QString User::getChannelName(quint64 channelId)
{
return m_channelModel->getChannelName(channelId);
}
void User::deleteChannel(quint64 channelId)
{
qCInfo(_tcp) << "sending delete channel request";
DeleteChannelPacket d;
d.channelId = channelId;
sendPacket(PacketType::DeleteChannel, d);
}
ClientUser *User::clientUser(quint64 id)
{
return m_clientUserManager->user(id);
}
void User::updateApp()
{
qCInfo(_updater) << "updateApp clicked";
QString exe = QCoreApplication::applicationDirPath() + "/BeanChatUpdater.exe";
qCInfo(_updater) << "trying to launch updater, path=" << exe;
if (!QProcess::startDetached(exe))
{
qCCritical(_updater) << "failed to launch updater.";
return;
}
qCInfo(_updater) << "updater launched, lets close self.";
QCoreApplication::quit();
}
void User::askForServerState()
{
qCInfo(_tcp) << "asking for server State packet..";
ServerStatePacket ssp;
sendPacket(PacketType::RequestServerState, ssp);
}
void User::askForNotFoundAvatars()
{
if(m_notFoundAvatars.count()>0)
{
qCInfo(_tcp) << "asking for not found avatars... not found avatars count=" << m_notFoundAvatars.count();
RequestAvatarsPacket ra;
ra.notFoundIds = m_notFoundAvatars;
sendPacket(PacketType::RequestAvatars, ra);
}
}
void User::newAvatarArrived(quint64 userId,
const QString& avatarHash,
const QString& oldAvatarHash,
const QByteArray& avatarData)
{
qCInfo(_tcp) << "Avatars response arrived";
//check whether that received avatarHash is valid?
if(avatarHash.isEmpty())
return;
if(m_avatarManager.saveAvatar(SAVE_AVATAR_PATH+QString::number(m_connectedServerId_onDb)
,avatarHash,avatarData))
{
qCInfo(_app) << "avatar saved for that user, "