forked from cppvik/teleperl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClifTg.pm
1422 lines (1168 loc) · 38.8 KB
/
ClifTg.pm
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
use Modern::Perl;
use utf8;
package CliTg;
use base "CLI::Framework";
use Carp;
use Encode ':all';
use AnyEvent::Impl::Perl;
use AnyEvent;
use AnyEvent::Log;
use Teleperl;
use Teleperl::Storage;
use Teleperl::Util qw(:DEFAULT get_AE_log_format_cb);
use Data::Dumper;
sub settable_opts {
[ 'verbose|v!' => 'be verbose, by default also influences logger' ],
[ 'debug|d:+' => 'pass debug (2=trace) to Telegram->new & AE::log' ],
[ 'session=s' => 'name of session data save dir', { default => '.'} ],
}
sub option_spec {
&settable_opts(),
[ 'encoding=s' => 'if your console is not in UTF-8' ],
[ 'noupdate!' => 'pass noupdate to Telegram->new' ],
[ 'config|c=s' => 'name of configuration file', { default => "teleperl.conf" } ],
[ 'offline!' => 'dont update account status', { default => 0 } ],
}
sub init {
my ($app, $opts) = @_;
$app->set_current_command('help') if $opts->{help};
$app->cache->set( 'verbose' => $opts->{verbose} );
$app->cache->set( 'debug' => $opts->{debug} );
# XXX do validate
$app->cache->set('encoding' => Encode::find_encoding($opts->{encoding}))
if $opts->{encoding};
$Data::Dumper::Indent = 1;
$AnyEvent::Log::FILTER->level(
$opts->{debug} ? ($opts->{debug}>1 ? "trace" : "debug") :
$opts->{verbose} ? "info" : "note");
$AnyEvent::Log::LOG->fmt_cb( get_AE_log_format_cb() );
install_AE_log_SIG_WARN();
install_AE_log_crutch();
my $stor = Teleperl::Storage->new( dir => $opts->{session} );
$app->cache->set( 'storage' => $stor );
my $tg = Teleperl->new( storage => $stor, online => !$opts->{offline}, autofetch => 1 );
$tg->reg_cb( update => sub { shift; $app->report_update(@_) } );
$tg->reg_cb( fetch => sub {
shift;
my %res = @_;
if ( defined $res{error} ) {
$app->render( "file fetch failed with error: $res{error}\n" );
}
else {
$app->render( "file $res{name}, size $res{size} fetched\n");
}
}
);
$tg->reg_cb( error => sub { AE::log error => "@_"; } );
$tg->start;
#$tg->update;
$app->cache->set( 'tg' => $tg );
$app->cache->set( 'argobject' => [] );
$app->set_prompt('T> ');
$app->ornaments('md,me,,');
$app->event_loop(40);
$app->with_readline_vars(sub {
my %params = @_;
$params{Attribs}->{basic_word_break_characters} =~ s/@//g;
$params{Attribs}->{completer_word_break_characters} =~ s/@//g;
});
}
sub command_map
{
argobject => 'CliTg::Command::Argobject',
auth => 'CliTg::Command::Auth',
chats => 'CliTg::Command::Chats',
describe => 'CliTg::Command::Describe',
dialogs => 'CliTg::Command::Dialogs',
history => 'CliTg::Command::History',
invoke => 'CliTg::Command::Invoke',
media => 'CliTg::Command::Media',
message => 'CliTg::Command::Message',
'read' => 'CliTg::Command::Read',
sessions => 'CliTg::Command::Sessions',
set => 'CliTg::Command::Set',
updates => 'CliTg::Command::Updates',
users => 'CliTg::Command::Users',
config => 'CliTg::Command::Config',
auth => 'CliTg::Command::Auth',
# built-in commands:
help => 'CLI::Framework::Command::Help',
menu => 'CliTg::Menu',
list => 'CLI::Framework::Command::List',
tree => 'CLI::Framework::Command::Tree',
'dump' => 'CLI::Framework::Command::Dump',
console => 'CLI::Framework::Command::Console',
alias => 'CLI::Framework::Command::Alias',
}
sub command_alias
{
m => 'message',
msg => 'message',
new => 'argobject',
obj => 'argobject',
}
sub _format_time {
my $ts = shift;
# TODO take from app options/config
return POSIX::strftime(
(AE::now - $ts < 86400) ? "%H:%M:%S" : "%Y.%m.%d %H:%M",
localtime $ts);
}
sub render {
my ($app, $output) = @_;
if (my $enc = $app->cache->get('encoding')) {
# FIXME correctness checks & flags
if (utf8::valid($output)) {
utf8::decode($output);
utf8::upgrade($output);
}
$output = $enc->encode($output, Encode::FB_PERLQQ);
}
$app->SUPER::render($output);
}
# XXX Template::Toolkit / Term::ANSIColor ?
sub render_msg {
my $self = shift;
#@type Telegram::Message
my $msg = shift;
my $tg = $self->cache->get('tg');
my $v = $self->cache->get('verbose');
my $name = defined $msg->{from_id} ? $tg->peer_name($msg->{from_id}, 1) : '(noid)';
my $to = $msg->{to_id};
my $ip = defined $msg->{from_id} ? $tg->peer_from_id($msg->{from_id}) : undef;
if ($to) {
if ($to->isa('Telegram::PeerChannel')) {
$to = $to->{channel_id};
}
if ($to->isa('Telegram::PeerChat')) {
$to = $to->{chat_id};
}
$ip = $tg->peer_from_id($to);
$to = $tg->peer_name($to);
}
$to = $to ? " in $to" : '';
# like telegram-cli/interface.c TODO more fields & maybe colors
my $add = "";
if ($msg->{fwd_from}) {
$add .= "[fwd from ";
my $fwh = $msg->{fwd_from};
if ($fwh->isa('Telegram::MessageFwdHeader')) {
$add .= $tg->peer_name($fwh->{from_id}, 1) if $fwh->{from_id};
$add .= " in " . $tg->peer_name($fwh->{channel_id}, 1) if $fwh->{channel_id};
if ($v) {
$add .= " @ " . _format_time($fwh->{date});
for (qw(channel_post post_author saved_from_msg_id)) {
$add .= "$_=" . $fwh->{$_} if $fwh->{$_};
}
# TODO saved_from_peer
}
}
$add .= "] ";
}
$add .= "[reply to " . $msg->{reply_to_msg_id} . "] " if $msg->{reply_to_msg_id};
$add .= "[mention] " if $msg->{mentioned};
$add .= "[via " . $tg->peer_name($msg->{via_bot_id}, 1) . "] " if $msg->{via_bot_id};
$add .= "[edited " . _format_time($msg->{edit_date}) . "] " if $msg->{edit_date};
$add .= "[media] " if $msg->{media};
$add .= "[reply_markup] " if $msg->{reply_markup};
my @t = localtime;
$self->render("\r[rcvd " . join(":", map {"0"x(2-length).$_} reverse @t[0..2]) . "] "
. ($v ? "id=$msg->{id} ":"")
. _format_time($msg->{date}) . " "
. "$name$to: $add$msg->{message}\n"
);
}
use Telegram::Messages::ForwardMessages;
use Telegram::InputPeer;
sub report_update
{
my ($self, $upd) = @_;
my $tg = $self->cache->get('tg');
if ($upd->isa('MTProto::RpcError')) {
$self->render("\rRpcError $upd->{error_code}: $upd->{error_message}");
}
if ($upd->isa('Telegram::Message')) {
$self->render_msg($upd);
#$tg->invoke(Telegram::Messages::ForwardMessages->new(
# id => [ $upd->{id} ],
# from_peer => $ip,
# to_peer => Telegram::InputPeerSelf->new,
# random_id => [ int(rand(65536)) ]
#)) if defined $ip;
#say Dumper $upd;
}
if ($upd->isa('Telegram::UpdateChatUserTyping')) {
my $user = $tg->peer_name($upd->{user_id});
my $chat = $tg->peer_name($upd->{chat_id});
if (defined $user and defined $chat) {
$self->render("\n$user is typing in $chat...");
}
}
}
package CliTg::Menu;
use base "CLI::Framework::Command::Menu";
sub menu_txt {
my ($self, $suppress) = @_;
return "" if $suppress;
return $self->SUPER::menu_txt();
}
package CliTg::Command::Message;
use base "CLI::Framework::Command";
use Telegram::MessageEntity;
use Encode qw/encode_utf8 decode_utf8/;
use Data::Dumper;
# do long scan once
my $entpkgs = Class::Inspector->subclasses('Telegram::MessageEntityABC');
my @_opts;
for (grep(!/input/i, @$entpkgs)) {
my $e = $_;
no strict 'refs';
my @keys = sort keys %{"$e\::FIELDS"};
$e =~ s/Telegram::MessageEntity//;
$e = lc $e;
push @_opts, [ "entity-$e=s\@{".(scalar @keys).'}' => "required args @keys" ],
}
# XXX allow repeated like '=s@{3}' here
sub getopt_conf { qw(no_bundling) }
sub option_spec {
[ "no_webpage!" => "same named API param, default false" ],
[ "silent!" => "same named API param, default false" ],
[ "background!" => "same named API param, default false" ],
[ "clear_draft!" => "same named API param, default false" ],
[ "reply_to_msg_id=i"=> "same named API param, default none" ],
@_opts,
}
sub complete_arg
{
my ($self, $lastopt, $argnum, $text, $attribs) = @_;
my $tg = $self->cache->get('tg');
if ($argnum == 1) {
return ($tg->cached_nicknames(), $tg->cached_usernames());
}
return undef;
}
sub validate
{
my ($self, $opts, @args) = @_;
die "user/chat must be specified" unless defined $args[0];
die "message text required" unless defined $args[1];
}
sub run
{
my ($self, $opts, $idpeer, @msg) = @_;
my $tg = $self->cache->get('tg');
my $peer = $tg->name_to_id($idpeer);
return "unknown user/chat" unless defined $peer;
my @ents;
for my $entkey (grep /^entit/, keys %$opts) {
my @vals = @{ $opts->{$entkey} };
$entkey =~ s/^entity.//;
my $class = (grep { lc $_ eq lc "Telegram::MessageEntity$entkey" } @$entpkgs )[0];
no strict 'refs';
my @keys = sort keys %{"$class\::FIELDS"};
die "invalid arg count" if scalar(@vals) % scalar(@keys) != 0;
while (my @ent = splice @vals, 0, scalar(@keys)) {
push @ents, $class->new(
map {
(shift @keys) => (shift @ent)
} (0 .. $#keys)
);
}
}
$tg->send_text_message(
to => $peer,
message => join(' ', @msg),
(map {
(defined $opts->{$_} ? ($_ => $opts->{$_}) : ())
} qw(no_webpage silent background clear_draft reply_to_msg_id)),
(@ents ? (entities => [@ents]) : ()),
);
}
package CliTg::Command::Set;
use base "CLI::Framework::Command::Meta";
*option_spec = \&CliTg::settable_opts;
sub run
{
my ($self, $opts, $val) = @_;
my $ret = "";
my $app = $self->get_app;
my $tg = $self->cache->get('tg');
if (exists $opts->{debug}) {
$tg->{debug} = $opts->debug;
$app->cache->set( 'debug' => $opts->{debug} );
$ret .= "debug is set to $opts->{debug}\n";
}
if (exists $opts->{verbose}) {
$app->cache->set( 'verbose' => $opts->{verbose} );
$ret .= "verbose is set to $opts->{verbose}\n";
}
if ($opts->{session} ne $app->cache->get('session')) {
$app->cache->set( 'session' => $opts->{session} );
$ret .= "session is set to $opts->{session}\n";
}
return $ret || "no opts changed";
}
package CliTg::Command::Dialogs;
use base "CLI::Framework::Command::Meta";
use Data::Dumper;
use Telegram::Messages::GetDialogs;
use Telegram::InputPeer;
sub handle_dialogs
{
my ($tg, $count, $say, $ds) = @_;
my $out = sub {
if ($count) {
$say->(sprintf "%4d %-4s %-10d %6d %-23s %s", $count, @_);
} else {
$say->(sprintf "\ndlg# Type Id Unread \@username Display Name");
}
};
if ($ds->isa('Telegram::Messages::DialogsABC')) {
my %users;
my %chats;
my $ipeer;
$tg->_cache_users(@{$ds->{users}});
$tg->_cache_chats(@{$ds->{chats}});
for my $u (@{$ds->{users}}) {
$users{$u->{id}} = $u;
}
for my $c (@{$ds->{chats}}) {
$chats{$c->{id}} = $c;
}
$out->() if $count == 0 && scalar @{$ds->{dialogs}};
for my $d (@{$ds->{dialogs}}) {
$count++;
my $peer = $d->{peer};
if ($peer->isa('Telegram::PeerUser')) {
my $user_id = $peer->{user_id};
$peer = $users{$user_id};
$out->(
$peer->{bot} ? "bot" : "user",
$user_id,
$d->{unread_count},
$peer->{username} // "",
($peer->{first_name}//"")." ".($peer->{last_name} // "")
);
$ipeer = Telegram::InputPeerUser->new(
user_id => $user_id,
access_hash => $peer->{access_hash}
);
}
if ($peer->isa('Telegram::PeerChannel')) {
my $chan_id = $peer->{channel_id};
$peer = $chats{$chan_id};
$ipeer = Telegram::InputPeerChannel->new(
channel_id => $chan_id,
access_hash => $peer->{access_hash}
);
$out->(
($peer->{megagroup} ? 'sgrp' : '#') .
(ref $peer =~ /Forbidden/ ? 'ban' : ''),
$chan_id,
$d->{unread_count},
($peer->{username} // "#chan with no name o_O"),
$peer->{title} // "",
);
}
if ($peer->isa('Telegram::PeerChat')){
my $chat_id = $peer->{chat_id};
$peer = $chats{$chat_id};
$ipeer = Telegram::InputPeerChat->new(
chat_id => $chat_id,
);
$out->(
ref $peer =~ /Forbidden/
? 'frbd'
: 'chat',
$chat_id, $d->{unread_count}, "", $peer->{title} // ""
);
}
}
if ($ds->isa('Telegram::Messages::DialogsSlice')) {
$tg->invoke(
Telegram::Messages::GetDialogs->new(
offset_id => $ds->{messages}[-1]{id},
offset_date => $ds->{messages}[-1]{date},
offset_peer => Telegram::InputPeerEmpty->new,
# offset_peer => $ipeer,
limit => -1,
hash => 0
),
sub { handle_dialogs($tg, $count, $say, @_) }
) if ($count < $ds->{count});
}
}
}
sub run
{
my ($self, $opts, $offset, $limit) = @_;
my $tg = $self->cache->get('tg');
$tg->invoke(
Telegram::Messages::GetDialogs->new(
offset_id => $offset // 0,
offset_date => 0,
offset_peer => Telegram::InputPeerEmpty->new,
limit => $limit // -1,
hash => 0
),
sub {
handle_dialogs(
$tg,
0,
sub { $self->get_app->render(join($,//"", @_) . "\n") },
@_)
}
);
}
package CliTg::Command::Media;
use base "CLI::Framework::Command";
use Telegram::Messages::SendMedia;
use Telegram::InputMedia;
sub run
{
my ($self, $opts, $peer, $msg) = @_;
my $tg = $self->cache->get('tg');
$tg->invoke(
Telegram::Messages::SendMedia->new(
peer => $tg->peer($peer),
media => Telegram::InputMediaDocumentExternal->new(
url => $msg,
caption => $msg
),
random_id => int(rand(65536))
)
);
}
package CliTg::Command::Users;
use base "CLI::Framework::Command";
use Data::Dumper;
sub run
{
my ($self, $opts, $peer, $msg) = @_;
my $tg = $self->cache->get('tg');
return Dumper $tg->{session}{users};
}
package CliTg::Command::Chats;
use base "CLI::Framework::Command";
use Data::Dumper;
sub run
{
my ($self, $opts, $peer, $msg) = @_;
my $tg = $self->cache->get('tg');
return Dumper $tg->{session}{chats};
}
package CliTg::Command::Updates;
use base "CLI::Framework::Command::Meta";
use Telegram::Updates::GetState;
use Data::Dumper;
sub run
{
my ($self, $opts, $peer, $msg) = @_;
my $tg = $self->cache->get('tg');
$tg->invoke( Telegram::Updates::GetState->new, sub {
$self->get_app->render(Dumper @_);
$tg->{session}{update_state}{date} = $_[0]->{date};
$tg->{session}{update_state}{pts} = $_[0]->{pts};
$tg->{session}{update_state}{seq} = $_[0]->{seq};
});
#$tg->invoke( Telegram::Updates::GetDifference->new(
# date => $tg->{session}{update_state}{date},
# pts => $tg->{session}{update_state}{pts},
# qts => -1,
# ), sub {say Dumper @_});
}
package CliTg::Command::History;
use base "CLI::Framework::Command::Meta";
use Telegram::InputPeer;
use Telegram::Messages::GetHistory;
use Data::Dumper;
sub option_spec {
[ "offset_id=i" => "same named API param, default 0" ],
[ "offset_date=i" => "same named API param, default 0" ],
[ "add_offset=i" => "same named API param, default 0" ],
[ "limit=i" => "same named API param, default 10" ],
[ "max_id=i" => "same named API param, default 0" ],
[ "min_id=i" => "same named API param, default 0" ],
}
sub complete_arg
{
my ($self, $lastopt, $argnum, $text, $attribs) = @_;
my $tg = $self->cache->get('tg');
if ($argnum == 1 && $text !~ /^-/) {
return ($tg->cached_nicknames());
}
return undef;
}
sub validate
{
my ($self, $opts, @args) = @_;
die "user/chat must be specified" unless defined $args[0];
}
sub handle_history
{
my ($self, $peer, $messages, $ptop, $opts) = @_;
my $tg = $self->cache->get('tg');
AE::log debug => "handle_history ".Dumper( $peer, $ptop, $opts );
my $top = 0;
$tg->_cache_users(@{$messages->{users}}) ;
for my $upd (@{$messages->{messages}}) {
$top = $upd->{id};
AE::log debug => "history: $upd->{id}";
$opts->{limit}-- if $opts->{limit};
if ($upd->isa('Telegram::Message')) {
$self->get_app->render_msg($upd);
}
}
return unless $top; # if bottom reached, slice will be empty
if ($ptop == 0 or $top < $ptop && ($opts->{limit} // "true")) {
$tg->invoke( Telegram::Messages::GetHistory->new(
peer => $peer,
offset_id => $top,
offset_date => $opts->{offset_date} // 0,
add_offset => $opts->{add_offset} // 0,
limit => $opts->{limit} // 10,
max_id => $opts->{max_id} // 0,
min_id => $opts->{min_id} // 0,
hash => 0
), sub {
$self->handle_history($peer, $_[0], $ptop ? $top : 0, $opts) if $_[0]->isa('Telegram::Messages::MessagesABC');
} );
}
}
sub run
{
my ($self, $opts, $peer, @msg) = @_;
my $tg = $self->cache->get('tg');
if ($peer eq 'self') {
$peer = Telegram::InputPeerSelf->new;
}
else {
$peer = $tg->name_to_id($peer);
$peer = $tg->peer_from_id($peer);
}
return "unknown user/chat" unless defined $peer;
$tg->invoke( Telegram::Messages::GetHistory->new(
peer => $peer,
offset_id => $opts->{offset_id} // 0,
offset_date => $opts->{offset_date} // 0,
add_offset => $opts->{add_offset} // 0,
limit => $opts->{limit} // 10,
max_id => $opts->{max_id} // 0,
min_id => $opts->{min_id} // 0,
hash => 0
), sub {
$self->handle_history($peer, $_[0], 0, $opts) if $_[0]->isa('Telegram::Messages::MessagesABC');
} );
}
package CliTg::Command::Read;
use base "CLI::Framework::Command::Meta";
use Telegram::Messages::ReadHistory;
use Telegram::Channels::ReadHistory;
use Data::Dumper;
sub usage_text {
q{
read <peer> [<max_id>]: Mark dialog with <peer> as read, all
messages by default, or up to <max_id> in history
}
}
sub complete_arg
{
my ($self, $lastopt, $argnum, $text, $attribs) = @_;
my $tg = $self->cache->get('tg');
if ($argnum == 1) {
return ($tg->cached_nicknames(), $tg->cached_usernames);
}
return undef;
}
sub validate
{
my ($self, $opts, @args) = @_;
die "user/chat must be specified" unless defined $args[0];
}
sub run
{
my ($self, $opts, $peer, $max) = @_;
my $tg = $self->cache->get('tg');
$peer = $tg->name_to_id($peer);
$peer = $tg->peer_from_id($peer);
return "unknown user/chat" unless defined $peer;
if ($peer->isa('Telegram::InputPeerChannel')) {
$tg->invoke( Telegram::Channels::ReadHistory->new(
channel => $peer,
max_id => $max // 0,
), sub { $self->get_app->render(Dumper @_) } );
}
else {
$tg->invoke( Telegram::Messages::ReadHistory->new(
peer => $peer,
max_id => $max // 0,
), sub { $self->get_app->render(Dumper @_) } );
}
}
package CliTg::Command::Sessions;
use base "CLI::Framework::Command::Meta";
use Telegram::Account::GetAuthorizations;
use Data::Dumper;
sub run
{
my $self = shift;
my $tg = $self->cache->get('tg');
$tg->invoke( Telegram::Account::GetAuthorizations->new, sub { $self->get_app->render(Dumper @_) } );
}
package CliTg::Command::Invoke;
use base "CLI::Framework::Command::Meta";
use Telegram::ObjTable;
use Data::Dumper;
our @cnames = map { $_->{class} } values %Telegram::ObjTable::tl_type;
our @fnames = map { $_->{func} } grep { exists $_->{func} and not exists $_->{bang} } values %Telegram::ObjTable::tl_type;
our $class = undef;
sub _func2class {
for (values %Telegram::ObjTable::tl_type) {
return $_->{class} if exists $_->{func} and $_->{func} eq $_[0];
}
return undef;
}
sub _class2file {
my $cname = shift;
my @clst = grep { $_->{class} eq $cname } values %Telegram::ObjTable::tl_type;
die "must have exactly one record for '$cname' in ObjTable"
if @clst == 0 or @clst > 1;
return $clst[0]->{file};
}
sub usage_text {
q{
invoke --class <name> [<options>]: do raw InvokeWithLayer with this query
invoke --func <fname> [<options>]: and then Data::Dumper response
ARGUMENTS
<name> name of Telegram::* class to call ->new() upon
<fname> function from schema/docs - will guess --class
$<number> substitute instantiated slot from 'argobject' command
OPTIONS
Long form, corresponding to field name, e.g. '--date' if class
has field 'date' - these will be arguments to new().
*BUG*! You may need to erase and try opt again for autocomplete to work,
and option may be non-recognized until completion tried.
}
}
sub option_spec {
my @opts = ([ "class=s", "which to instantiate" ],
[ "func=s", "schema function/method to get class from" ]);
if ($class) {
require Class::Inspector->filename($class);
no strict 'refs';
push @opts, [ "$_=s", "" ] for keys %{"$class\::FIELDS"};
}
return @opts;
}
sub complete_arg
{
my ($self, $lastopt, $argnum, $text, $attribs, $rawARGV) = @_;
#print "|$text,$lastopt,$argnum#".join(':',@args)."%".join('^',@$rawARGV)."|\n";
# the trick is: we must change $class on the fly so option_spec()
# will return class fields as options and they will be completed
# by CLIF - not us! - on *next* iteration.
if ($argnum == 1) {
if ($lastopt =~ /^--class$/) {
$class = $text if scalar grep { $_ eq $text } @cnames;
return @cnames;
} elsif ($lastopt =~ /^--func$/) {
$class = _func2class($text) if scalar grep { $_ eq $text } @fnames;
return @fnames;
}
}
my @args = @$rawARGV;
if (@args > 1) {
for my $i (0..$#args-1) {
if ($args[$i] eq '--class' and scalar grep { $_ eq $args[$i+1] } @cnames) {
$class = $args[$i+1];
last;
}
if ($args[$i] eq '--func' and scalar grep { $_ eq $args[$i+1] } @fnames) {
$class = _func2class($args[$i+1]);
last;
}
}
}
if ($text =~ /^\$/) {
my $arr = $self->cache->get('argobject');
my @slots;
for (my $i = 0; $i < $#$arr; $i++) {
push @slots, '$'.$i if defined $arr->[$i];
}
return @slots;
}
return undef;
}
sub validate
{
my ($self, $opts, @args) = @_;
die "Telegram::* subclass or schema.funcMethodName must be specified"
unless defined $opts->{class} or defined $opts->{func};
my $arr = $self->cache->get('argobject');
for (@args) {
if (/^\$[0-9]+$/) {
die "slot $_ is unset" if not defined $arr->[substr $_, 1];
}
}
}
sub run
{
my ($self, $opts) = @_;
my $tg = $self->cache->get('tg');
my $argo = $self->cache->get('argobject');
my $obj = $class->new(
map {
my $v = $opts->{$_};
$v = $argo->[substr $v, 1] if $v =~ /^\$[0-9]+$/;
($_ => $v);
} grep {
$_ ne 'class' &&
$_ ne 'func' &&
$_ ne 'flags' # XXX what if in future scheme it will be renamed?
} keys %$opts
);
$class = undef;
my $retid;
$retid = $tg->invoke($obj, sub {
local $Data::Dumper::Varname = $retid . "#";
$self->get_app->render(Dumper @_)
}
);
return "Invoked request # $retid";
}
package CliTg::Command::Argobject;
use base "CLI::Framework::Command::Meta";
sub usage_text {
q{
argobject [<opt>] push --class <name> [<options>]
argobject [<opt>] push [<list of builtin bare types>]
argobject [<opt>] dump
argobject [<opt>] delete <indexes>
argobject [<opt>] pop
argobject [<opt>] shift
argobject [<opt>] inputpeer <self|empty|@username|@chatname|numericalid>
argobject [<opt>] inputuser <self|empty|@username|numericalid>
OPTIONS
--on-slot=N do operation on sub-array in slot N instead of global
ARGUMENTS (subcommands)
push add new slot w/class or bare types to end of (sub)array
dump print current (sub)array with Data::Dumper style 3
delete arguments are indexes of elements to delete
pop delete last element and dump it to screen
shift delete first element, dump it to screen and shift others
inputPeer as 'push' but for InputPeer only with proper completion
inputUser as 'push' but for InputUser only with proper completion
ARGUMENTS in subcommands
<cname> name of Telegram::* class to call ->new() upon
<indexes> numbers - indexes of slots in (sub)array
SUBCOMMAND OPTIONS
Long form, corresponding to field name, e.g. '--date' if class
has field 'date' - these will be arguments to new().
*BUG*! You may need to erase and try opt again for autocomplete to work,
and option may be non-recognized until completion tried.
}
}
sub option_spec {
[ "on-slot=i" => "operate on slot N instead of whole array" ],
}
sub subcommand_alias {
'append' => 'push',
'add' => 'push',
'unset' => 'delete',
}
sub notify_of_subcommand_dispatch {
my ($self, $subcommand, $cmd_opts, @args) = @_;
my $argobj = $self->cache->get('argobject');
if (my $i = $cmd_opts->{"on_slot"}) {
die "Invalid slot $i" unless $i < $#$argobj+2; # XXX really need this?
$argobj->[$i] = [] unless ref $argobj->[$i] eq 'ARRAY';
$argobj = $argobj->[$i];
}
$self->cache->set('_argobjarr' => $argobj);
}
package CliTg::Command::Argobject::Push;
use base "CliTg::Command::Argobject";
use Telegram::ObjTable;
use Data::Dumper;
# reuse some code
*cnames = \@CliTg::Command::Invoke::cnames;
our $class = undef;
*_class2file = \&CliTg::Command::Invoke::_class2file;
sub option_spec {
my @opts = ([ "class=s", "which to instantiate" ]);
if ($class) {
require(_class2file($class));
no strict 'refs';
push @opts, [ "$_=s", "" ] for keys %{"$class\::FIELDS"};
}
return @opts;
}
sub complete_arg
{
my ($self, $lastopt, $argnum, $text, $attribs, $rawARGV) = @_;
#print "|$text,$lastopt,$argnum#".join(':',@args)."%".join('^',@$rawARGV)."|\n";
# the trick is: we must change $class on the fly so option_spec()
# will return class fields as options and they will be completed
# by CLIF - not us! - on *next* iteration.
if ($argnum == 1) {
if ($lastopt =~ /^--class$/) {
$class = $text if scalar grep { $_ eq $text } @cnames;
return @cnames;
}
}
my @args = @$rawARGV;
if (@args > 1) {
for my $i (0..$#args-1) {
if ($args[$i] eq '--class' and scalar grep { $_ eq $args[$i+1] } @cnames) {
$class = $args[$i+1];
last;
}
}
}
if ($text =~ /^\$/) {
my $arr = $self->cache->get('argobject'); # XXX or _argobjarr ?
my @slots;
for (my $i = 0; $i < $#$arr; $i++) {
push @slots, '$'.$i if defined $arr->[$i];
}
return @slots;
}
return undef;
}
sub validate
{