forked from ars3niy/tdlib-purple
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtd-client.cpp
2366 lines (2105 loc) · 109 KB
/
td-client.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
#include "td-client.h"
#include "purple-info.h"
#include "config.h"
#include "format.h"
#include "receiving.h"
#include "file-transfer.h"
#include "call.h"
#include "secret-chat.h"
#include "sticker.h"
#include "receiving.h"
#include <unistd.h>
#include <stdlib.h>
#include <algorithm>
enum {
// Typing notifications seems to be resent every 5-6 seconds, so 10s timeout hould be appropriate
REMOTE_TYPING_NOTICE_TIMEOUT = 10,
SUPERGROUP_MEMBER_LIMIT = 200,
};
PurpleTdClient::PurpleTdClient(PurpleAccount *acct, ITransceiverBackend *testBackend)
: m_transceiver(this, acct, &PurpleTdClient::processUpdate, testBackend),
m_data(acct, m_transceiver)
{
StickerConversionThread::setCallback(&PurpleTdClient::onAnimatedStickerConverted);
m_account = acct;
setPurpleConnectionInProgress();
}
PurpleTdClient::~PurpleTdClient()
{
std::vector<PurpleXfer *> transfers;
m_data.removeAllFileTransfers(transfers);
for (PurpleXfer *xfer: transfers) {
// We keep uploads ref'd but not downloads
if (purple_xfer_get_type(xfer) == PURPLE_XFER_SEND)
purple_xfer_unref(xfer);
purple_xfer_cancel_local(xfer);
}
m_data.extractFileTransferRequests(transfers);
for (PurpleXfer *xfer: transfers) {
purple_xfer_unref(xfer);
purple_xfer_cancel_local(xfer);
}
std::vector<IncomingMessage> messages;
m_data.pendingMessages.flush(messages);
// This avoids re-sending download request when displaying message. Doing this for messages
// that don't involve inline downloads is fine.
for (IncomingMessage &fullMessage: messages)
fullMessage.inlineDownloadTimeout = true;
showMessages(messages, m_data);
}
void PurpleTdClient::setLogLevel(int level)
{
// Why not just call setLogVerbosityLevel? No idea!
td::Client::execute({0, td::td_api::make_object<td::td_api::setLogVerbosityLevel>(level)});
}
void PurpleTdClient::setTdlibFatalErrorCallback(td::Log::FatalErrorCallbackPtr callback)
{
td::Log::set_fatal_error_callback(callback);
}
void PurpleTdClient::processUpdate(td::td_api::Object &update)
{
purple_debug_misc(config::pluginId, "Incoming update\n");
switch (update.get_id()) {
case td::td_api::updateAuthorizationState::ID: {
auto &update_authorization_state = static_cast<td::td_api::updateAuthorizationState &>(update);
purple_debug_misc(config::pluginId, "Incoming update: authorization state\n");
if (update_authorization_state.authorization_state_) {
m_lastAuthState = update_authorization_state.authorization_state_->get_id();
processAuthorizationState(*update_authorization_state.authorization_state_);
}
break;
}
case td::td_api::updateUser::ID: {
auto &userUpdate = static_cast<td::td_api::updateUser &>(update);
updateUser(std::move(userUpdate.user_));
break;
}
case td::td_api::updateNewChat::ID: {
auto &newChat = static_cast<td::td_api::updateNewChat &>(update);
purple_debug_misc(config::pluginId, "Incoming update: new chat\n");
if (newChat.chat_->type_->get_id() == td::td_api::chatTypePrivate::ID ||
newChat.chat_->type_->get_id() == td::td_api::chatTypeSecret::ID ||
m_data.isGroupChatWithMembership(*newChat.chat_.get()))
addChat(std::move(newChat.chat_));
else {
purple_debug_misc(config::pluginId,
"Incoming update: ignorig ID=%d\n",
update.get_id());
purple_debug_misc(config::pluginId,
"Not adding a group that we are not a member of");
}
break;
}
case td::td_api::updateNewMessage::ID: {
auto &newMessageUpdate = static_cast<td::td_api::updateNewMessage &>(update);
purple_debug_misc(config::pluginId, "Incoming update: new message\n");
if (newMessageUpdate.message_)
onIncomingMessage(std::move(newMessageUpdate.message_));
else
purple_debug_warning(config::pluginId, "Received null new message\n");
break;
}
case td::td_api::updateUserStatus::ID: {
auto &updateStatus = static_cast<td::td_api::updateUserStatus &>(update);
purple_debug_misc(config::pluginId, "Incoming update: user status\n");
if (updateStatus.status_)
updateUserStatus(getUserId(updateStatus), std::move(updateStatus.status_));
break;
}
case td::td_api::updateChatAction::ID: {
auto &updateChatAction = static_cast<td::td_api::updateChatAction &>(update);
purple_debug_misc(config::pluginId, "Incoming update: chat action %d\n",
updateChatAction.action_ ? updateChatAction.action_->get_id() : 0);
handleUserChatAction(updateChatAction);
break;
}
case td::td_api::updateBasicGroup::ID: {
auto &groupUpdate = static_cast<td::td_api::updateBasicGroup &>(update);
updateGroup(std::move(groupUpdate.basic_group_));
break;
}
case td::td_api::updateSupergroup::ID: {
auto &groupUpdate = static_cast<td::td_api::updateSupergroup &>(update);
updateSupergroup(std::move(groupUpdate.supergroup_));
break;
}
case td::td_api::updateBasicGroupFullInfo::ID: {
auto &groupUpdate = static_cast<td::td_api::updateBasicGroupFullInfo &>(update);
updateGroupFull(getBasicGroupId(groupUpdate), std::move(groupUpdate.basic_group_full_info_));
break;
};
case td::td_api::updateSupergroupFullInfo::ID: {
auto &groupUpdate = static_cast<td::td_api::updateSupergroupFullInfo &>(update);
updateSupergroupFull(getSupergroupId(groupUpdate), std::move(groupUpdate.supergroup_full_info_));
break;
};
case td::td_api::updateMessageSendSucceeded::ID: {
auto &sendSucceeded = static_cast<const td::td_api::updateMessageSendSucceeded &>(update);
purple_debug_misc(config::pluginId, "Incoming update: message %" G_GINT64_FORMAT " send succeeded\n",
sendSucceeded.old_message_id_);
removeTempFile(sendSucceeded.old_message_id_);
break;
}
case td::td_api::updateMessageSendFailed::ID: {
auto &sendFailed = static_cast<const td::td_api::updateMessageSendFailed &>(update);
purple_debug_misc(config::pluginId, "Incoming update: message %" G_GINT64_FORMAT " send failed\n",
sendFailed.old_message_id_);
removeTempFile(sendFailed.old_message_id_);
notifySendFailed(sendFailed, m_data);
// TODO notify in chat
break;
}
case td::td_api::updateChatPosition::ID: {
auto &chatPositionUpdate = static_cast<td::td_api::updateChatPosition &>(update);
purple_debug_misc(config::pluginId, "Incoming update: update chat position for chat %" G_GINT64_FORMAT "\n",
chatPositionUpdate.chat_id_);
if (chatPositionUpdate.position_)
m_data.updateChatPosition(getChatId(chatPositionUpdate), std::move(chatPositionUpdate.position_));
updateChat(m_data.getChat(getChatId(chatPositionUpdate)));
break;
}
case td::td_api::updateChatTitle::ID: {
auto &chatTitleUpdate = static_cast<td::td_api::updateChatTitle &>(update);
purple_debug_misc(config::pluginId, "Incoming update: update chat title for chat %" G_GINT64_FORMAT "\n",
chatTitleUpdate.chat_id_);
m_data.updateChatTitle(getChatId(chatTitleUpdate), chatTitleUpdate.title_);
updateChat(m_data.getChat(getChatId(chatTitleUpdate)));
break;
}
case td::td_api::updateChatLastMessage::ID: {
auto &lastMessage = static_cast<td::td_api::updateChatLastMessage &>(update);
updateChatLastMessage(lastMessage);
break;
}
case td::td_api::updateOption::ID: {
const td::td_api::updateOption &option = static_cast<const td::td_api::updateOption &>(update);
updateOption(option, m_data);
break;
}
case td::td_api::updateFile::ID: {
auto &fileUpdate = static_cast<const td::td_api::updateFile &>(update);
purple_debug_misc(config::pluginId, "Incoming update: file update, id %d\n",
fileUpdate.file_ ? fileUpdate.file_->id_ : 0);
if (fileUpdate.file_)
updateFileTransferProgress(*fileUpdate.file_, m_transceiver, m_data,
&PurpleTdClient::sendMessageResponse);
break;
};
case td::td_api::updateSecretChat::ID: {
auto &chatUpdate = static_cast<td::td_api::updateSecretChat &>(update);
purple_debug_misc(config::pluginId, "Incoming update: secret chat, id %d\n",
chatUpdate.secret_chat_ ? chatUpdate.secret_chat_->id_ : 0);
updateSecretChat(std::move(chatUpdate.secret_chat_), m_transceiver, m_data);
break;
};
case td::td_api::updateCall::ID: {
auto &callUpdate = static_cast<const td::td_api::updateCall &>(update);
if (callUpdate.call_) {
purpleDebug("Call update: id {}, outgoing={}, user id {}, state {}", {
std::to_string(callUpdate.call_->id_),
std::to_string(callUpdate.call_->user_id_),
std::to_string((int)callUpdate.call_->is_outgoing_),
std::to_string(callUpdate.call_->state_ ? callUpdate.call_->state_->get_id() : 0)});
updateCall(*callUpdate.call_, m_data, m_transceiver);
}
break;
};
default:
purple_debug_misc(config::pluginId, "Incoming update: ignorig ID=%d\n", update.get_id());
break;
}
}
void PurpleTdClient::processAuthorizationState(td::td_api::AuthorizationState &authState)
{
switch (authState.get_id()) {
case td::td_api::authorizationStateWaitEmailAddress::ID:
purple_debug_misc(config::pluginId, "Authorization email requested\n");
requestAuthEmail();
break;
case td::td_api::authorizationStateWaitEmailCode::ID:
purple_debug_misc(config::pluginId, "Authorization email confirmation code requested\n");
requestAuthEmailCode();
break;
case td::td_api::authorizationStateWaitTdlibParameters::ID:
purple_debug_misc(config::pluginId, "Authorization state update: TDLib parameters requested\n");
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::disableProxy>(), nullptr);
if (addProxy()) {
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::getProxies>(),
&PurpleTdClient::getProxiesResponse);
sendTdlibParameters();
}
break;
case td::td_api::authorizationStateWaitPhoneNumber::ID:
purple_debug_misc(config::pluginId, "Authorization state update: phone number requested\n");
sendPhoneNumber();
break;
case td::td_api::authorizationStateWaitCode::ID: {
auto &codeState = static_cast<td::td_api::authorizationStateWaitCode &>(authState);
purple_debug_misc(config::pluginId, "Authorization state update: authentication code requested\n");
requestAuthCode(codeState.code_info_.get());
break;
}
case td::td_api::authorizationStateWaitRegistration::ID: {
purple_debug_misc(config::pluginId, "Authorization state update: new user registration\n");
registerUser();
break;
}
case td::td_api::authorizationStateWaitPassword::ID: {
purple_debug_misc(config::pluginId, "Authorization state update: password requested\n");
auto &pwInfo = static_cast<const td::td_api::authorizationStateWaitPassword &>(authState);
requestPassword(pwInfo);
break;
}
case td::td_api::authorizationStateReady::ID:
purple_debug_misc(config::pluginId, "Authorization state update: ready\n");
onLoggedIn();
break;
}
}
bool PurpleTdClient::addProxy()
{
PurpleProxyInfo *purpleProxy = purple_proxy_get_setup(m_account);
PurpleProxyType proxyType = purpleProxy ? purple_proxy_info_get_type(purpleProxy) : PURPLE_PROXY_NONE;
const char * username = purpleProxy ? purple_proxy_info_get_username(purpleProxy) : "";
const char * password = purpleProxy ? purple_proxy_info_get_password(purpleProxy) : "";
const char * host = purpleProxy ? purple_proxy_info_get_host(purpleProxy) : "";
int port = purpleProxy ? purple_proxy_info_get_port(purpleProxy) : 0;
if (username == NULL) username = "";
if (password == NULL) password = "";
if (host == NULL) host = "";
std::string errorMessage;
td::td_api::object_ptr<td::td_api::ProxyType> tdProxyType;
switch (proxyType) {
case PURPLE_PROXY_NONE:
tdProxyType = nullptr;
break;
case PURPLE_PROXY_SOCKS5:
tdProxyType = td::td_api::make_object<td::td_api::proxyTypeSocks5>(username, password);
break;
case PURPLE_PROXY_HTTP:
tdProxyType = td::td_api::make_object<td::td_api::proxyTypeHttp>(username, password, true);
break;
default:
// TRANSLATOR: Buddy-window error message, argument will be some kind of proxy-identifier.
errorMessage = formatMessage(_("Proxy type {} is not supported"), proxyTypeToString(proxyType));
break;
}
if (!errorMessage.empty()) {
purple_connection_error(purple_account_get_connection(m_account), errorMessage.c_str());
return false;
} else if (tdProxyType) {
auto addProxy = td::td_api::make_object<td::td_api::addProxy>();
addProxy->server_ = host;
addProxy->port_ = port;
addProxy->enable_ = true;
addProxy->type_ = std::move(tdProxyType);
m_transceiver.sendQuery(std::move(addProxy), &PurpleTdClient::addProxyResponse);
m_isProxyAdded = true;
}
return true;
}
void PurpleTdClient::addProxyResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
if (object && (object->get_id() == td::td_api::proxy::ID)) {
m_addedProxy = td::move_tl_object_as<td::td_api::proxy>(object);
if (m_proxies)
removeOldProxies();
} else {
// TRANSLATOR: Buddy-window error message
std::string message = formatMessage(_("Could not set proxy: {}"), getDisplayedError(object));
purple_connection_error(purple_account_get_connection(m_account), message.c_str());
}
}
void PurpleTdClient::getProxiesResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
if (object && (object->get_id() == td::td_api::proxies::ID)) {
m_proxies = td::move_tl_object_as<td::td_api::proxies>(object);
if (!m_isProxyAdded || m_addedProxy)
removeOldProxies();
} else {
// TRANSLATOR: Buddy-window error message
std::string message = formatMessage(_("Could not get proxies: {}"), getDisplayedError(object));
purple_connection_error(purple_account_get_connection(m_account), message.c_str());
}
}
void PurpleTdClient::removeOldProxies()
{
for (const td::td_api::object_ptr<td::td_api::proxy> &proxy: m_proxies->proxies_)
if (proxy && (!m_addedProxy || (proxy->id_ != m_addedProxy->id_)))
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::removeProxy>(proxy->id_), nullptr);
}
std::string PurpleTdClient::getBaseDatabasePath()
{
return std::string(purple_user_dir()) + G_DIR_SEPARATOR_S + config::configSubdir;
}
static void stuff(td::td_api::setTdlibParameters ¶meters)
{
std::string s(config::stuff);
for (size_t i = 0; i < s.length(); i++)
s[i] -= 16;
size_t i = s.find('i');
if (i == std::string::npos)
return;
s[i] = ' ';
sscanf(s.c_str(), "%" G_GINT32_FORMAT, ¶meters.api_id_);
parameters.api_hash_ = s.c_str()+i+1;
}
void PurpleTdClient::sendTdlibParameters()
{
auto parameters = td::td_api::make_object<td::td_api::setTdlibParameters>();
const char *username = purple_account_get_username(m_account);
const char *api_id = purple_account_get_string(m_account, AccountOptions::ApiId, "");
const char *api_hash = purple_account_get_string(m_account, AccountOptions::ApiHash, "");
parameters->database_directory_ = getBaseDatabasePath() + G_DIR_SEPARATOR_S + username;
purple_debug_misc(config::pluginId, "Account %s using database directory %s\n",
username, parameters->database_directory_.c_str());
parameters->use_chat_info_database_ = true;
parameters->use_message_database_ = true;
parameters->use_secret_chats_ = (purple_account_get_bool(m_account, AccountOptions::EnableSecretChats,
AccountOptions::EnableSecretChatsDefault) != FALSE);
parameters->api_id_ = atoi((api_id == nullptr || strlen(api_id) == 0) ? config::api_id : api_id);
parameters->api_hash_ = (api_hash == nullptr || strlen(api_hash) == 0) ? config::api_hash : api_hash;
if (*config::stuff)
stuff(*parameters);
parameters->system_language_code_ = "en";
parameters->device_model_ = "Desktop";
parameters->system_version_ = "Unknown";
parameters->application_version_ = "1.0";
m_transceiver.sendQuery(std::move(parameters),
&PurpleTdClient::authResponse);
}
void PurpleTdClient::sendPhoneNumber()
{
const char *number = purple_account_get_username(m_account);
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::setAuthenticationPhoneNumber>(number, nullptr),
&PurpleTdClient::authResponse);
}
static std::string getAuthCodeDesc(const td::td_api::AuthenticationCodeType &codeType)
{
switch (codeType.get_id()) {
case td::td_api::authenticationCodeTypeTelegramMessage::ID:
// TRANSLATOR: Authentication dialog, secondary content. Appears after a colon (':'). Argument is a number.
return formatMessage(_("Telegram message (length: {})"),
static_cast<const td::td_api::authenticationCodeTypeTelegramMessage &>(codeType).length_);
case td::td_api::authenticationCodeTypeSms::ID:
// TRANSLATOR: Authentication dialog, secondary content. Appears after a colon (':'). Argument is a number.
return formatMessage(_("SMS (length: {})"),
static_cast<const td::td_api::authenticationCodeTypeSms &>(codeType).length_);
case td::td_api::authenticationCodeTypeCall::ID:
// TRANSLATOR: Authentication dialog, secondary content. Appears after a colon (':'). Argument is a number.
return formatMessage(_("Phone call (length: {})"),
static_cast<const td::td_api::authenticationCodeTypeCall &>(codeType).length_);
case td::td_api::authenticationCodeTypeFlashCall::ID:
// TRANSLATOR: Authentication dialog, secondary content. Official name "flash call". Appears after a colon (':'). Argument is some text-string-ish.
return formatMessage(_("Poor man's phone call (pattern: {})"),
static_cast<const td::td_api::authenticationCodeTypeFlashCall &>(codeType).pattern_);
default:
// Shouldn't happen, so don't translate.
return "Pigeon post";
}
}
void PurpleTdClient::requestAuthCode(const td::td_api::authenticationCodeInfo *codeInfo)
{
// TRANSLATOR: Authentication dialog, primary content. Will be followed by instructions and an input box.
std::string message = _("Enter authentication code") + std::string("\n");
if (codeInfo) {
if (codeInfo->type_) {
// TRANSLATOR: Authentication dialog, secondary content. Argument will be a term.
message += formatMessage(_("Code sent via: {}"), getAuthCodeDesc(*codeInfo->type_)) + "\n";
}
if (codeInfo->next_type_) {
// TRANSLATOR: Authentication dialog, secondary content. Argument will be a term.
message += formatMessage(_("Next code will be: {}"), getAuthCodeDesc(*codeInfo->next_type_)) + "\n";
}
}
purple_request_input (purple_account_get_connection(m_account),
// TRANSLATOR: Authentication dialog, title.
_("Login code"),
message.c_str(),
NULL, // secondary message
NULL, // default value
FALSE, // multiline input
FALSE, // masked input
NULL,
// TRANSLATOR: Authentication dialog, alternative is "_Cancel". The underscore marks accelerator keys, they must be different!
_("_OK"), G_CALLBACK(requestCodeEntered),
// TRANSLATOR: Authentication dialog, alternative is "_OK". The underscore marks accelerator keys, they must be different!
_("_Cancel"), G_CALLBACK(requestCodeCancelled),
m_account,
NULL, // buddy
NULL, // conversation
this);
}
void PurpleTdClient::requestAuthEmail()
{
std::string message = _("Enter authentication email") + std::string("\n");
purple_request_input (purple_account_get_connection(m_account),
// TRANSLATOR: Authentication dialog, title.
_("Authentication email"),
message.c_str(),
NULL, // secondary message
NULL, // default value
FALSE, // multiline input
FALSE, // masked input
NULL,
// TRANSLATOR: Authentication dialog, alternative is "_Cancel". The underscore marks accelerator keys, they must be different!
_("_OK"), G_CALLBACK(requestAuthEmailEntered),
// TRANSLATOR: Authentication dialog, alternative is "_OK". The underscore marks accelerator keys, they must be different!
_("_Cancel"), G_CALLBACK(requestAuthEmailCancelled),
m_account,
NULL, // buddy
NULL, // conversation
this);
}
void PurpleTdClient::requestAuthEmailEntered(PurpleTdClient *self, const gchar *email)
{
purple_debug_misc(config::pluginId, "Authentication email entered: '%s'\n", email);
auto authEmail = td::td_api::make_object<td::td_api::setAuthenticationEmailAddress>(email);
self->m_transceiver.sendQuery(std::move(authEmail), &PurpleTdClient::authResponse);
}
void PurpleTdClient::requestAuthEmailCancelled(PurpleTdClient *self)
{
purple_connection_error(purple_account_get_connection(self->m_account),
// TRANSLATOR: Connection failure, error message (title; empty content)
_("Authentication email required"));
}
void PurpleTdClient::requestAuthEmailCode()
{
std::string message = _("Enter code sent to authentication email") + std::string("\n");
purple_request_input (purple_account_get_connection(m_account),
// TRANSLATOR: Authentication dialog, title.
_("Code from authentication email"),
message.c_str(),
NULL, // secondary message
NULL, // default value
FALSE, // multiline input
FALSE, // masked input
NULL,
// TRANSLATOR: Authentication dialog, alternative is "_Cancel". The underscore marks accelerator keys, they must be different!
_("_OK"), G_CALLBACK(requestAuthEmailCodeEntered),
// TRANSLATOR: Authentication dialog, alternative is "_OK". The underscore marks accelerator keys, they must be different!
_("_Cancel"), G_CALLBACK(requestAuthEmailCodeCancelled),
m_account,
NULL, // buddy
NULL, // conversation
this);
}
void PurpleTdClient::requestAuthEmailCodeEntered(PurpleTdClient *self, const gchar *code)
{
purple_debug_misc(config::pluginId, "Authentication email code entered: '%s'\n", code);
auto authEmailCode = td::td_api::make_object<td::td_api::checkAuthenticationEmailCode>(
td::td_api::make_object<td::td_api::emailAddressAuthenticationCode>(code));
self->m_transceiver.sendQuery(std::move(authEmailCode), &PurpleTdClient::authResponse);
}
void PurpleTdClient::requestAuthEmailCodeCancelled(PurpleTdClient *self)
{
purple_connection_error(purple_account_get_connection(self->m_account),
// TRANSLATOR: Connection failure, error message (title; empty content)
_("Authentication email required"));
}
void PurpleTdClient::requestCodeEntered(PurpleTdClient *self, const gchar *code)
{
purple_debug_misc(config::pluginId, "Authentication code entered: '%s'\n", code);
auto checkCode = td::td_api::make_object<td::td_api::checkAuthenticationCode>();
if (code)
checkCode->code_ = code;
self->m_transceiver.sendQuery(std::move(checkCode), &PurpleTdClient::authResponse);
}
void PurpleTdClient::requestCodeCancelled(PurpleTdClient *self)
{
purple_connection_error(purple_account_get_connection(self->m_account),
// TRANSLATOR: Connection failure, error message (title; empty content)
_("Authentication code required"));
}
void PurpleTdClient::passwordEntered(PurpleTdClient *self, const gchar *password)
{
purple_debug_misc(config::pluginId, "Password code entered\n");
auto checkPassword = td::td_api::make_object<td::td_api::checkAuthenticationPassword>();
if (password)
checkPassword->password_ = password;
self->m_transceiver.sendQuery(std::move(checkPassword), &PurpleTdClient::authResponse);
}
void PurpleTdClient::passwordCancelled(PurpleTdClient *self)
{
// TRANSLATOR: Connection failure, error message title (title; empty content)
purple_connection_error(purple_account_get_connection(self->m_account), _("Password required"));
}
void PurpleTdClient::requestPassword(const td::td_api::authorizationStateWaitPassword &pwInfo)
{
std::string hints;
if (!pwInfo.password_hint_.empty()) {
// TRANSLATOR: 2FA dialog, secondary content, appears in new line. Argument is an arbitrary string from Telegram.
hints = formatMessage(_("Hint: {}"), pwInfo.password_hint_);
}
if (!pwInfo.recovery_email_address_pattern_.empty()) {
if (!hints.empty())
hints += '\n';
// TRANSLATOR: 2FA dialog, secondary content, appears in new line. Argument is an e-mail address.
hints += formatMessage(_("Recovery e-mail may have been sent to {}"), pwInfo.recovery_email_address_pattern_);
}
if (!purple_request_input (purple_account_get_connection(m_account),
// TRANSLATOR: 2FA dialog, title
_("Password"),
// TRANSLATOR: 2FA dialog, primary content
_("Enter password for two-factor authentication"),
hints.empty() ? NULL : hints.c_str(),
NULL, // default value
FALSE, // multiline input
FALSE, // masked input
NULL,
// TRANSLATOR: 2FA dialog, alternative is "_Cancel". The underscore marks accelerator keys, they must be different!
_("_OK"), G_CALLBACK(passwordEntered),
// TRANSLATOR: 2FA dialog, alternative is "_OK". The underscore marks accelerator keys, they must be different!
_("_Cancel"), G_CALLBACK(passwordCancelled),
m_account,
NULL, // buddy
NULL, // conversation
this))
{
// Only happens with like empathy, not worth translating
purple_connection_error(purple_account_get_connection(m_account),
"Authentication code is required but this libpurple doesn't support input requests");
}
}
void PurpleTdClient::registerUser()
{
std::string firstName, lastName;
getNamesFromAlias(purple_account_get_alias(m_account), firstName, lastName);
if (firstName.empty() && lastName.empty()) {
if (!purple_request_input (purple_account_get_connection(m_account),
// TRANSLATOR: Registration dialog, title
_("Registration"),
// TRANSLATOR: Registration dialog, content
_("New account is being created. Please enter your display name."),
NULL,
NULL, // default value
FALSE, // multiline input
FALSE, // masked input
NULL,
// TRANSLATOR: Registration dialog, alternative is "_Cancel". The underscore marks accelerator keys, they must be different!
_("_OK"), G_CALLBACK(displayNameEntered),
// TRANSLATOR: Registration dialog, alternative is "_OK". The underscore marks accelerator keys, they must be different!
_("_Cancel"), G_CALLBACK(displayNameCancelled),
m_account,
NULL, // buddy
NULL, // conversation
this))
{
// Same as when requesting authentication code - not worth translating
purple_connection_error(purple_account_get_connection(m_account),
"Registration is required but this libpurple doesn't support input requests");
}
} else
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::registerUser>(firstName, lastName, false),
&PurpleTdClient::authResponse);
}
void PurpleTdClient::displayNameEntered(PurpleTdClient *self, const gchar *name)
{
std::string firstName, lastName;
getNamesFromAlias(name, firstName, lastName);
if (firstName.empty() && lastName.empty())
purple_connection_error(purple_account_get_connection(self->m_account),
// TRANSLATOR: Connection error message after failed registration.
_("Display name is required for registration"));
else
self->m_transceiver.sendQuery(td::td_api::make_object<td::td_api::registerUser>(firstName, lastName, false),
&PurpleTdClient::authResponse);
}
void PurpleTdClient::displayNameCancelled(PurpleTdClient *self)
{
purple_connection_error(purple_account_get_connection(self->m_account),
// TRANSLATOR: Connection error message after failed registration.
_("Display name is required for registration"));
}
void PurpleTdClient::authResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
if (object && (object->get_id() == td::td_api::ok::ID))
purple_debug_misc(config::pluginId, "Authentication success on query %lu\n", (unsigned long)requestId);
else
notifyAuthError(object);
}
void PurpleTdClient::notifyAuthError(const td::td_api::object_ptr<td::td_api::Object> &response)
{
std::string message;
message = _("Authentication error: {}");
message = formatMessage(message.c_str(), getDisplayedError(response));
purple_connection_error(purple_account_get_connection(m_account), message.c_str());
}
void PurpleTdClient::setPurpleConnectionInProgress()
{
purple_debug_misc(config::pluginId, "Connection in progress\n");
PurpleConnection *gc = purple_account_get_connection(m_account);
if (PURPLE_CONNECTION_IS_CONNECTED(gc))
purple_blist_remove_account(m_account);
purple_connection_set_state (gc, PURPLE_CONNECTING);
purple_connection_update_progress(gc, "Connecting", 1, 2);
}
void PurpleTdClient::onLoggedIn()
{
purple_connection_set_state (purple_account_get_connection(m_account), PURPLE_CONNECTED);
// This query ensures an updateUser for every contact
m_transceiver.sendQuery(td::td_api::make_object<td::td_api::getContacts>(),
&PurpleTdClient::getContactsResponse);
}
void PurpleTdClient::getContactsResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
purple_debug_misc(config::pluginId, "getContacts response to request %" G_GUINT64_FORMAT "\n", requestId);
if (object && (object->get_id() == td::td_api::users::ID)) {
m_data.setContacts(*td::move_tl_object_as<td::td_api::users>(object));
auto getChatsRequest = td::td_api::make_object<td::td_api::loadChats>();
getChatsRequest->chat_list_ = td::td_api::make_object<td::td_api::chatListMain>();
getChatsRequest->limit_ = 200;
m_transceiver.sendQuery(std::move(getChatsRequest), &PurpleTdClient::getChatsResponse);
} else
notifyAuthError(object);
}
void PurpleTdClient::getChatsResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
purple_debug_misc(config::pluginId, "getChats response to request %" G_GUINT64_FORMAT "\n", requestId);
if (object && (object->get_id() == td::td_api::ok::ID)) {
auto getChatsRequest = td::td_api::make_object<td::td_api::loadChats>();
getChatsRequest->chat_list_ = td::td_api::make_object<td::td_api::chatListMain>();
getChatsRequest->limit_ = 200;
m_transceiver.sendQuery(std::move(getChatsRequest), &PurpleTdClient::getChatsResponse);
} else {
std::string message = getDisplayedError(object);
purple_debug_misc(config::pluginId, "Got no more chats: %s\n", message.c_str());
m_data.getContactsWithNoChat(m_usersForNewPrivateChats);
requestMissingPrivateChats();
}
}
void PurpleTdClient::requestMissingPrivateChats()
{
if (m_usersForNewPrivateChats.empty()) {
purple_debug_misc(config::pluginId, "Login sequence complete\n");
onChatListReady();
} else {
UserId userId = m_usersForNewPrivateChats.back();
m_usersForNewPrivateChats.pop_back();
purpleDebug("Requesting private chat for user id {}", userId.value());
td::td_api::object_ptr<td::td_api::createPrivateChat> createChat =
td::td_api::make_object<td::td_api::createPrivateChat>(userId.value(), false);
m_transceiver.sendQuery(std::move(createChat), &PurpleTdClient::loginCreatePrivateChatResponse);
}
}
void PurpleTdClient::loginCreatePrivateChatResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
if (object && (object->get_id() == td::td_api::chat::ID)) {
td::td_api::object_ptr<td::td_api::chat> chat = td::move_tl_object_as<td::td_api::chat>(object);
purple_debug_misc(config::pluginId, "Requested private chat received: id %" G_GINT64_FORMAT "\n",
chat->id_);
// Here the "new" chat already exists in AccountData because there has just been
// updateNewChat about this same chat. But do addChat anyway, just in case.
m_data.addChat(std::move(chat));
} else
purple_debug_misc(config::pluginId, "Failed to get requested private chat\n");
requestMissingPrivateChats();
}
void PurpleTdClient::requestBasicGroupFullInfo(BasicGroupId groupId)
{
if (!m_data.isBasicGroupInfoRequested(groupId)) {
m_data.setBasicGroupInfoRequested(groupId);
uint64_t requestId = m_transceiver.sendQuery(td::td_api::make_object<td::td_api::getBasicGroupFullInfo>(groupId.value()),
&PurpleTdClient::groupInfoResponse);
m_data.addPendingRequest<GroupInfoRequest>(requestId, groupId);
}
}
void PurpleTdClient::requestSupergroupFullInfo(SupergroupId groupId)
{
if (!m_data.isSupergroupInfoRequested(groupId)) {
m_data.setSupergroupInfoRequested(groupId);
uint64_t requestId = m_transceiver.sendQuery(td::td_api::make_object<td::td_api::getSupergroupFullInfo>(groupId.value()),
&PurpleTdClient::supergroupInfoResponse);
m_data.addPendingRequest<SupergroupInfoRequest>(requestId, groupId);
auto getMembersReq = td::td_api::make_object<td::td_api::getSupergroupMembers>();
getMembersReq->supergroup_id_ = groupId.value();
getMembersReq->filter_ = td::td_api::make_object<td::td_api::supergroupMembersFilterRecent>();
getMembersReq->limit_ = SUPERGROUP_MEMBER_LIMIT;
requestId = m_transceiver.sendQuery(std::move(getMembersReq), &PurpleTdClient::supergroupMembersResponse);
m_data.addPendingRequest<SupergroupInfoRequest>(requestId, groupId);
}
}
// TODO process messageChatAddMembers and messageChatDeleteMember
// TODO process messageChatUpgradeTo and messageChatUpgradeFrom
void PurpleTdClient::groupInfoResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
std::unique_ptr<GroupInfoRequest> request = m_data.getPendingRequest<GroupInfoRequest>(requestId);
if (request && object && (object->get_id() == td::td_api::basicGroupFullInfo::ID)) {
td::td_api::object_ptr<td::td_api::basicGroupFullInfo> groupInfo =
td::move_tl_object_as<td::td_api::basicGroupFullInfo>(object);
updateGroupFull(request->groupId, std::move(groupInfo));
}
}
void PurpleTdClient::supergroupInfoResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
std::unique_ptr<SupergroupInfoRequest> request = m_data.getPendingRequest<SupergroupInfoRequest>(requestId);
if (request && object && (object->get_id() == td::td_api::supergroupFullInfo::ID)) {
td::td_api::object_ptr<td::td_api::supergroupFullInfo> groupInfo =
td::move_tl_object_as<td::td_api::supergroupFullInfo>(object);
updateSupergroupFull(request->groupId, std::move(groupInfo));
}
}
void PurpleTdClient::supergroupMembersResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
std::unique_ptr<SupergroupInfoRequest> request = m_data.getPendingRequest<SupergroupInfoRequest>(requestId);
if (request && object && (object->get_id() == td::td_api::chatMembers::ID)) {
td::td_api::object_ptr<td::td_api::chatMembers> members =
td::move_tl_object_as<td::td_api::chatMembers>(object);
auto getMembersReq = td::td_api::make_object<td::td_api::getSupergroupMembers>();
getMembersReq->supergroup_id_ = request->groupId.value();
getMembersReq->filter_ = td::td_api::make_object<td::td_api::supergroupMembersFilterAdministrators>();
getMembersReq->limit_ = SUPERGROUP_MEMBER_LIMIT;
uint64_t newRequestId = m_transceiver.sendQuery(std::move(getMembersReq), &PurpleTdClient::supergroupAdministratorsResponse);
m_data.addPendingRequest<GroupMembersRequestCont>(newRequestId, request->groupId, members.release());
}
}
void PurpleTdClient::supergroupAdministratorsResponse(uint64_t requestId, td::td_api::object_ptr<td::td_api::Object> object)
{
std::unique_ptr<GroupMembersRequestCont> request = m_data.getPendingRequest<GroupMembersRequestCont>(requestId);
if (request) {
auto members = std::move(request->members);
if (object && (object->get_id() == td::td_api::chatMembers::ID)) {
td::td_api::object_ptr<td::td_api::chatMembers> newMembers =
td::move_tl_object_as<td::td_api::chatMembers>(object);
for (auto &pNewMember: newMembers->members_) {
if (! pNewMember || !pNewMember->member_id_) continue;
const td::td_api::MessageSender *pNewMemberInfo = pNewMember->member_id_.get();
if (std::find_if(members->members_.begin(), members->members_.end(),
[pNewMemberInfo](const td::td_api::object_ptr<td::td_api::chatMember> &pExistingMember) {
return pExistingMember && pExistingMember->member_id_ &&
isSameUser(*pExistingMember->member_id_, *pNewMemberInfo);
}) == members->members_.end())
{
members->members_.push_back(std::move(pNewMember));
}
}
}
const td::td_api::chat *chat = m_data.getSupergroupChatByGroup(request->groupId);
if (chat) {
PurpleConvChat *purpleChat = findChatConversation(m_account, *chat);
if (purpleChat)
updateSupergroupChatMembers(purpleChat, *members, m_data);
}
m_data.updateSupergroupMembers(request->groupId, std::move(members));
}
}
void PurpleTdClient::updateGroupFull(BasicGroupId groupId, td::td_api::object_ptr<td::td_api::basicGroupFullInfo> groupInfo)
{
const td::td_api::chat *chat = m_data.getBasicGroupChatByGroup(groupId);
if (chat) {
PurpleConvChat *purpleChat = findChatConversation(m_account, *chat);
if (purpleChat)
updateChatConversation(purpleChat, *groupInfo, m_data);
}
m_data.updateBasicGroupInfo(groupId, std::move(groupInfo));
}
void PurpleTdClient::updateSupergroupFull(SupergroupId groupId, td::td_api::object_ptr<td::td_api::supergroupFullInfo> groupInfo)
{
const td::td_api::chat *chat = m_data.getSupergroupChatByGroup(groupId);
if (chat) {
PurpleConvChat *purpleChat = findChatConversation(m_account, *chat);
if (purpleChat)
updateChatConversation(purpleChat, *groupInfo, m_data);
}
m_data.updateSupergroupInfo(groupId, std::move(groupInfo));
}
void PurpleTdClient::onChatListReady()
{
m_chatListReady = true;
std::vector<const td::td_api::chat *> chats;
m_data.getChats(chats);
for (const td::td_api::chat *chat: chats) {
const td::td_api::user *user = m_data.getUserByPrivateChat(*chat);
if (user && isChatInContactList(*chat, user)) {
std::string userName = getPurpleBuddyName(*user);
purple_prpl_got_user_status(m_account, userName.c_str(),
getPurpleStatusId(*user->status_), NULL);
}
}
for (PurpleRoomlist *roomlist: m_pendingRoomLists) {
populateGroupChatList(roomlist, chats, m_data);
purple_roomlist_unref(roomlist);
}
m_pendingRoomLists.clear();
// Here we could remove buddies for which no private chat exists, meaning they have been remove
// from the contact list perhaps in another client
const td::td_api::user *selfInfo = m_data.getUserByPhone(purple_account_get_username(m_account));
if (selfInfo != nullptr) {
std::string alias = makeBasicDisplayName(*selfInfo);
purple_debug_misc(config::pluginId, "Setting own alias to '%s'\n", alias.c_str());
purple_account_set_alias(m_account, alias.c_str());
} else
purple_debug_warning(config::pluginId, "Did not receive user information for self (%s) at login\n",
purple_account_get_username(m_account));
purple_blist_add_account(m_account);
}
void PurpleTdClient::onAnimatedStickerConverted(AccountThread *arg)
{
std::unique_ptr<AccountThread> baseThread(arg);
StickerConversionThread *thread = dynamic_cast<StickerConversionThread *>(arg);
const td::td_api::chat *chat = thread ? m_data.getChat(thread->chatId) : nullptr;
if (!chat || !thread)
return;
IncomingMessage *pendingMessage = m_data.pendingMessages.findPendingMessage(getId(*chat), thread->message().id);
std::string errorMessage = thread->getErrorMessage();
gchar *imageData = NULL;
gsize imageSize = 0;
bool success = false;
if (errorMessage.empty()) {
GError *error = NULL;
g_file_get_contents(thread->getOutputFileName().c_str(), &imageData, &imageSize, &error);
if (error) {
// unlikely error message not worth translating
errorMessage = formatMessage("Could not read converted file {}: {}", {
thread->getOutputFileName(), error->message});
g_error_free(error);
} else
success = true;
remove(thread->getOutputFileName().c_str());
}
if (success) {
int id = purple_imgstore_add_with_id (imageData, imageSize, NULL);
if (pendingMessage) {
pendingMessage->animatedStickerConverted = true;
pendingMessage->animatedStickerConvertSuccess = true;
pendingMessage->animatedStickerImageId = id;
checkMessageReady(pendingMessage, m_transceiver, m_data);
pendingMessage = nullptr;
} else {
std::string text = makeInlineImageText(id);
showMessageText(m_data, *chat, thread->message(), text.c_str(), NULL, PURPLE_MESSAGE_IMAGES);
}
} else {
if (pendingMessage) {
pendingMessage->animatedStickerConverted = true;
pendingMessage->animatedStickerConvertSuccess = false;
checkMessageReady(pendingMessage, m_transceiver, m_data);
pendingMessage = nullptr;
}
// TRANSLATOR: In-chat error message, arguments will be a file name and a proper reason
errorMessage = formatMessage(_("Could not read sticker file {0}: {1}"),