-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
cli.cpp
3028 lines (2768 loc) · 118 KB
/
cli.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 Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/ClientActor.h"
#include "td/telegram/Log.h"
#include "td/telegram/td_api_json.h"
#include "td/actor/actor.h"
#include "td/tl/tl_json.h" // should be included after td_api_json?
#include "memprof/memprof.h"
#include "td/utils/buffer.h"
#include "td/utils/BufferedFd.h"
#include "td/utils/FileLog.h"
#include "td/utils/format.h"
#include "td/utils/JsonBuilder.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/port/Fd.h"
#include "td/utils/port/FileFd.h"
#include "td/utils/port/signals.h"
#include "td/utils/port/Stat.h"
#include "td/utils/port/thread_local.h"
#include "td/utils/Random.h"
#include "td/utils/Slice.h"
#include "td/utils/Status.h"
#include "td/utils/StringBuilder.h"
#include "td/utils/Time.h"
#ifndef USE_READLINE
#include "td/utils/find_boundary.h"
#endif
#include <algorithm>
#include <array>
#include <atomic>
#include <clocale>
#include <cstdlib>
#include <cstring> // for strcmp
#include <ctime>
#include <iostream>
#include <limits>
#include <memory>
#include <queue>
#include <tuple>
#include <unordered_map>
#ifdef USE_READLINE
/* Standard readline include files. */
#include <readline/history.h>
#include <readline/readline.h>
#endif
namespace td {
static void dump_memory_usage() {
if (is_memprof_on()) {
LOG(WARNING) << "memory_dump";
clear_thread_locals();
std::vector<AllocInfo> v;
dump_alloc([&](const AllocInfo &info) { v.push_back(info); });
std::sort(v.begin(), v.end(), [](const AllocInfo &a, const AllocInfo &b) { return a.size > b.size; });
size_t total_size = 0;
size_t other_size = 0;
int cnt = 0;
for (auto &info : v) {
if (cnt++ < 50) {
LOG(WARNING) << td::format::as_size(info.size) << td::format::as_array(info.backtrace);
} else {
other_size += info.size;
}
total_size += info.size;
}
LOG(WARNING) << tag("other", td::format::as_size(other_size));
LOG(WARNING) << tag("total", td::format::as_size(total_size));
LOG(WARNING) << tag("total traces", get_ht_size());
LOG(WARNING) << tag("fast_backtrace_success_rate", get_fast_backtrace_success_rate());
}
}
#ifdef USE_READLINE
const char *prompt = "td_cli> ";
static int32 saved_point;
static string saved_line;
static std::atomic_flag readline_lock = ATOMIC_FLAG_INIT;
static void deactivate_readline() {
while (readline_lock.test_and_set(std::memory_order_acquire)) {
// spin
}
saved_point = rl_point;
saved_line = string(rl_line_buffer, rl_end);
rl_set_prompt("");
rl_replace_line("", 0);
rl_redisplay();
}
static void reactivate_readline() {
rl_set_prompt(prompt);
rl_replace_line(saved_line.c_str(), 0);
rl_point = saved_point;
rl_redisplay();
readline_lock.clear(std::memory_order_release);
}
static char *command_generator(const char *text, int state) {
static vector<CSlice> commands{"GetContacts",
"GetChats",
"GetHistory",
"SetVerbosity",
"SendVideo",
"SearchDocument",
"GetChatMember",
"GetSupergroupAdministrators",
"GetSupergroupBanned",
"GetSupergroupMembers",
"GetFile",
"DownloadFile",
"CancelDownloadFile",
"ImportContacts",
"RemoveContacts",
"DumpNetQueries",
"CreateSecretChat",
"CreateNewSecretChat"};
static size_t cmd_i;
if (state == 0) {
cmd_i = 0;
}
while (cmd_i < commands.size()) {
const char *a = commands[cmd_i++].c_str();
const char *b = text;
const char *c = b;
while (*c && to_lower(*c) == *c) {
c++;
}
bool only_lowercase = !is_alpha(*c);
while (*a && *b) {
if (*a == *b || (only_lowercase && *a == to_upper(*b))) {
b++;
}
a++;
}
if (*b == 0) {
// TODO call to strdup is completely wrong. Readline will try to call std::free() on the returned char*,
// which may be incompatible with the std::malloc() called by strdup
// It is especially likely to happen if Readline is used as dynamic library
// Unfortunately Readline doesn't provide memory allocation functions/memory deallocation callbacks to fix this
#if TD_MSVC
return _strdup(commands[cmd_i - 1].c_str());
#else
return strdup(commands[cmd_i - 1].c_str());
#endif
}
}
return nullptr;
}
static char **tg_cli_completion(const char *text, int start, int end) {
char **matches = nullptr;
if (start == 0) {
matches = rl_completion_matches(text, command_generator);
}
return matches;
}
#endif
class CliLog : public LogInterface {
public:
void append(CSlice slice, int log_level) override {
#ifdef USE_READLINE
deactivate_readline();
#endif
if (log_level == VERBOSITY_NAME(PLAIN)) {
#if TD_WINDOWS
TsCerr() << slice;
#else
TsCerr() << TC_GREEN << slice << TC_EMPTY;
#endif
} else {
default_log_interface->append(slice, log_level);
}
#ifdef USE_READLINE
reactivate_readline();
#endif
}
void rotate() override {
}
};
struct SendMessageInfo {
double start_time = 0;
double quick_ack_time = 0;
double ack_time = 0;
bool empty() const {
return quick_ack_time != 0 || ack_time != 0;
}
};
StringBuilder &operator<<(StringBuilder &sb, const SendMessageInfo &info) {
sb << format::cond(info.quick_ack_time != 0, tag("quick_ack", info.quick_ack_time - info.start_time));
sb << format::cond(info.ack_time != 0, tag("ack", info.ack_time - info.start_time));
return sb;
}
class CliClient final : public Actor {
public:
CliClient(bool use_test_dc, bool get_chat_list, bool disable_network, int32 api_id, string api_hash)
: use_test_dc_(use_test_dc)
, get_chat_list_(get_chat_list)
, disable_network_(disable_network)
, api_id_(api_id)
, api_hash_(api_hash) {
}
static void quit_instance() {
instance_->quit();
}
private:
void start_up() override {
yield();
}
std::unordered_map<uint64, SendMessageInfo> query_id_to_send_message_info_;
std::unordered_map<uint64, SendMessageInfo> message_id_to_send_message_info_;
struct User {
string first_name;
string last_name;
string username;
};
std::unordered_map<int32, User> users_;
std::unordered_map<string, int32> username_to_user_id_;
void register_user(const td_api::user &user) {
User &new_user = users_[user.id_];
new_user.first_name = user.first_name_;
new_user.last_name = user.last_name_;
new_user.username = user.username_;
username_to_user_id_[to_lower(new_user.username)] = user.id_;
}
void print_user(Logger &log, int32 user_id, bool full = false) {
const User *user = &users_[user_id];
log << user->first_name << " " << user->last_name << " #" << user_id;
if (!user->username.empty()) {
log << " @" << user->username;
}
}
void update_users(const td_api::users &users) {
Logger log{*log_interface, VERBOSITY_NAME(PLAIN)};
for (auto &user_id : users.user_ids_) {
if (user_id == 0) {
continue;
}
print_user(log, user_id);
log << "\n";
}
}
std::unordered_map<string, int32> username_to_supergroup_id;
void register_supergroup(const td_api::supergroup &supergroup) {
if (!supergroup.username_.empty()) {
username_to_supergroup_id[to_lower(supergroup.username_)] = supergroup.id_;
}
}
void update_option(const td_api::updateOption &option) {
if (option.name_ == "my_id") {
if (option.value_->get_id() == td_api::optionValueInteger::ID) {
my_id_ = static_cast<const td_api::optionValueInteger *>(option.value_.get())->value_;
LOG(INFO) << "Set my id to " << my_id_;
}
}
}
int64 get_history_chat_id = 0;
int64 search_chat_id = 0;
void on_get_messages(const td_api::messages &messages) {
if (get_history_chat_id != 0) {
int64 last_message_id = 0;
for (auto &m : messages.messages_) {
// LOG(PLAIN) << to_string(m);
if (m->content_->get_id() == td_api::messageText::ID) {
LOG(PLAIN) << td::oneline(static_cast<const td_api::messageText *>(m->content_.get())->text_->text_) << "\n";
}
last_message_id = m->id_;
}
if (last_message_id > 0) {
send_request(make_tl_object<td_api::getChatHistory>(get_history_chat_id, last_message_id, 0, 100, false));
} else {
get_history_chat_id = 0;
}
}
if (search_chat_id != 0) {
if (!messages.messages_.empty()) {
auto last_message_id = messages.messages_.back()->id_;
LOG(ERROR) << (last_message_id >> 20);
send_request(
make_tl_object<td_api::searchChatMessages>(search_chat_id, "", 0, last_message_id, 0, 100,
make_tl_object<td_api::searchMessagesFilterPhotoAndVideo>()));
} else {
search_chat_id = 0;
}
}
}
void on_get_message(const td_api::message &message) {
if (message.sending_state_ != nullptr &&
message.sending_state_->get_id() == td_api::messageSendingStatePending::ID) {
// send_request(make_tl_object<td_api::deleteMessages>(message.chat_id_, vector<int64>{message.id_}, true));
}
}
struct FileGeneration {
int64 id = 0;
string destination;
string source;
int32 part_size = 0;
int32 local_size = 0;
int32 size = 0;
};
vector<FileGeneration> pending_file_generations;
void on_file_generation_start(const td_api::updateFileGenerationStart &update) {
FileGeneration file_generation;
file_generation.id = update.generation_id_;
file_generation.destination = update.destination_path_;
if (update.conversion_ == "#url#") {
// TODO: actually download
file_generation.source = "test.jpg";
file_generation.part_size = 1000000;
} else {
file_generation.source = update.original_path_;
file_generation.part_size = to_integer<int32>(update.conversion_);
}
auto r_stat = stat(file_generation.source);
if (r_stat.is_ok()) {
auto size = r_stat.ok().size_;
if (size <= 0 || size > 1500000000) {
r_stat = Status::Error(400, size == 0 ? Slice("File is empty") : Slice("File is too big"));
}
}
if (r_stat.is_ok()) {
file_generation.size = narrow_cast<int32>(r_stat.ok().size_);
if (file_generation.part_size <= 0) {
file_generation.part_size = file_generation.size;
}
pending_file_generations.push_back(std::move(file_generation));
timeout_expired();
} else {
send_request(make_tl_object<td_api::finishFileGeneration>(
update.generation_id_, td_api::make_object<td_api::error>(400, r_stat.error().message().str())));
}
}
int64 as_chat_id(Slice str) const {
str = trim(str);
if (str[0] == '@') {
auto it = username_to_user_id_.find(to_lower(str.substr(1)));
if (it != username_to_user_id_.end()) {
return it->second;
}
auto it2 = username_to_supergroup_id.find(to_lower(str.substr(1)));
if (it2 != username_to_supergroup_id.end()) {
auto supergroup_id = it2->second;
return static_cast<int64>(-1000'000'000'000ll) - supergroup_id;
}
LOG(ERROR) << "Can't resolve " << str;
return 0;
}
if (str == "me") {
return my_id_;
}
return to_integer<int64>(str);
}
vector<int64> as_chat_ids(Slice chat_ids, char delimiter = ' ') const {
return transform(full_split(chat_ids, delimiter), [this](Slice str) { return as_chat_id(str); });
}
static int64 as_message_id(Slice str) {
return to_integer<int64>(trim(str));
}
static vector<int64> as_message_ids(Slice message_ids_string, char delimiter = ' ') {
return transform(full_split(message_ids_string, delimiter), as_message_id);
}
int32 as_user_id(Slice str) const {
str = trim(str);
if (str[0] == '@') {
auto it = username_to_user_id_.find(to_lower(str.substr(1)));
if (it != username_to_user_id_.end()) {
return it->second;
}
LOG(ERROR) << "Can't find user " << str;
return 0;
}
if (str == "me") {
return my_id_;
}
return to_integer<int32>(str);
}
vector<int32> as_user_ids(Slice user_ids, char delimiter = ' ') const {
return transform(full_split(user_ids, delimiter), [this](Slice str) { return as_user_id(str); });
}
static int32 as_file_id(string str) {
return to_integer<int32>(trim(std::move(str)));
}
static int32 as_call_id(string str) {
return to_integer<int32>(trim(std::move(str)));
}
static td_api::object_ptr<td_api::InputFile> as_input_file_id(string str) {
return make_tl_object<td_api::inputFileId>(as_file_id(str));
}
static tl_object_ptr<td_api::InputFile> as_local_file(string path) {
return make_tl_object<td_api::inputFileLocal>(trim(std::move(path)));
}
static tl_object_ptr<td_api::InputFile> as_generated_file(string original_path, string conversion,
int32 expected_size = 0) {
return make_tl_object<td_api::inputFileGenerated>(trim(original_path), trim(conversion), expected_size);
}
static tl_object_ptr<td_api::location> as_location(string latitude, string longitude) {
return make_tl_object<td_api::location>(to_double(latitude), to_double(longitude));
}
static bool as_bool(string str) {
str = to_lower(str);
return str == "true" || str == "1";
}
template <class T>
static vector<T> to_integers(Slice ids_string, char delimiter = ' ') {
return transform(full_split(ids_string, delimiter), to_integer<T>);
}
void on_result(uint64 id, tl_object_ptr<td_api::Object> result) {
if (id > 0 && GET_VERBOSITY_LEVEL() < VERBOSITY_NAME(td_requests)) {
LOG(ERROR) << "on_result [id=" << id << "] " << to_string(result);
}
auto as_json_str = json_encode<std::string>(ToJson(result));
// LOG(INFO) << "on_result [id=" << id << "] " << as_json_str;
auto copy_as_json_str = as_json_str;
auto as_json_value = json_decode(copy_as_json_str).move_as_ok();
td_api::object_ptr<td_api::Object> object;
from_json(object, as_json_value).ensure();
CHECK(object != nullptr);
auto as_json_str2 = json_encode<std::string>(ToJson(object));
CHECK(as_json_str == as_json_str2) << "\n" << tag("a", as_json_str) << "\n" << tag("b", as_json_str2);
// LOG(INFO) << "on_result [id=" << id << "] " << as_json_str;
int32 result_id = result == nullptr ? 0 : result->get_id();
[&] {
if (id != 0) {
auto it = query_id_to_send_message_info_.find(id);
if (it == query_id_to_send_message_info_.end()) {
return;
}
auto info = it->second;
query_id_to_send_message_info_.erase(id);
if (result_id == td_api::message::ID) {
auto *message = static_cast<const td_api::message *>(result.get());
message_id_to_send_message_info_[message->id_] = info;
}
}
}();
[&] {
if (result_id == td_api::updateMessageSendAcknowledged::ID) {
auto *message = static_cast<const td_api::updateMessageSendAcknowledged *>(result.get());
auto it = message_id_to_send_message_info_.find(message->message_id_);
if (it == message_id_to_send_message_info_.end()) {
return;
}
auto &info = it->second;
info.quick_ack_time = Time::now();
}
}();
[&] {
if (result_id == td_api::updateMessageSendSucceeded::ID) {
auto *message = static_cast<const td_api::updateMessageSendSucceeded *>(result.get());
auto it = message_id_to_send_message_info_.find(message->old_message_id_);
if (it == message_id_to_send_message_info_.end()) {
return;
}
auto info = it->second;
message_id_to_send_message_info_.erase(it);
info.ack_time = Time::now();
LOG(INFO) << info;
}
}();
switch (result_id) {
case td_api::updateUser::ID:
register_user(*static_cast<const td_api::updateUser *>(result.get())->user_);
break;
case td_api::updateSupergroup::ID:
register_supergroup(*static_cast<const td_api::updateSupergroup *>(result.get())->supergroup_);
break;
case td_api::users::ID:
update_users(*static_cast<const td_api::users *>(result.get()));
break;
case td_api::updateOption::ID:
update_option(*static_cast<const td_api::updateOption *>(result.get()));
break;
case td_api::message::ID:
on_get_message(*static_cast<const td_api::message *>(result.get()));
break;
case td_api::messages::ID:
on_get_messages(*static_cast<const td_api::messages *>(result.get()));
break;
case td_api::updateFileGenerationStart::ID:
on_file_generation_start(*static_cast<const td_api::updateFileGenerationStart *>(result.get()));
break;
case td_api::updateChatLastMessage::ID: {
auto message = static_cast<const td_api::updateChatLastMessage *>(result.get())->last_message_.get();
if (message != nullptr && message->content_->get_id() == td_api::messageText::ID) {
// auto text = static_cast<const td_api::messageText *>(message->content_.get())->text_->text_;
}
break;
}
}
}
void on_error(uint64 id, tl_object_ptr<td_api::error> error) {
auto current_verbosity_level = GET_VERBOSITY_LEVEL();
SET_VERBOSITY_LEVEL(VERBOSITY_NAME(INFO));
LOG(INFO) << "on_error [id=" << id << "] " << to_string(error);
SET_VERBOSITY_LEVEL(current_verbosity_level);
}
void on_closed() {
LOG(INFO) << "on_closed";
ready_to_stop_ = true;
if (close_flag_) {
yield();
return;
}
}
void quit() {
if (close_flag_) {
return;
}
LOG(WARNING) << "QUIT";
close_flag_ = true;
dump_memory_usage();
td_.reset();
#if TD_WINDOWS
stdin_reader_.reset();
#else
is_stdin_reader_stopped_ = true;
#endif
yield();
}
#ifdef USE_READLINE
Fd stdin_;
#else
using StreamConnection = BufferedFd<Fd>;
StreamConnection stdin_;
#endif
static CliClient *instance_;
#ifdef USE_READLINE
/* Callback function called for each line when accept-line executed, EOF
* seen, or EOF character read. This sets a flag and returns; it could
* also call exit. */
static void cb_linehandler(char *line) {
/* Can use ^D (stty eof) to exit. */
if (line == nullptr) {
LOG(FATAL) << "closed";
return;
}
if (*line) {
add_history(line);
}
instance_->add_cmd(line);
rl_free(line);
}
#endif
unique_ptr<TdCallback> make_td_callback() {
class TdCallbackImpl : public TdCallback {
public:
explicit TdCallbackImpl(CliClient *client) : client_(client) {
}
void on_result(uint64 id, tl_object_ptr<td_api::Object> result) override {
client_->on_result(id, std::move(result));
}
void on_error(uint64 id, tl_object_ptr<td_api::error> error) override {
client_->on_error(id, std::move(error));
}
void on_closed() override {
client_->on_closed();
}
private:
CliClient *client_;
};
return make_unique<TdCallbackImpl>(this);
}
void init_td() {
close_flag_ = false;
ready_to_stop_ = false;
td_ = create_actor<ClientActor>("Td-proxy", make_td_callback());
auto bad_parameters = td_api::make_object<td_api::tdlibParameters>();
bad_parameters->database_directory_ = "/..";
bad_parameters->api_id_ = api_id_;
bad_parameters->api_hash_ = api_hash_;
send_request(td_api::make_object<td_api::setTdlibParameters>(std::move(bad_parameters)));
auto parameters = td_api::make_object<td_api::tdlibParameters>();
parameters->use_test_dc_ = use_test_dc_;
parameters->use_message_database_ = true;
parameters->use_secret_chats_ = true;
parameters->api_id_ = api_id_;
parameters->api_hash_ = api_hash_;
parameters->system_language_code_ = "en";
parameters->device_model_ = "Desktop";
parameters->system_version_ = "Unknown";
parameters->application_version_ = "tg_cli";
send_request(td_api::make_object<td_api::setTdlibParameters>(std::move(parameters)));
send_request(td_api::make_object<td_api::checkDatabaseEncryptionKey>());
}
void init() {
instance_ = this;
init_td();
#if TD_WINDOWS
auto stdin_id = Scheduler::instance()->sched_count() - 1;
class StdinReader : public Actor {
public:
explicit StdinReader(ActorShared<CliClient> parent) : parent_(std::move(parent)) {
}
void start_up() override {
stdin_ = &Fd::Stdin();
set_timeout_in(0.001);
}
void timeout_expired() override {
std::array<char, 100> buf;
auto t_res = stdin_->read(MutableSlice(buf.data(), buf.size()));
if (t_res.is_error()) {
LOG(FATAL) << "Can't read from stdin";
}
auto res = t_res.ok();
VLOG(fd) << res << " " << string(buf.data(), res);
data_.append(string(buf.data(), res));
process();
set_timeout_in(0.05);
}
private:
Fd *stdin_ = nullptr;
string data_;
ActorShared<CliClient> parent_;
void process() {
while (true) {
auto pos = data_.find('\n');
if (pos == string::npos) {
break;
}
auto cmd = string(data_.data(), pos);
while (!cmd.empty() && cmd.back() == '\r') {
cmd.pop_back();
}
send_closure(parent_, &CliClient::on_cmd, cmd);
data_ = data_.substr(pos + 1);
}
}
};
stdin_reader_ = create_actor_on_scheduler<StdinReader>("stdin_reader", stdin_id, actor_shared(this, 1));
#else
Fd::Stdin().set_is_blocking(false).ensure();
#ifdef USE_READLINE
deactivate_readline();
rl_callback_handler_install(prompt, cb_linehandler);
rl_attempted_completion_function = tg_cli_completion;
reactivate_readline();
stdin_ = Fd::Stdin().clone();
#else
stdin_ = StreamConnection(Fd::Stdin().clone());
#endif
stdin_.get_fd().set_observer(this);
subscribe(stdin_, Fd::Read);
#endif
if (get_chat_list_) {
send_request(make_tl_object<td_api::getChats>(std::numeric_limits<int64>::max(), 0, 100));
}
if (disable_network_) {
send_request(make_tl_object<td_api::setNetworkType>(make_tl_object<td_api::networkTypeNone>()));
}
}
#ifndef USE_READLINE
size_t buffer_pos_ = 0;
Result<BufferSlice> process_stdin(ChainBufferReader *buffer) {
auto found = find_boundary(buffer->clone(), "\n", buffer_pos_);
if (!found) {
return Status::Error("End of line not found");
}
auto data = buffer->cut_head(buffer_pos_).move_as_buffer_slice();
if (!data.empty() && data[data.size() - 1] == '\r') {
data.truncate(data.size() - 1);
}
buffer->cut_head(1);
buffer_pos_ = 0;
return std::move(data);
}
#endif
static tl_object_ptr<td_api::formattedText> as_caption(string caption,
vector<td_api::object_ptr<td_api::textEntity>> entities = {}) {
if (entities.empty()) {
auto parsed_caption =
execute(make_tl_object<td_api::parseTextEntities>(caption, make_tl_object<td_api::textParseModeMarkdown>()));
if (parsed_caption->get_id() == td_api::formattedText::ID) {
auto text = td_api::move_object_as<td_api::formattedText>(parsed_caption);
caption = std::move(text->text_);
entities = std::move(text->entities_);
}
}
return make_tl_object<td_api::formattedText>(caption, std::move(entities));
}
tl_object_ptr<td_api::NotificationSettingsScope> get_notification_settings_scope(Slice scope) const {
if (scope == "users" || scope == "privateChats") {
return make_tl_object<td_api::notificationSettingsScopePrivateChats>();
} else if (scope == "chats" || scope == "groups" || scope == "groupChats") {
return make_tl_object<td_api::notificationSettingsScopeBasicGroupChats>();
} else if (scope == "all" || scope == "dialogs") {
return make_tl_object<td_api::notificationSettingsScopeAllChats>();
} else {
return make_tl_object<td_api::notificationSettingsScopeChat>(as_chat_id(scope));
}
}
static tl_object_ptr<td_api::UserPrivacySetting> get_user_privacy_setting(MutableSlice setting) {
setting = trim(setting);
to_lower_inplace(setting);
if (setting == "invite") {
return make_tl_object<td_api::userPrivacySettingAllowChatInvites>();
}
if (setting == "status") {
return make_tl_object<td_api::userPrivacySettingShowStatus>();
}
if (setting == "call") {
return make_tl_object<td_api::userPrivacySettingAllowCalls>();
}
return nullptr;
}
static tl_object_ptr<td_api::SearchMessagesFilter> get_search_messages_filter(MutableSlice filter) {
filter = trim(filter);
to_lower_inplace(filter);
if (filter == "an" || filter == "animation") {
return make_tl_object<td_api::searchMessagesFilterAnimation>();
}
if (filter == "au" || filter == "audio") {
return make_tl_object<td_api::searchMessagesFilterAudio>();
}
if (filter == "d" || filter == "document") {
return make_tl_object<td_api::searchMessagesFilterDocument>();
}
if (filter == "p" || filter == "photo") {
return make_tl_object<td_api::searchMessagesFilterPhoto>();
}
if (filter == "vi" || filter == "video") {
return make_tl_object<td_api::searchMessagesFilterVideo>();
}
if (filter == "vo" || filter == "voice") {
return make_tl_object<td_api::searchMessagesFilterVoiceNote>();
}
if (filter == "pvo") {
return make_tl_object<td_api::searchMessagesFilterPhotoAndVideo>();
}
if (filter == "u" || filter == "url") {
return make_tl_object<td_api::searchMessagesFilterUrl>();
}
if (filter == "cp" || filter == "chatphoto") {
return make_tl_object<td_api::searchMessagesFilterChatPhoto>();
}
if (filter == "vc" || filter == "call") {
return make_tl_object<td_api::searchMessagesFilterCall>();
}
if (filter == "mvc" || filter == "missedcall") {
return make_tl_object<td_api::searchMessagesFilterMissedCall>();
}
if (filter == "vn" || filter == "videonote") {
return make_tl_object<td_api::searchMessagesFilterVideoNote>();
}
if (filter == "vvn" || filter == "voicevideonote") {
return make_tl_object<td_api::searchMessagesFilterVoiceAndVideoNote>();
}
if (filter == "m" || filter == "mention") {
return make_tl_object<td_api::searchMessagesFilterMention>();
}
if (filter == "um" || filter == "umention") {
return make_tl_object<td_api::searchMessagesFilterUnreadMention>();
}
if (!filter.empty()) {
LOG(ERROR) << "Unsupported message filter " << filter;
}
return nullptr;
}
tl_object_ptr<td_api::TopChatCategory> get_top_chat_category(MutableSlice category) {
category = trim(category);
to_lower_inplace(category);
if (!category.empty() && category.back() == 's') {
category.remove_suffix(1);
}
if (category == "bot") {
return make_tl_object<td_api::topChatCategoryBots>();
} else if (category == "group") {
return make_tl_object<td_api::topChatCategoryGroups>();
} else if (category == "channel") {
return make_tl_object<td_api::topChatCategoryChannels>();
} else if (category == "inline") {
return make_tl_object<td_api::topChatCategoryInlineBots>();
} else if (category == "call") {
return make_tl_object<td_api::topChatCategoryCalls>();
} else {
return make_tl_object<td_api::topChatCategoryUsers>();
}
}
static tl_object_ptr<td_api::ChatAction> get_chat_action(MutableSlice action) {
action = trim(action);
to_lower_inplace(action);
if (action == "c" || action == "cancel") {
return make_tl_object<td_api::chatActionCancel>();
}
if (action == "rvi" || action == "record_video") {
return make_tl_object<td_api::chatActionRecordingVideo>();
}
if (action == "uvi" || action == "upload_video") {
return make_tl_object<td_api::chatActionUploadingVideo>(50);
}
if (action == "rvo" || action == "record_voice") {
return make_tl_object<td_api::chatActionRecordingVoiceNote>();
}
if (action == "uvo" || action == "upload_voice") {
return make_tl_object<td_api::chatActionUploadingVoiceNote>(50);
}
if (action == "up" || action == "upload_photo") {
return make_tl_object<td_api::chatActionUploadingPhoto>(50);
}
if (action == "ud" || action == "upload_document") {
return make_tl_object<td_api::chatActionUploadingDocument>(50);
}
if (action == "fl" || action == "find_location") {
return make_tl_object<td_api::chatActionChoosingLocation>();
}
if (action == "cc" || action == "choose_contact") {
return make_tl_object<td_api::chatActionChoosingContact>();
}
if (action == "spg" || action == "start_play_game") {
return make_tl_object<td_api::chatActionStartPlayingGame>();
}
if (action == "rvn" || action == "record_video_note") {
return make_tl_object<td_api::chatActionRecordingVideoNote>();
}
if (action == "uvn" || action == "upload_video_note") {
return make_tl_object<td_api::chatActionUploadingVideoNote>(50);
}
return make_tl_object<td_api::chatActionTyping>();
}
static tl_object_ptr<td_api::NetworkType> get_network_type(MutableSlice type) {
type = trim(type);
to_lower_inplace(type);
if (type == "none") {
return make_tl_object<td_api::networkTypeNone>();
}
if (type == "mobile") {
return make_tl_object<td_api::networkTypeMobile>();
}
if (type == "roaming") {
return make_tl_object<td_api::networkTypeMobileRoaming>();
}
if (type == "wifi") {
return make_tl_object<td_api::networkTypeWiFi>();
}
if (type == "other") {
return make_tl_object<td_api::networkTypeOther>();
}
return nullptr;
}
static td_api::object_ptr<td_api::Object> execute(tl_object_ptr<td_api::Function> f) {
LOG(INFO) << "Execute request " << to_string(f);
auto res = ClientActor::execute(std::move(f));
LOG(INFO) << "Execute response" << to_string(res);
return res;
}
uint64 send_request(tl_object_ptr<td_api::Function> f) {
static uint64 query_num = 1;
if (!td_.empty()) {
auto id = query_num++;
send_closure_later(td_, &ClientActor::request, id, std::move(f));
return id;
} else {
LOG(ERROR) << "Failed to send: " << to_string(f);
return 0;
}
}
void send_message(const string &chat_id, tl_object_ptr<td_api::InputMessageContent> &&input_message_content,
bool disable_notification = false, bool from_background = false, int64 reply_to_message_id = 0) {
auto chat = as_chat_id(chat_id);
auto id = send_request(make_tl_object<td_api::sendMessage>(
chat, reply_to_message_id, disable_notification, from_background, nullptr, std::move(input_message_content)));
query_id_to_send_message_info_[id].start_time = Time::now();
}
void on_cmd(string cmd) {
// TODO: need to remove https://en.wikipedia.org/wiki/ANSI_escape_code from cmd
cmd.erase(remove_if(cmd.begin(), cmd.end(), [](char c) { return 0 <= c && c < 32; }), cmd.end());
LOG(INFO) << "CMD:[" << cmd << "]";
string op;
string args;
std::tie(op, args) = split(cmd);
const int32 OP_BLOCK_COUNT = 5;
int32 op_not_found_count = 0;
if (op == "gas") {
send_request(make_tl_object<td_api::getAuthorizationState>());
} else if (op == "sap") {
send_request(make_tl_object<td_api::setAuthenticationPhoneNumber>(args, false, false));
} else if (op == "rac") {
send_request(make_tl_object<td_api::resendAuthenticationCode>());
} else if (op == "cdek" || op == "CheckDatabaseEncryptionKey") {
send_request(make_tl_object<td_api::checkDatabaseEncryptionKey>(args));
} else if (op == "sdek" || op == "SetDatabaseEncryptionKey") {
send_request(make_tl_object<td_api::setDatabaseEncryptionKey>(args));
} else if (op == "cac") {
string code;
string first_name;
string last_name;
std::tie(code, args) = split(args);
std::tie(first_name, last_name) = split(args);
send_request(make_tl_object<td_api::checkAuthenticationCode>(code, first_name, last_name));
} else if (op == "cap") {
send_request(make_tl_object<td_api::checkAuthenticationPassword>(args));
} else if (op == "cab") {
send_request(make_tl_object<td_api::checkAuthenticationBotToken>(args));
} else if (op == "rapr") {
send_request(make_tl_object<td_api::requestAuthenticationPasswordRecovery>());
} else if (op == "rap") {
send_request(make_tl_object<td_api::recoverAuthenticationPassword>(args));
} else if (op == "lo" || op == "LogOut" || op == "logout") {
send_request(make_tl_object<td_api::logOut>());
} else if (op == "ra" || op == "destroy") {
send_request(make_tl_object<td_api::destroy>());
} else if (op == "reset") {
init_td();
} else if (op == "close_td") {
send_request(make_tl_object<td_api::close>());
} else if (op == "DeleteAccountYesIReallyWantToDeleteMyAccount") {
send_request(make_tl_object<td_api::deleteAccount>(args));