forked from Aseman-Land/libqtelegram-aseman-edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.cpp
1925 lines (1627 loc) · 88.8 KB
/
telegram.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
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
/*
* Copyright 2014 Canonical Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Roberto Mier
* Tiago Herrmann
*/
#include "telegram.h"
#include <exception>
#include <stdexcept>
#include <openssl/sha.h>
#include <openssl/md5.h>
#include <QDebug>
#include <QLoggingCategory>
#include <QCryptographicHash>
#include <QFile>
#include <QFileInfo>
#include <QMimeDatabase>
#include <QtEndian>
#include <QImage>
#include <QImageReader>
#include <QCryptographicHash>
#include "util/tlvalues.h"
#include "telegram/types/types.h"
#include "core/dcprovider.h"
#include "core/api.h"
#include "secret/secretstate.h"
#include "secret/encrypter.h"
#include "secret/decrypter.h"
#include "secret/secretchatmessage.h"
#include "secret/decryptedmessagebuilder.h"
#include "file/filehandler.h"
#include "core/dcprovider.h"
#include "telegram/coretypes.h"
Q_LOGGING_CATEGORY(TG_TELEGRAM, "tg.telegram")
Q_LOGGING_CATEGORY(TG_LIB_SECRET, "tg.lib.secret")
#define CHECK_API if(!prv->mApi) {qDebug() << __FUNCTION__ << "Error: API is not ready."; return 0;}
QSettings::Format qtelegram_default_settings_format = QSettings::IniFormat;
class TelegramPrivate
{
public:
TelegramPrivate() :
mLibraryState(Telegram::LoggedOut),
mLastRetryType(Telegram::NotRetry),
mSlept(false),
mApi(0),
mSecretState(0) {}
Telegram::LibraryState mLibraryState;
Telegram::LastRetryType mLastRetryType;
bool mSlept;
Settings *mSettings;
CryptoUtils *mCrypto;
Api *mApi;
DcProvider *mDcProvider;
FileHandler::Ptr mFileHandler;
QString m_phoneCodeHash;
QString mSettingsId;
// cached contacts
QList<Contact> m_cachedContacts;
QList<User> m_cachedUsers;
QHash<qint64, int> pendingForwards;
QHash<qint64, int> pendingMediaSends;
// encrypted chats
SecretState mSecretState;
Encrypter *mEncrypter;
Decrypter *mDecrypter;
bool mLoggedIn;
bool mCreatedSharedKeys;
//info for retries
QString mLastPhoneChecked;
QString mLastLangCode;
QList<InputContact> mLastContacts;
};
Telegram::Telegram(const QString &defaultHostAddress, qint16 defaultHostPort, qint16 defaultHostDcId, qint32 appId, const QString &appHash, const QString &phoneNumber, const QString &configPath, const QString &publicKeyFile) {
// Qt5.2 doesn't support .ini files to control logging, so use this
// manual workaround instead.
// http://blog.qt.digia.com/blog/2014/03/11/qt-weekly-1-categorized-logging/
prv = new TelegramPrivate;
QLoggingCategory::setFilterRules(QString(qgetenv("QT_LOGGING_RULES")));
prv->mSettingsId = defaultHostAddress + ":" + QString::number(defaultHostPort) + ":" + configPath +
":" + QString::number(defaultHostPort) + ":" + QString::number(appId) + ":" + appHash +
phoneNumber;
prv->mSettings = new Settings();
prv->mSettings->setAppHash(appHash);
prv->mSettings->setAppId(appId);
prv->mSettings->setDefaultHostAddress(defaultHostAddress);
prv->mSettings->setDefaultHostDcId(defaultHostDcId);
prv->mSettings->setDefaultHostPort(defaultHostPort);
// load settings
if (!prv->mSettings->loadSettings(phoneNumber, configPath, publicKeyFile)) {
throw std::runtime_error("loadSettings failure");
}
prv->mCrypto = new CryptoUtils(prv->mSettings);
prv->mDcProvider = new DcProvider(prv->mSettings, prv->mCrypto);
prv->mDcProvider->setParent(this);
prv->mSecretState = SecretState(prv->mSettings);
prv->mEncrypter = new Encrypter(prv->mSettings);
prv->mDecrypter = new Decrypter(prv->mSettings);
connect(prv->mDecrypter, SIGNAL(sequenceNumberGap(qint32,qint32,qint32)), SLOT(onSequenceNumberGap(qint32,qint32,qint32)));
prv->mSecretState.load();
connect(prv->mDcProvider, SIGNAL(fatalError()), this, SIGNAL(fatalError()));
// activate dc provider ready signal
connect(prv->mDcProvider, SIGNAL(dcProviderReady()), this, SLOT(onDcProviderReady()));
// activate rest of dc provider signal connections
connect(prv->mDcProvider, SIGNAL(authNeeded()), this, SIGNAL(authNeeded()));
connect(prv->mDcProvider, SIGNAL(authTransferCompleted()), this, SLOT(onAuthLoggedIn()));
connect(prv->mDcProvider, SIGNAL(error(qint64,qint32,const QString&)), this, SIGNAL(error(qint64,qint32,const QString&)));
}
bool Telegram::sleep() {
// sleep only if not slept and library already logged in. Returns true if sleep operations completes
if (!prv->mSlept && prv->mLibraryState >= LoggedIn) {
if (prv->mApi && prv->mApi->mainSession()) {
prv->mApi->mainSession()->close();
}
prv->mSlept = true;
return true;
}
return false;
}
bool Telegram::wake() {
// wake only if slept and library already logged in. Returns true if wake operation completes
if (prv->mSlept && prv->mLibraryState >= LoggedIn) {
CHECK_API;
connect(prv->mApi, SIGNAL(mainSessionReady()), this, SIGNAL(woken()), Qt::UniqueConnection);
DC *dc = prv->mDcProvider->getWorkingDc();
prv->mApi->createMainSessionToDc(dc);
prv->mSlept = false;
return true;
}
return false;
}
bool Telegram::isSlept() const
{
return prv->mSlept;
}
void Telegram::setPhoneNumber(const QString &phoneNumber) {
if (!prv->mSettings->loadSettings(phoneNumber)) {
throw std::runtime_error("setPhoneNumber: could not load settings");
}
prv->mSecretState.load();
}
void Telegram::init() {
// check the auth values stored in settings, check the available DCs config data if there is
// connection to servers, and emit signals depending on user authenticated or not.
prv->mDcProvider->initialize();
}
Telegram::~Telegram() {
delete prv->mDcProvider;
delete prv->mSettings;
delete prv;
}
QString Telegram::defaultHostAddress()
{
return prv->mSettings->defaultHostAddress();
}
qint16 Telegram::defaultHostPort()
{
return prv->mSettings->defaultHostPort();
}
qint16 Telegram::defaultHostDcId()
{
return prv->mSettings->defaultHostDcId();
}
qint32 Telegram::appId()
{
return prv->mSettings->appId();
}
QString Telegram::appHash()
{
return prv->mSettings->appHash();
}
Settings *Telegram::settings() const
{
return prv->mSettings;
}
CryptoUtils *Telegram::crypto() const
{
return prv->mCrypto;
}
void Telegram::setDefaultSettingsFormat(const QSettings::Format &format)
{
qtelegram_default_settings_format = format;
}
QSettings::Format Telegram::defaultSettingsFormat()
{
return qtelegram_default_settings_format;
}
bool Telegram::isConnected() {
if (prv->mApi && prv->mApi->mainSession()) {
return prv->mApi->mainSession()->state() == QAbstractSocket::ConnectedState;
}
return false;
}
bool Telegram::isLoggedIn() {
return prv->mLibraryState == LoggedIn;
}
void Telegram::onAuthLoggedIn() {
prv->mLibraryState = LoggedIn;
Q_EMIT authLoggedIn();
}
void Telegram::onAuthLogOutAnswer(qint64 id, bool ok) {
prv->mDcProvider->logOut();
prv->mLibraryState = LoggedOut;
Q_EMIT authLogOutAnswer(id,ok);
}
qint32 Telegram::ourId() {
return prv->mSettings->ourId();
}
void Telegram::onDcProviderReady() {
prv->mLibraryState = CreatedSharedKeys;
prv->mApi = prv->mDcProvider->getApi();
// api signal-signal and signal-slot connections
// updates
connect(prv->mApi, SIGNAL(updatesTooLong()), this, SIGNAL(updatesTooLong()));
connect(prv->mApi, SIGNAL(updateShortMessage(qint32,qint32,const QString&,qint32,qint32,qint32,qint32,qint32,qint32,bool,bool)), this, SIGNAL(updateShortMessage(qint32,qint32,const QString&,qint32,qint32,qint32,qint32,qint32,qint32,bool,bool)));
connect(prv->mApi, SIGNAL(updateShortChatMessage(qint32,qint32,qint32,const QString&,qint32,qint32,qint32,qint32,qint32,qint32,bool,bool)), this, SIGNAL(updateShortChatMessage(qint32,qint32,qint32,const QString&,qint32,qint32,qint32,qint32,qint32,qint32,bool,bool)));
connect(prv->mApi, SIGNAL(updateShort(const Update&,qint32)), this, SIGNAL(updateShort(const Update&,qint32)));
connect(prv->mApi, SIGNAL(updatesCombined(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32,qint32)), this, SIGNAL(updatesCombined(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32,qint32)));
connect(prv->mApi, SIGNAL(updates(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32)), this, SIGNAL(updates(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32)));
// errors
connect(prv->mApi, SIGNAL(fatalError()), this, SIGNAL(fatalError()));
connect(prv->mApi, SIGNAL(error(qint64,qint32,const QString&,const QString&)), this, SLOT(onError(qint64,qint32,const QString&,const QString&)));
connect(prv->mApi, SIGNAL(errorRetry(qint64,qint32,const QString&)), this, SLOT(onErrorRetry(qint64,qint32,const QString&)));
connect(prv->mApi, SIGNAL(authSignInError(qint64,qint32,const QString&)), this, SIGNAL(authSignInError(qint64,qint32,const QString&)));
connect(prv->mApi, SIGNAL(authSignUpError(qint64,qint32,const QString&)), this, SIGNAL(authSignUpError(qint64,qint32,const QString&)));
// positive responses
connect(prv->mApi, SIGNAL(helpGetInviteTextAnswer(qint64,const QString&)), this, SIGNAL(helpGetInviteTextAnswer(qint64,const QString&)));
connect(prv->mApi, SIGNAL(authCheckedPhone(qint64,bool)), this, SIGNAL(authCheckPhoneAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authCheckedPhoneError(qint64)), this, SIGNAL(authCheckedPhoneError(qint64)));
connect(prv->mApi, SIGNAL(authCheckPhoneSent(qint64,const QString&)), this, SIGNAL(authCheckPhoneSent(qint64,const QString&)));
connect(prv->mApi, SIGNAL(authSentCode(qint64,bool,const QString&,qint32,bool)), this, SLOT(onAuthSentCode(qint64,bool,const QString&,qint32,bool)));
connect(prv->mApi, SIGNAL(authSendCodeError(qint64)), this, SIGNAL(authSendCodeError(qint64)));
connect(prv->mApi, SIGNAL(authSentAppCode(qint64,bool,const QString&,qint32,bool)), this, SLOT(onAuthSentCode(qint64,bool,const QString&,qint32,bool)));
connect(prv->mApi, SIGNAL(authSendSmsResult(qint64,bool)), this, SIGNAL(authSendSmsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authSendCallResult(qint64,bool)), this, SIGNAL(authSendCallAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authSignInAuthorization(qint64,qint32,const User&)), this, SLOT(onUserAuthorized(qint64,qint32,const User&)));
connect(prv->mApi, SIGNAL(authSignUpAuthorization(qint64,qint32,const User&)), this, SLOT(onUserAuthorized(qint64,qint32,const User&)));
connect(prv->mApi, SIGNAL(authLogOutResult(qint64,bool)), this, SLOT(onAuthLogOutAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authSendInvitesResult(qint64,bool)), this, SIGNAL(authSendInvitesAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authResetAuthorizationsResult(qint64,bool)), this, SIGNAL(authResetAuthorizationsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(authCheckPasswordResult(qint64,qint32,const User&)), this, SLOT(onUserAuthorized(qint64,qint32,const User&)));
connect(prv->mApi, SIGNAL(authRequestPasswordRecoveryResult(qint64,AuthPasswordRecovery)), this, SIGNAL(authRequestPasswordRecoveryAnswer(qint64,AuthPasswordRecovery)));
connect(prv->mApi, SIGNAL(authRecoverPasswordResult(qint64,AuthAuthorization)), this, SIGNAL(authRecoverPasswordAnswer(qint64,AuthAuthorization)));
connect(prv->mApi, SIGNAL(accountRegisterDeviceResult(qint64,bool)), this, SIGNAL(accountRegisterDeviceAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountUnregisterDeviceResult(qint64,bool)), this, SIGNAL(accountUnregisterDeviceAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountUpdateNotifySettingsResult(qint64,bool)), this, SIGNAL(accountUpdateNotifySettingsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountPeerNotifySettings(qint64,const PeerNotifySettings&)), this, SIGNAL(accountGetNotifySettingsAnswer(qint64,const PeerNotifySettings&)));
connect(prv->mApi, SIGNAL(accountResetNotifySettingsResult(qint64,bool)), this, SIGNAL(accountResetNotifySettingsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountUser(qint64,const User&)), this, SIGNAL(accountUpdateProfileAnswer(qint64,const User&)));
connect(prv->mApi, SIGNAL(accountUpdateStatusResult(qint64,bool)), this, SIGNAL(accountUpdateStatusAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountGetWallPapersResult(qint64,const QList<WallPaper>&)), this, SIGNAL(accountGetWallPapersAnswer(qint64,const QList<WallPaper>&)));
connect(prv->mApi, SIGNAL(accountCheckUsernameResult(qint64,bool)), this, SIGNAL(accountCheckUsernameAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountUpdateUsernameResult(qint64,const User&)), this, SIGNAL(accountUpdateUsernameAnswer(qint64,const User&)));
connect(prv->mApi, SIGNAL(accountDeleteAccountResult(qint64,bool)), this, SIGNAL(accountDeleteAccountAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountGetAccountTTLResult(qint64,const AccountDaysTTL&)), this, SIGNAL(accountGetAccountTTLAnswer(qint64,const AccountDaysTTL&)));
connect(prv->mApi, SIGNAL(accountSetAccountTTLResult(qint64,bool)), this, SIGNAL(accountSetAccountTTLAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountUpdateDeviceLockedResult(qint64,bool)), this, SIGNAL(accountUpdateDeviceLockedAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountSentChangePhoneCode(qint64,const QString&,qint32)), this, SIGNAL(accountSentChangePhoneCode(qint64,const QString&,qint32)));
connect(prv->mApi, SIGNAL(accountGetPasswordResult(qint64,const AccountPassword&)), this, SIGNAL(accountGetPasswordAnswer(qint64,const AccountPassword&)));
connect(prv->mApi, SIGNAL(accountGetAuthorizationsResult(qint64,AccountAuthorizations)), this, SIGNAL(accountGetAuthorizationsAnswer(qint64,AccountAuthorizations)));
connect(prv->mApi, SIGNAL(accountResetAuthorizationResult(qint64,bool)), this, SIGNAL(accountResetAuthorizationAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountGetPasswordSettingsResult(qint64,AccountPasswordSettings)), this, SIGNAL(accountGetPasswordSettingsAnswer(qint64,AccountPasswordSettings)));
connect(prv->mApi, SIGNAL(accountUpdatePasswordSettingsResult(qint64,bool)), this, SIGNAL(accountUpdatePasswordSettingsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(accountChangePhoneResult(qint64,const User&)), this, SIGNAL(accountChangePhoneAnswer(qint64,const User&)));
connect(prv->mApi, SIGNAL(photosPhoto(qint64,const Photo&,const QList<User>&)), this, SIGNAL(photosUploadProfilePhotoAnswer(qint64,const Photo&,const QList<User>&)));
connect(prv->mApi, SIGNAL(photosUserProfilePhoto(qint64,const UserProfilePhoto&)), this, SIGNAL(photosUpdateProfilePhotoAnswer(qint64,const UserProfilePhoto&)));
connect(prv->mApi, SIGNAL(usersGetUsersResult(qint64,const QList<User>&)), this, SIGNAL(usersGetUsersAnswer(qint64,const QList<User>&)));
connect(prv->mApi, SIGNAL(userFull(qint64,const User&,const ContactsLink&,const Photo&,const PeerNotifySettings&,bool,const QString&,const QString&)), this, SIGNAL(usersGetFullUserAnswer(qint64,const User&,const ContactsLink&,const Photo&,const PeerNotifySettings&,bool,const QString&,const QString&)));
connect(prv->mApi, SIGNAL(photosPhotos(qint64,const QList<Photo>&,const QList<User>&)), this, SLOT(onPhotosPhotos(qint64, const QList<Photo>&, const QList<User>&)));
connect(prv->mApi, SIGNAL(photosPhotosSlice(qint64,qint32,const QList<Photo>&,const QList<User>&)), this, SIGNAL(photosGetUserPhotosAnswer(qint64,qint32,const QList<Photo>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(contactsGetStatusesResult(qint64,const QList<ContactStatus>&)), this, SIGNAL(contactsGetStatusesAnswer(qint64,const QList<ContactStatus>&)));
connect(prv->mApi, SIGNAL(contactsContacts(qint64,const QList<Contact>&,const QList<User>&)), this, SLOT(onContactsContacts(qint64,const QList<Contact>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(contactsContactsNotModified(qint64)), this, SLOT(onContactsContactsNotModified(qint64)));
connect(prv->mApi, SIGNAL(contactsImportedContacts(qint64,const QList<ImportedContact>&,const QList<qint64>&,const QList<User>&)), this, SIGNAL(contactsImportContactsAnswer(qint64,const QList<ImportedContact>&,const QList<qint64>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(contactsImportedContacts(qint64,const QList<ImportedContact>&,const QList<qint64>&,const QList<User>&)), this, SLOT(onContactsImportContactsAnswer()));
connect(prv->mApi, SIGNAL(contactsFound(qint64,const QList<ContactFound>&,const QList<User>&)), this, SIGNAL(contactsFound(qint64,const QList<ContactFound>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(contactsResolveUsernameResult(qint64,const User&)), this, SIGNAL(contactsResolveUsernameAnswer(qint64,const User&)));
connect(prv->mApi, SIGNAL(contactsDeleteContactLink(qint64,const ContactLink&,const ContactLink&,const User&)), this, SIGNAL(contactsDeleteContactAnswer(qint64,const ContactLink&,const ContactLink&,const User&)));
connect(prv->mApi, SIGNAL(contactsDeleteContactsResult(qint64,bool)), this, SIGNAL(contactsDeleteContactsAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(contactsBlockResult(qint64,bool)), this, SIGNAL(contactsBlockAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(contactsUnblockResult(qint64,bool)), this, SIGNAL(contactsUnblockAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(contactsBlocked(qint64,const QList<ContactBlocked>&,const QList<User>&)), this, SLOT(onContactsBlocked(qint64,const QList<ContactBlocked>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(contactsBlockedSlice(qint64,qint32,const QList<ContactBlocked>&,const QList<User>&)), this, SIGNAL(contactsGetBlockedAnswer(qint64,qint32,QList<ContactBlocked>,QList<User>)));
connect(prv->mApi, SIGNAL(messagesSentMessage(qint64,qint32,qint32,const MessageMedia&,qint32,qint32,qint32)), this, SLOT(onMessagesSentMessage(qint64,qint32,qint32,const MessageMedia&,qint32,qint32,qint32)));
connect(prv->mApi, SIGNAL(messagesSentMessageLink(qint64,qint32,qint32,const MessageMedia&,qint32,qint32,qint32,const QList<ContactsLink>&)), this, SIGNAL(messagesSendMessageAnswer(qint64,qint32,qint32,const MessageMedia&,qint32,qint32,qint32,const QList<ContactsLink>&)));
connect(prv->mApi, SIGNAL(messagesSetTypingResult(qint64,bool)), this, SIGNAL(messagesSetTypingAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(messagesGetMessagesMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SLOT(onMessagesGetMessagesMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesGetMessagesMessagesSlice(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SIGNAL(messagesGetMessagesAnswer(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesDialogs(qint64, const QList<Dialog>&,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SLOT(onMessagesDialogs(qint64,const QList<Dialog>&,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesDialogsSlice(qint64,qint32,const QList<Dialog>&,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SIGNAL(messagesGetDialogsAnswer(qint64,qint32,const QList<Dialog>&,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesGetHistoryMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SLOT(onMessagesGetHistoryMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesGetHistoryMessagesSlice(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SIGNAL(messagesGetHistoryAnswer(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesSearchMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SLOT(onMessagesSearchMessages(qint64,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesSearchMessagesSlice(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)), this, SIGNAL(messagesSearchAnswer(qint64,qint32,const QList<Message>&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesReadAffectedHistory(qint64,qint32,qint32,qint32)), this, SIGNAL(messagesReadHistoryAnswer(qint64,qint32,qint32,qint32)));
connect(prv->mApi, SIGNAL(messagesReadMessageContentsResult(qint64,const MessagesAffectedMessages&)), this, SIGNAL(messagesReadMessageContentsAnswer(qint64,const MessagesAffectedMessages&)));
connect(prv->mApi, SIGNAL(messagesDeleteAffectedHistory(qint64,qint32,qint32,qint32)), this, SIGNAL(messagesDeleteHistoryAnswer(qint64,qint32,qint32,qint32)));
connect(prv->mApi, SIGNAL(messagesDeleteMessagesResult(qint64,const MessagesAffectedMessages&)), this, SIGNAL(messagesDeleteMessagesAnswer(qint64,const MessagesAffectedMessages&)));
connect(prv->mApi, SIGNAL(messagesReceivedMessagesResult(qint64,const QList<ReceivedNotifyMessage>&)), this, SIGNAL(messagesReceivedMessagesAnswer(qint64,const QList<ReceivedNotifyMessage>&)));
connect(prv->mApi, SIGNAL(messagesForwardedMessage(qint64,const UpdatesType&)), this, SIGNAL(messagesForwardMessageAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesForwardedMessages(qint64,const UpdatesType&)), this, SIGNAL(messagesForwardMessagesAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesSentBroadcast(qint64,const UpdatesType&)), this, SIGNAL(messagesSendBroadcastAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesGetWebPagePreviewResult(qint64,MessageMedia)), this, SIGNAL(messagesGetWebPagePreviewAnswer(qint64,MessageMedia)));
connect(prv->mApi, SIGNAL(messagesForwardedMedia(qint64,UpdatesType)), SLOT(onMessagesForwardMediaAnswer(qint64,UpdatesType)));
connect(prv->mApi, SIGNAL(messagesChats(qint64,const QList<Chat>&)), this, SIGNAL(messagesGetChatsAnswer(qint64,const QList<Chat>&)));
connect(prv->mApi, SIGNAL(messagesChatFull(qint64,const ChatFull&,const QList<Chat>&,const QList<User>&)), this, SIGNAL(messagesGetFullChatAnswer(qint64,const ChatFull&,const QList<Chat>&,const QList<User>&)));
connect(prv->mApi, SIGNAL(messagesEditedChatTitle(qint64,const UpdatesType&)), this, SIGNAL(messagesEditChatTitleAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesEditedChatPhoto(qint64,const UpdatesType&)), this, SIGNAL(messagesEditChatPhotoStatedMessageAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesAddedChatUser(qint64,const UpdatesType&)), this, SIGNAL(messagesAddChatUserAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesDeletedChat(qint64,const UpdatesType&)), this, SIGNAL(messagesDeleteChatUserAnswer(qint64,const UpdatesType&)));
connect(prv->mApi, SIGNAL(messagesCreatedChat(qint64,const UpdatesType&)), this, SIGNAL(messagesCreateChatAnswer(qint64,const UpdatesType&)));
// secret chats
connect(prv->mApi, SIGNAL(messagesDhConfig(qint64,qint32,const QByteArray&,qint32,const QByteArray&)), this, SLOT(onMessagesDhConfig(qint64,qint32,const QByteArray&,qint32,const QByteArray&)));
connect(prv->mApi, SIGNAL(messagesDhConfigNotModified(qint64,const QByteArray&)), this, SLOT(onMessagesDhConfigNotModified(qint64,const QByteArray&)));
connect(prv->mApi, SIGNAL(messagesRequestEncryptionEncryptedChat(qint64,const EncryptedChat&)), this, SLOT(onMessagesRequestEncryptionEncryptedChat(qint64,const EncryptedChat&)));
connect(prv->mApi, SIGNAL(messagesAcceptEncryptionEncryptedChat(qint64,const EncryptedChat&)), this, SLOT(onMessagesAcceptEncryptionEncryptedChat(qint64,const EncryptedChat&)));
connect(prv->mApi, SIGNAL(messagesDiscardEncryptionResult(qint64,bool)), this, SLOT(onMessagesDiscardEncryptionResult(qint64,bool)));
connect(prv->mApi, SIGNAL(messagesReadEncryptedHistoryResult(qint64,bool)), this, SIGNAL(messagesReadEncryptedHistoryAnswer(qint64,bool)));
connect(prv->mApi, SIGNAL(messagesSendEncryptedSentEncryptedMessage(qint64,qint32)), this, SIGNAL(messagesSendEncryptedAnswer(qint64,qint32)));
connect(prv->mApi, SIGNAL(messagesSendEncryptedSentEncryptedFile(qint64,qint32,const EncryptedFile&)), this, SIGNAL(messagesSendEncryptedAnswer(qint64,qint32,const EncryptedFile&)));
connect(prv->mApi, SIGNAL(messagesSendEncryptedServiceSentEncryptedMessage(qint64,qint32)), this, SIGNAL(messagesSendEncryptedServiceAnswer(qint64,qint32)));
connect(prv->mApi, SIGNAL(messagesSendEncryptedServiceSentEncryptedFile(qint64,qint32,const EncryptedFile&)), this, SIGNAL(messagesSendEncryptedServiceAnswer(qint64,qint32,const EncryptedFile&)));
connect(prv->mApi, SIGNAL(messagesGetStickersResult(qint64,const MessagesStickers&)), this, SIGNAL(messagesGetStickersAnwer(qint64,const MessagesStickers&)));
connect(prv->mApi, SIGNAL(messagesGetAllStickersResult(qint64,const MessagesAllStickers&)), this, SIGNAL(messagesGetAllStickersAnwer(qint64,const MessagesAllStickers&)));
connect(prv->mApi, SIGNAL(messagesGetStickerSetResult(qint64,MessagesStickerSet)), this, SIGNAL(messagesGetStickerSetAnwer(qint64,MessagesStickerSet)));
connect(prv->mApi, SIGNAL(messagesInstallStickerSetResult(qint64,bool)), this, SIGNAL(messagesInstallStickerSetAnwer(qint64,bool)));
connect(prv->mApi, SIGNAL(messagesUninstallStickerSetResult(qint64,bool)), this, SIGNAL(messagesUninstallStickerSetAnwer(qint64,bool)));
connect(prv->mApi, SIGNAL(messagesExportChatInviteResult(qint64,ExportedChatInvite)), this, SIGNAL(messagesExportChatInviteAnwer(qint64,ExportedChatInvite)));
connect(prv->mApi, SIGNAL(messagesCheckChatInviteResult(qint64,ChatInvite)), this, SIGNAL(messagesCheckChatInviteAnwer(qint64,ChatInvite)));
connect(prv->mApi, SIGNAL(messagesImportChatInviteResult(qint64,UpdatesType)), this, SIGNAL(messagesImportChatInviteAnwer(qint64,UpdatesType)));
connect(prv->mApi, SIGNAL(updateShort(const Update&,qint32)), SLOT(onUpdateShort(const Update&)));
connect(prv->mApi, SIGNAL(updatesCombined(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32,qint32)), SLOT(onUpdatesCombined(const QList<Update>&)));
connect(prv->mApi, SIGNAL(updates(const QList<Update>&,const QList<User>&,const QList<Chat>&,qint32,qint32)), SLOT(onUpdates(const QList<Update>&)));
// updates
connect(prv->mApi, SIGNAL(updatesState(qint64,qint32,qint32,qint32,qint32,qint32)), this, SIGNAL(updatesGetStateAnswer(qint64,qint32,qint32,qint32,qint32,qint32)));
connect(prv->mApi, SIGNAL(updatesDifferenceEmpty(qint64,qint32,qint32)), this, SIGNAL(updatesGetDifferenceAnswer(qint64,qint32,qint32)));
connect(prv->mApi, SIGNAL(updatesDifference(qint64,const QList<Message>&,const QList<EncryptedMessage>&,const QList<Update>&,const QList<Chat>&,const QList<User>&,const UpdatesState&)), this, SLOT(onUpdatesDifference(qint64,const QList<Message>&,const QList<EncryptedMessage>&,const QList<Update>&,const QList<Chat>&,const QList<User>&,const UpdatesState&)));
connect(prv->mApi, SIGNAL(updatesDifferenceSlice(qint64,const QList<Message>,const QList<EncryptedMessage>,const QList<Update>&,const QList<Chat>&,const QList<User>&,const UpdatesState&)), this, SLOT(onUpdatesDifferenceSlice(qint64,const QList<Message>&,const QList<EncryptedMessage>&,const QList<Update>&,const QList<Chat>&,const QList<User>&,const UpdatesState&)));
// logic additional signal slots
connect(prv->mApi, SIGNAL(mainSessionDcChanged(DC*)), this, SLOT(onAuthCheckPhoneDcChanged()));
connect(prv->mApi, SIGNAL(mainSessionDcChanged(DC*)), this, SLOT(onHelpGetInviteTextDcChanged()));
connect(prv->mApi, SIGNAL(mainSessionDcChanged(DC*)), this, SLOT(onImportContactsDcChanged()));
connect(prv->mApi, SIGNAL(mainSessionReady()), this, SIGNAL(connected()));
connect(prv->mApi, SIGNAL(mainSessionClosed()), this, SIGNAL(disconnected()));
prv->mFileHandler = FileHandler::Ptr(new FileHandler(prv->mApi, prv->mCrypto, prv->mSettings, *prv->mDcProvider, prv->mSecretState));
connect(prv->mFileHandler.data(), SIGNAL(uploadSendFileAnswer(qint64,qint32,qint32,qint32)), SIGNAL(uploadSendFileAnswer(qint64,qint32,qint32,qint32)));
connect(prv->mFileHandler.data(), SIGNAL(uploadGetFileAnswer(qint64,const StorageFileType&,qint32,const QByteArray&,qint32,qint32,qint32)), SIGNAL(uploadGetFileAnswer(qint64,const StorageFileType&,qint32,const QByteArray&,qint32,qint32,qint32)));
connect(prv->mFileHandler.data(), SIGNAL(uploadCancelFileAnswer(qint64,bool)), SIGNAL(uploadCancelFileAnswer(qint64,bool)));
connect(prv->mFileHandler.data(), SIGNAL(error(qint64,qint32,const QString&)), SIGNAL(error(qint64,qint32,const QString&)));
connect(prv->mFileHandler.data(), SIGNAL(messagesSentMedia(qint64,const UpdatesType&)), SLOT(onMessagesSendMediaAnswer(qint64,const UpdatesType&)));
connect(prv->mFileHandler.data(), SIGNAL(messagesSendEncryptedFileAnswer(qint64,qint32,const EncryptedFile&)), SIGNAL(messagesSendEncryptedFileAnswer(qint64,qint32,const EncryptedFile&)));
// At this point we should test the main session state and emit by hand signals of connected/disconnected
// depending on the connection state of the session. This is so because first main session connection, if done,
// is performed before we could connect the signal-slots to advise about it;
if (prv->mApi->mainSession()->state() == QAbstractSocket::ConnectedState) {
Q_EMIT connected();
} else {
Q_EMIT disconnected();
}
}
qint64 Telegram::messagesCreateEncryptedChat(const InputUser &user) {
qCDebug(TG_LIB_SECRET) << "creating new encrypted chat";
// generate a new object where store all the needed secret chat data
SecretChat *secretChat = new SecretChat(prv->mSettings);
secretChat->setRequestedUser(user);
return generateGAorB(secretChat);
}
qint64 Telegram::messagesAcceptEncryptedChat(qint32 chatId) {
qCDebug(TG_LIB_SECRET) << "accepting requested encrypted chat with id" << chatId;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Not found any chat related to" << chatId;
return -1;
}
return generateGAorB(secretChat);
}
qint64 Telegram::messagesDiscardEncryptedChat(qint32 chatId) {
CHECK_API;
qCDebug(TG_LIB_SECRET) << "discarding encrypted chat with id" << chatId;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Trying to discard a not existant chat";
Q_EMIT messagesEncryptedChatDiscarded(chatId);
return -1;
}
qint64 requestId = prv->mApi->messagesDiscardEncryption(chatId);
// insert another entry related to this request for deleting chat only when response is ok
prv->mSecretState.chats().insert(requestId, secretChat);
return requestId;
}
qint64 Telegram::messagesSetEncryptedTTL(qint64 randomId, qint32 chatId, qint32 ttl) {
CHECK_API;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not set secret chat TTL, chat not found.";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForTtl(randomId, ttl);
prv->mEncrypter->setSecretChat(secretChat);
QByteArray data = prv->mEncrypter->generateEncryptedData(decryptedMessage);
QList<qint64> previousMsgs = secretChat->sequence();
qint64 requestId = prv->mApi->messagesSendEncrypted(previousMsgs, inputEncryptedChat, randomId, data);
secretChat->increaseOutSeqNo();
secretChat->appendToSequence(randomId);
prv->mSecretState.save();
return requestId;
}
qint64 Telegram::messagesReadEncryptedHistory(qint32 chatId, qint32 maxDate) {
CHECK_API;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not read history of a not yet existant chat";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(chatId);
inputEncryptedChat.setAccessHash(secretChat->accessHash());
return prv->mApi->messagesReadEncryptedHistory(inputEncryptedChat, maxDate);
}
qint64 Telegram::messagesSendEncrypted(qint32 chatId, qint64 randomId, qint32 ttl, const QString &text) {
CHECK_API;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not find any related secret chat to send the message";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForSendMessage(randomId, ttl, text);
prv->mEncrypter->setSecretChat(secretChat);
QByteArray data = prv->mEncrypter->generateEncryptedData(decryptedMessage);
QList<qint64> previousMsgs = secretChat->sequence();
qint64 request = prv->mApi->messagesSendEncrypted(previousMsgs, inputEncryptedChat, randomId, data);
secretChat->increaseOutSeqNo();
secretChat->appendToSequence(randomId);
prv->mSecretState.save();
return request;
}
void Telegram::onSequenceNumberGap(qint32 chatId, qint32 startSeqNo, qint32 endSeqNo) {
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
ASSERT(secretChat);
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
qint64 randomId;
Utils::randomBytes(&randomId, 8);
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForResend(randomId, startSeqNo, endSeqNo);
prv->mEncrypter->setSecretChat(secretChat);
QByteArray data = prv->mEncrypter->generateEncryptedData(decryptedMessage);
QList<qint64> previousMsgs = secretChat->sequence();
prv->mApi->messagesSendEncrypted(previousMsgs, inputEncryptedChat, randomId, data);
secretChat->increaseOutSeqNo();
secretChat->appendToSequence(randomId);
prv->mSecretState.save();
}
qint64 Telegram::messagesSendEncryptedPhoto(qint32 chatId, qint64 randomId, qint32 ttl, const QString &filePath) {
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not find any related secret chat to send the photo";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
FileOperation *op = new FileOperation(FileOperation::sendEncryptedFile);
op->setInputEncryptedChat(inputEncryptedChat);
op->setRandomId(randomId);
op->initializeKeyAndIv();
QByteArray key = op->key();
QByteArray iv = op->iv();
QFileInfo fileInfo(filePath);
qint32 size = fileInfo.size();
QImage image;
image.load(filePath);
qint32 width = image.width();
qint32 height = image.height();
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForSendPhoto(randomId, ttl, key, iv, size, width, height);
op->setDecryptedMessage(decryptedMessage);
return prv->mFileHandler->uploadSendFile(*op, filePath);
}
qint64 Telegram::messagesSendEncryptedVideo(qint32 chatId, qint64 randomId, qint32 ttl, const QString &filePath, qint32 duration, qint32 width, qint32 height, const QByteArray &thumbnailBytes) {
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not find any related secret chat to send the video";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
FileOperation *op = new FileOperation(FileOperation::sendEncryptedFile);
op->setInputEncryptedChat(inputEncryptedChat);
op->setRandomId(randomId);
op->initializeKeyAndIv();
QByteArray key = op->key();
QByteArray iv = op->iv();
QFileInfo fileInfo(filePath);
qint32 size = fileInfo.size();
QString mimeType = QMimeDatabase().mimeTypeForFile(QFileInfo(filePath)).name();
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage =
builder.buildDecryptedMessageForSendVideo(randomId, ttl, key, iv, size, mimeType, duration, width, height, thumbnailBytes);
op->setDecryptedMessage(decryptedMessage);
return prv->mFileHandler->uploadSendFile(*op, filePath);
}
qint64 Telegram::messagesSendEncryptedDocument(qint32 chatId, qint64 randomId, qint32 ttl, const QString &filePath) {
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not find any related secret chat to send the document";
return -1;
}
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
FileOperation *op = new FileOperation(FileOperation::sendEncryptedFile);
op->setInputEncryptedChat(inputEncryptedChat);
op->setRandomId(randomId);
op->initializeKeyAndIv();
QByteArray key = op->key();
QByteArray iv = op->iv();
QFileInfo fileInfo(filePath);
qint32 size = fileInfo.size();
QString fileName = fileInfo.fileName();
QString mimeType = QMimeDatabase().mimeTypeForFile(filePath).name();
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForSendDocument(randomId, ttl, key, iv, size, fileName, mimeType);
op->setDecryptedMessage(decryptedMessage);
return prv->mFileHandler->uploadSendFile(*op, filePath);
}
qint64 Telegram::messagesReceivedQueue(qint32 maxQts) {
CHECK_API;
return prv->mApi->messagesReceivedQueue(maxQts);
}
qint64 Telegram::messagesGetStickers(const QString &emoticon, const QString &hash) {
CHECK_API;
return prv->mApi->messagesGetStickers(emoticon, hash);
}
qint64 Telegram::messagesGetAllStickers(const QString &hash) {
CHECK_API;
return prv->mApi->messagesGetAllStickers(hash);
}
qint64 Telegram::messagesGetStickerSet(const InputStickerSet &stickerset) {
CHECK_API;
return prv->mApi->messagesGetStickerSet(stickerset);
}
qint64 Telegram::messagesInstallStickerSet(const InputStickerSet &stickerset) {
CHECK_API;
return prv->mApi->messagesInstallStickerSet(stickerset);
}
qint64 Telegram::messagesUninstallStickerSet(const InputStickerSet &stickerset) {
CHECK_API;
return prv->mApi->messagesUninstallStickerSet(stickerset);
}
qint64 Telegram::messagesExportChatInvite(qint32 chatId) {
CHECK_API;
return prv->mApi->messagesExportChatInvite(chatId);
}
qint64 Telegram::messagesCheckChatInvite(const QString &hash) {
CHECK_API;
return prv->mApi->messagesCheckChatInvite(hash);
}
qint64 Telegram::messagesImportChatInvite(const QString &hash) {
CHECK_API;
return prv->mApi->messagesImportChatInvite(hash);
}
qint64 Telegram::generateGAorB(SecretChat *secretChat) {
CHECK_API;
qCDebug(TG_LIB_SECRET) << "requesting for DH config parameters";
// call messages.getDhConfig to get p and g for start creating shared key
qint64 reqId = prv->mApi->messagesGetDhConfig(prv->mSecretState.version(), DH_CONFIG_SERVER_RANDOM_LENGTH);
// store in secret chats map related to this request id, temporally
prv->mSecretState.chats().insert(reqId, secretChat);
return reqId;
}
void Telegram::onMessagesDhConfig(qint64 msgId, qint32 g, const QByteArray &p, qint32 version, const QByteArray &random) {
qCDebug(TG_LIB_SECRET) << "received new DH parameters g ="<< QString::number(g) << ",p =" << p.toBase64()
<< ",version =" << version;
prv->mSecretState.setVersion(version);
prv->mSecretState.setG(g);
prv->mSecretState.setP(p);
if (prv->mCrypto->checkDHParams(prv->mSecretState.p(), g) < 0) {
qCCritical(TG_TELEGRAM) << "Diffie-Hellman config parameters are not valid";
return;
}
onMessagesDhConfigNotModified(msgId, random);
}
void Telegram::onMessagesDhConfigNotModified(qint64 msgId, const QByteArray &random) {
qCDebug(TG_LIB_SECRET) << "processing DH parameters";
SecretChat *secretChat = prv->mSecretState.chats().take(msgId);
ASSERT(secretChat);
// create secret a number by taking server random (and generating a client random also to have more entrophy)
secretChat->createMyKey(random);
// create empty bignum where store the result of operation g^a mod p
BIGNUM *r = BN_new();
Utils::ensurePtr(r);
// do the opeation -> r = g^a mod p
Utils::ensure(prv->mCrypto->BNModExp(r, prv->mSecretState.g(), secretChat->myKey(), prv->mSecretState.p()));
// check that g and r are greater than one and smaller than p-1. Also checking that r is between 2^{2048-64} and p - 2^{2048-64}
if (prv->mCrypto->checkCalculatedParams(r, prv->mSecretState.g(), prv->mSecretState.p()) < 0) {
qCCritical(TG_LIB_SECRET) << "gAOrB or g params are not valid";
return;
}
// convert result to big endian before sending request encryption query
uchar rawGAOrB[256];
memset(rawGAOrB, 0, 256);
BN_bn2bin(r, rawGAOrB);
QByteArray gAOrB = QByteArray::fromRawData(reinterpret_cast<char*>(rawGAOrB), 256);
switch (static_cast<qint32>(secretChat->state())) {
case SecretChat::Init: {
// generate randomId, used not only to request encryption but as chatId
qint32 randomId;
Utils::randomBytes(&randomId, 4);
secretChat->setChatId(randomId);
prv->mSecretState.chats().insert(randomId, secretChat);
qCDebug(TG_LIB_SECRET) << "Requesting encryption for chatId" << secretChat->chatId();
prv->mApi->messagesRequestEncryption(secretChat->requestedUser(), randomId, gAOrB);
break;
}
case SecretChat::Requested: {
QByteArray gA = secretChat->gAOrB();
createSharedKey(secretChat, prv->mSecretState.p(), gA);
qint64 keyFingerprint = secretChat->keyFingerprint();
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(secretChat->chatId());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
qCDebug(TG_LIB_SECRET) << "Accepting encryption for chatId" << secretChat->chatId();
prv->mApi->messagesAcceptEncryption(inputEncryptedChat, gAOrB, keyFingerprint);
break;
}
default:
Q_ASSERT("Not handled");
break;
}
BN_free(r);
prv->mSecretState.save();
}
void Telegram::onMessagesRequestEncryptionEncryptedChat(qint64, const EncryptedChat &chat) {
Q_EMIT messagesCreateEncryptedChatAnswer(chat.id(), chat.date(), chat.participantId(), chat.accessHash());
}
void Telegram::onMessagesAcceptEncryptionEncryptedChat(qint64, const EncryptedChat &chat) {
qCDebug(TG_LIB_SECRET) << "Joined to secret chat" << chat.id() << "with peer" << chat.adminId();
SecretChat *secretChat = prv->mSecretState.chats().value(chat.id());
secretChat->setState(SecretChat::Accepted);
prv->mSecretState.save();
Q_EMIT messagesEncryptedChatCreated(chat.id(), chat.date(), chat.adminId(), chat.accessHash());
//notify peer about our layer
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(chat.id());
inputEncryptedChat.setAccessHash(secretChat->accessHash());
prv->mEncrypter->setSecretChat(secretChat);
qint64 randomId;
Utils::randomBytes(&randomId, 8);
QList<qint64> previousMsgs = secretChat->sequence();
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForNotifyLayer(randomId, CoreTypes::typeLayerVersion);
QByteArray data = prv->mEncrypter->generateEncryptedData(decryptedMessage);
prv->mApi->messagesSendEncryptedService(previousMsgs, inputEncryptedChat, randomId, data);
secretChat->increaseOutSeqNo();
secretChat->appendToSequence(randomId);
prv->mSecretState.save();
qCDebug(TG_LIB_SECRET) << "Notified our layer:" << CoreTypes::typeLayerVersion;
}
void Telegram::onMessagesDiscardEncryptionResult(qint64 requestId, bool ok) {
SecretChat *secretChat = prv->mSecretState.chats().take(requestId);
ASSERT(secretChat);
qint32 chatId = secretChat->chatId();
if (ok) {
prv->mSecretState.chats().remove(chatId);
prv->mSecretState.save();
qCDebug(TG_LIB_SECRET) << "Discarded secret chat" << chatId;
delete secretChat;
secretChat = 0;
Q_EMIT messagesEncryptedChatDiscarded(chatId);
} else {
qCWarning(TG_LIB_SECRET) << "Could not discard secret chat with id" << chatId;
}
}
void Telegram::onUpdateShort(const Update &update) {
processSecretChatUpdate(update);
}
void Telegram::onUpdatesCombined(const QList<Update> &updates) {
Q_FOREACH (const Update &update, updates) {
processSecretChatUpdate(update);
}
}
void Telegram::onUpdates(const QList<Update> &udts) {
Q_FOREACH (const Update &update, udts) {
processSecretChatUpdate(update);
}
}
SecretChatMessage Telegram::toSecretChatMessage(const EncryptedMessage &encrypted) {
SecretChatMessage secretChatMessage;
qint32 chatId = encrypted.chatId();
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "received encrypted message does not belong to any known secret chat";
return secretChatMessage;
}
secretChatMessage.setChatId(chatId);
secretChatMessage.setDate(encrypted.date());
prv->mDecrypter->setSecretChat(secretChat);
DecryptedMessage decrypted = prv->mDecrypter->decryptEncryptedData(encrypted.randomId(), encrypted.bytes());
secretChatMessage.setDecryptedMessage(decrypted);
// if having a not 0 randomId, the decrypted message is valid
if (decrypted.randomId()) {
EncryptedFile attachment = encrypted.file();
//if attachment, check keyFingerprint
if (attachment.classType() != EncryptedFile::typeEncryptedFileEmpty) {
qint32 receivedKeyFingerprint = attachment.keyFingerprint();
const QByteArray &key = decrypted.media().key();
const QByteArray &iv = decrypted.media().iv();
qint32 computedKeyFingerprint = prv->mCrypto->computeKeyFingerprint(key, iv);
qCDebug(TG_LIB_SECRET) << "received keyFingerprint:" << receivedKeyFingerprint;
qCDebug(TG_LIB_SECRET) << "computed keyFingerprint:" << computedKeyFingerprint;
if (receivedKeyFingerprint != computedKeyFingerprint) {
qCWarning(TG_LIB_SECRET) << "Computed and received key fingerprints are not equals. Discarding message";
return secretChatMessage;
}
secretChatMessage.setAttachment(attachment);
}
prv->mSecretState.save();
}
return secretChatMessage;
}
void Telegram::processSecretChatUpdate(const Update &update) {
switch (static_cast<qint32>(update.classType())) {
case Update::typeUpdateNewEncryptedMessage: {
EncryptedMessage encrypted = update.messageEncrypted();
SecretChatMessage secretChatMessage = toSecretChatMessage(encrypted);
// if having a not 0 randomId, the decrypted message is valid
if (secretChatMessage.decryptedMessage().randomId()) {
prv->mSecretState.save();
qint32 qts = update.qts();
Q_EMIT updateSecretChatMessage(secretChatMessage, qts);
}
break;
}
case Update::typeUpdateEncryption: {
const EncryptedChat &encryptedChat = update.chat();
qint32 chatId = encryptedChat.id();
switch (static_cast<qint32>(encryptedChat.classType())) {
case EncryptedChat::typeEncryptedChatRequested: {
// here, we have received a request of creating a new secret chat. Emit a signal
// with chat details for user B to accept or reject chat creation
qint64 accessHash = encryptedChat.accessHash();
qint32 date = encryptedChat.date();
qint32 adminId = encryptedChat.adminId();
qint32 participantId = encryptedChat.participantId();
QByteArray gA = encryptedChat.gA();
qCDebug(TG_LIB_SECRET) << "Requested secret chat creation:";
qCDebug(TG_LIB_SECRET) << "chatId:" << chatId;
qCDebug(TG_LIB_SECRET) << "date:" << date;
qCDebug(TG_LIB_SECRET) << "adminId:" << adminId;
qCDebug(TG_LIB_SECRET) << "participantId:" << participantId;
qCDebug(TG_LIB_SECRET) << "gA:" << gA.toBase64();
qCDebug(TG_LIB_SECRET) << "ourId:" << ourId();
ASSERT(participantId == ourId());
SecretChat* secretChat = new SecretChat(prv->mSettings);
secretChat->setChatId(encryptedChat.id());
secretChat->setAccessHash(encryptedChat.accessHash());
secretChat->setDate(encryptedChat.date());
secretChat->setAdminId(encryptedChat.adminId());
secretChat->setParticipantId(encryptedChat.participantId());
secretChat->setGAOrB(gA);
secretChat->setState(SecretChat::Requested);
prv->mSecretState.chats().insert(chatId, secretChat);
Q_EMIT messagesEncryptedChatRequested(chatId, date, adminId, accessHash);
break;
}
case EncryptedChat::typeEncryptedChat: {
qCDebug(TG_LIB_SECRET) << "received encrypted chat creation update";
// here, the request for encryption has been accepted. Take the secret chat data
qint64 accessHash = encryptedChat.accessHash();
qint32 date = encryptedChat.date();
qint32 adminId = encryptedChat.adminId();
qint32 participantId = encryptedChat.participantId();
QByteArray gB = encryptedChat.gAOrB();
qint64 keyFingerprint = encryptedChat.keyFingerprint();
qCDebug(TG_LIB_SECRET) << "Peer accepted secret chat creation:";
qCDebug(TG_LIB_SECRET) << "chatId:" << chatId;
qCDebug(TG_LIB_SECRET) << "accessHash:" << accessHash;
qCDebug(TG_LIB_SECRET) << "date:" << date;
qCDebug(TG_LIB_SECRET) << "adminId:" << adminId;
qCDebug(TG_LIB_SECRET) << "participantId:" << participantId;
qCDebug(TG_LIB_SECRET) << "gB:" << gB.toBase64();
qCDebug(TG_LIB_SECRET) << "received keyFingerprint:" << keyFingerprint;
SecretChat *secretChat = prv->mSecretState.chats().value(chatId);
if (!secretChat) {
qCWarning(TG_LIB_SECRET) << "Could not find secret chat with id" << chatId;
return;
}
createSharedKey(secretChat, prv->mSecretState.p(), gB);
qint64 calculatedKeyFingerprint = secretChat->keyFingerprint();
qCDebug(TG_LIB_SECRET) << "calculated keyFingerprint:" << calculatedKeyFingerprint;
if (calculatedKeyFingerprint == keyFingerprint) {
qCDebug(TG_LIB_SECRET) << "Generated shared key for secret chat" << chatId;
secretChat->setChatId(chatId);
secretChat->setAccessHash(accessHash);
secretChat->setDate(date);
secretChat->setAdminId(adminId);
secretChat->setParticipantId(participantId);
secretChat->setState(SecretChat::Accepted);
qCDebug(TG_LIB_SECRET) << "Joined to secret chat" << chatId << "with peer" << participantId;
prv->mSecretState.save();
Q_EMIT messagesEncryptedChatCreated(chatId, date, participantId, accessHash);
//notify peer about our layer
InputEncryptedChat inputEncryptedChat;
inputEncryptedChat.setChatId(chatId);
inputEncryptedChat.setAccessHash(accessHash);
prv->mEncrypter->setSecretChat(secretChat);
qint64 randomId;
Utils::randomBytes(&randomId, 8);
QList<qint64> previousMsgs = secretChat->sequence();
DecryptedMessageBuilder builder(secretChat->layer());
DecryptedMessage decryptedMessage = builder.buildDecryptedMessageForNotifyLayer(randomId, CoreTypes::typeLayerVersion);
QByteArray data = prv->mEncrypter->generateEncryptedData(decryptedMessage);
prv->mApi->messagesSendEncryptedService(previousMsgs, inputEncryptedChat, randomId, data);
secretChat->increaseOutSeqNo();
secretChat->appendToSequence(randomId);