-
Notifications
You must be signed in to change notification settings - Fork 84
/
Irc.pm
1321 lines (1096 loc) · 42.7 KB
/
Irc.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
package Convos::Core::Connection::Irc;
use Mojo::Base 'Convos::Core::Connection';
no warnings qw(utf8);
use feature qw(current_sub);
use Convos::Util qw($CHANNEL_RE);
use IRC::Utils ();
use Mojo::JSON qw(false true);
use Mojo::Parameters;
use Mojo::Util qw(b64_encode term_escape trim);
use Parse::IRC ();
use Socket;
use Time::HiRes qw(time);
use constant IS_TESTING => $ENV{HARNESS_ACTIVE} || 0;
use constant PERIDOC_INTERVAL => $ENV{CONVOS_IRC_PERIDOC_INTERVAL} || 60;
require Convos;
our $VERSION = Convos->VERSION;
our $CONVOS_URL = 'https://convos.chat';
our %CTCP_QUOTE = ("\012" => 'n', "\015" => 'r', "\0" => '0', "\cP" => "\cP");
my %CLASS_DATA;
sub _available_conversations { $CLASS_DATA{conversations}{$_[0]->url->host} ||= {} }
sub disconnect_p {
my $self = shift;
return Mojo::Promise->resolve if $self->state =~ m!^disconnect!;
$self->info->{authenticated} = false;
$self->info->{capabilities} = {};
$self->state(disconnecting => 'Quitting...');
return $self->_write_p("QUIT :$CONVOS_URL")->then(sub { $self->_stream_remove_p });
}
sub send_p {
my ($self, $target, $message) = @_;
$target //= '';
$message //= '';
$message =~ s![\x00-\x09\x0b-\x1f]!!g; # remove invalid characters
$message =~ s!^\s*/!/!s; # Remove space in front of command
$message =~ s![\r\n]+$!!s;
unless ($message =~ s!^/([A-Za-z]+)\s*!!) {
my $re = join '|', map {quotemeta} @{$self->profile->service_accounts};
$target = $1 if $message =~ s!^($re):\s+!!;
return $self->_send_message_p($target, $message);
}
my $cmd = uc $1;
return $self->_send_message_p($target, "\x{1}ACTION $message\x{1}") if $cmd eq 'ME';
return $self->_send_message_p($target, $message) if $cmd eq 'SAY';
return $self->_send_message_p(split /\s+/, $message, 2) if $cmd eq 'MSG';
return $self->_send_clear_p(split /\s+/, $message) if $cmd eq 'CLEAR';
return $self->_send_query_p($message) if $cmd eq 'QUERY';
return $self->_send_join_p($message) if $cmd eq 'JOIN';
return $self->_send_list_p($message) if $cmd eq 'LIST';
return $self->_send_nick_p($message) if $cmd eq 'NICK';
return $self->_send_whois_p($message) if $cmd eq 'WHOIS';
return $self->_send_away_p($message) if $cmd eq 'AWAY';
return $self->_send_names_p($target) if $cmd eq 'NAMES';
return $self->_send_invite_p($target, $message) if $cmd eq 'INVITE';
return $self->_send_kick_p($target, $message) if $cmd eq 'KICK';
return $self->_send_mode_p($target, $message) if $cmd eq 'MODE';
return $self->_send_oper_p($target, $message) if $cmd eq 'OPER';
return $self->_send_topic_p($target, $message) if $cmd eq 'TOPIC';
return $self->_send_ison_p($message || $target) if $cmd eq 'ISON';
return $self->_send_part_p($message || $target) if $cmd eq 'CLOSE' or $cmd eq 'PART';
return $self->_set_wanted_state_p('connected') if $cmd eq 'CONNECT';
return $self->_set_wanted_state_p('disconnected') if $cmd eq 'DISCONNECT';
return $self->_write_p($message) if $cmd eq 'QUOTE';
return $self->reconnect_p if $cmd eq 'RECONNECT';
return Mojo::Promise->reject('Unknown command.');
}
sub _connect_args_p {
my $self = shift;
my $url = $self->url;
my $params = $self->url->query;
$self->_periodic_events;
$url->port($params->param('tls') ? 6669 : 6667) unless $url->port;
$params->param(nick => $self->nick) unless $params->param('nick');
$self->info->{authenticated} = false;
$self->info->{capabilities} = {};
$self->info->{nick} = $params->param('nick');
delete $self->info->{real_host};
return $self->SUPER::_connect_args_p;
}
sub _irc_event_900 { goto &_irc_event_sasl_status } # RPL_LOGGEDIN
sub _irc_event_901 { goto &_irc_event_sasl_status } # RPL_LOGGEDOUT
sub _irc_event_902 { goto &_irc_event_sasl_status } # ERR_NICKLOCKED
sub _irc_event_903 { goto &_irc_event_sasl_status } # RPL_SASLSUCCESS
sub _irc_event_904 { goto &_irc_event_sasl_status } # ERR_SASLFAIL
sub _irc_event_905 { goto &_irc_event_sasl_status } # ERR_SASLTOOLONG
sub _irc_event_906 { goto &_irc_event_sasl_status } # ERR_SASLABORTED
sub _irc_event_907 { goto &_irc_event_sasl_status } # ERR_SASLALREADY
sub _irc_event_908 { goto &_irc_event_cap } # RPL_SASLMECHS
sub _irc_event_rpl_creationtime { }
sub _irc_event_rpl_endofmotd { }
sub _irc_event_sasl_status {
my ($self, $msg) = @_;
$msg->{error} = 1 if $msg->{command} =~ m!90[14567]!;
$self->_irc_event_fallback($msg);
$self->info->{authenticated} = $msg->{command} =~ m!90[03]! ? true : false;
$self->emit(state => info => $self->info);
$self->_write("CAP END\r\n");
}
sub _irc_event_cap {
my ($self, $msg) = @_;
$self->_irc_event_fallback($msg);
if ($msg->{raw_line} =~ m!\s(?:LIST|LS)[^:]+:(.*)!) {
$self->info->{capabilities}{$_} = true for split /\s/, $1;
my @cap_req;
push @cap_req, 'sasl' if $self->info->{capabilities}{sasl} and $self->_sasl_mechanism;
$self->_write(@cap_req ? sprintf "CAP REQ :%s\r\n", join ' ', @cap_req : "CAP END\r\n");
}
elsif ($msg->{raw_line} =~ m!\sACK\W*(.+)!) {
my ($capabilities, $mech) = ($1, $self->_sasl_mechanism);
$self->_write("AUTHENTICATE $mech\r\n") if $capabilities =~ m!\bsasl\b!;
}
else {
$self->_write("CAP END\r\n");
}
}
sub _irc_event_ctcp_action {
shift->_irc_event_privmsg(@_);
}
sub _irc_event_ctcp_ping {
my ($self, $msg) = @_;
my $ts = $msg->{params}[1] or return;
my $nick = IRC::Utils::parse_user($msg->{prefix});
$self->_write(sprintf "NOTICE %s %s\r\n", $nick, $self->_make_ctcp_string("PING $ts"));
}
sub _irc_event_ctcp_time {
my ($self, $msg) = @_;
my $nick = IRC::Utils::parse_user($msg->{prefix});
$self->_write(sprintf "NOTICE %s %s\r\n",
$nick, $self->_make_ctcp_string(TIME => scalar localtime));
}
sub _irc_event_ctcp_version {
my ($self, $msg) = @_;
my $nick = IRC::Utils::parse_user($msg->{prefix});
$self->_write(sprintf "NOTICE %s %s\r\n",
$nick, $self->_make_ctcp_string("VERSION Convos $VERSION"));
}
sub _irc_event_err_cannotsendtochan {
my ($self, $msg) = @_;
$self->_message("Cannot send to channel $msg->{params}[1].", type => 'error');
}
sub _irc_event_err_erroneusnickname {
my ($self, $msg) = @_;
return if $msg->{handled};
my $nick = $msg->{params}[1] || 'unknown';
$self->_message("Invalid nickname $nick.", type => 'error');
}
sub _irc_event_err_nicknameinuse {
my ($self, $msg) = @_;
return if $msg->{handled};
# do not want to flod frontend with these messages
my $nick = $msg->{params}[1];
$self->_message("Nickname $nick is already in use.", type => 'error')
unless $self->{err_nicknameinuse}{$nick}++;
$self->info->{nick} = "${nick}_";
$self->emit(state => info => $self->info);
Mojo::IOLoop->timer(0.2 => sub { $self and $self->_write("NICK $self->info->{nick}\r\n") });
}
sub _irc_event_err_unknowncommand {
my ($self, $msg) = @_;
$self->_message("Unknown command: $msg->{params}[1]", type => 'error');
}
sub _irc_event_error {
my ($self, $msg) = @_;
$self->_irc_event_fallback($msg);
}
sub _irc_event_fallback {
my ($self, $msg) = @_;
my @params = @{$msg->{params}};
shift @params if $self->_is_current_nick($params[0]);
$self->emit(
message => $self->messages,
{
from => $self->id,
highlight => false,
message => join(' ', @params),
ts => time,
type => $msg->{error} || $msg->{command} =~ m!err! ? 'error' : 'notice',
}
);
}
sub _irc_event_invite {
my ($self, $msg) = @_;
my $conversation
= $self->conversation({name => $msg->{params}[1], frozen => 'You have a pending invitation.'});
$self->emit(state => frozen => $conversation->TO_JSON);
}
sub _irc_event_join {
my ($self, $msg) = @_;
my ($nick, $user, $host) = IRC::Utils::parse_user($msg->{prefix});
my $channel = $msg->{params}[0];
if ($self->_is_current_nick($nick)) {
my $conversation = $self->conversation({name => $channel, frozen => ''});
$self->emit(state => frozen => $conversation->TO_JSON);
$self->_write("TOPIC $channel\r\n"); # Topic is not part of the join response
}
elsif (my $conversation = $self->get_conversation($channel)) {
$self->emit(state => join => {conversation_id => $conversation->id, nick => $nick});
}
}
sub _irc_event_kick {
my ($self, $msg) = @_;
my ($kicker) = IRC::Utils::parse_user($msg->{prefix});
my $conversation = $self->conversation({name => $msg->{params}[0]});
my $nick = $msg->{params}[1];
my $reason = $msg->{params}[2] || '';
$self->emit(state => part =>
{conversation_id => $conversation->id, kicker => $kicker, nick => $nick, message => $reason});
}
# :superman!superman@i.love.debian.org MODE superman :+i
# :superman!superman@i.love.debian.org MODE #convos superman :+o
# :hybrid8.debian.local MODE #no_such_room +nt
sub _irc_event_mode {
my ($self, $msg) = @_;
return if $msg->{handled};
my $mode = $msg->{params}[1] || '';
if ($mode =~ /(o|v)$/ and $msg->{params}[2]) {
my $nick = $msg->{params}[2];
my ($from) = IRC::Utils::parse_user($msg->{prefix});
$self->emit(state => mode =>
{conversation_id => lc $msg->{params}[0], from => $from, mode => $mode, nick => $nick});
}
else {
my $params = $msg->{params}[2] // '';
$params =~ s!.!*!g if $mode =~ /k/;
$self->_notice("$msg->{params}[0] changed mode $mode $params");
}
}
sub _irc_event_rpl_motd {
my ($self, $msg) = @_;
my $message = $msg->{params}[1];
$message =~ s!^-\s!!;
$self->emit(
message => $self->messages,
{
from => $msg->{prefix} || $self->id,
highlight => false,
message => $message,
ts => time,
type => 'preformat',
}
);
}
# :Superman12923!superman@i.love.debian.org NICK :Supermanx
sub _irc_event_nick {
my ($self, $msg) = @_;
my ($old_nick) = IRC::Utils::parse_user($msg->{prefix});
my $new_nick = $msg->{params}[0];
my $wanted_nick = $self->url->query->param('nick');
if ($wanted_nick and $wanted_nick eq $new_nick) {
delete $self->{err_nicknameinuse}; # allow warning on next nick change
}
if ($self->nick eq $old_nick) {
$self->url->query->param(nick => $new_nick);
$self->info->{nick} = $new_nick;
$self->emit(state => info => $self->info);
}
else {
$self->emit(state => nick_change => {new_nick => $new_nick, old_nick => $old_nick});
}
}
sub _irc_event_part {
my ($self, $msg) = @_;
my ($nick, $user, $host) = IRC::Utils::parse_user($msg->{prefix});
my $conversation = $self->get_conversation($msg->{params}[0]);
my $reason = $msg->{params}[1] || '';
if ($conversation and !$self->_is_current_nick($nick)) {
$self->emit(
state => part => {conversation_id => $conversation->id, nick => $nick, message => $reason});
}
}
sub _irc_event_ping {
my ($self, $msg) = @_;
$self->_write("PONG $msg->{params}[0]\r\n");
}
# Do not care about the PING response
sub _irc_event_pong { }
sub _irc_event_notice {
my ($self, $msg) = @_;
# AUTH :*** Ident broken or disabled, to continue to connect you must type /QUOTE PASS 21105
$self->_write("QUOTE PASS $1\r\n") if $msg->{params}[0] =~ m!Ident broken.*QUOTE PASS (\S+)!;
$self->_irc_event_privmsg($msg);
}
sub _irc_event_privmsg {
my ($self, $msg) = @_;
my ($nick, $user, $host) = IRC::Utils::parse_user($msg->{prefix});
my ($from, $highlight, $target);
my ($conversation_id, @message) = @{$msg->{params}};
$message[0] = join ' ', @message;
if ($self->profile->find_service_account($nick, $conversation_id)) {
$target = $self->_is_current_nick($conversation_id) ? $nick : $conversation_id;
$target = $self->get_conversation($target) || $self->messages;
$from = $nick;
}
elsif ($user) {
$target = $self->_is_current_nick($conversation_id) ? $nick : $conversation_id;
$target = $self->get_conversation($target) || $self->conversation({name => $target});
$from = $nick;
}
$target ||= $self->messages;
$from ||= $self->id;
unless ($self->_is_current_nick($nick)) {
$highlight = grep { $message[0] =~ /\b\Q$_\E\b/i } $self->nick,
@{$self->user->highlight_keywords};
$target->inc_unread; # The unread count will be saved periodically by _periodic_events()
}
# server message or message without a conversation
$self->emit(
message => $target,
{
from => $from,
highlight => $highlight ? true : false,
message => $message[0],
ts => time,
type => _message_type($msg),
}
);
}
sub _irc_event_quit {
my ($self, $msg) = @_;
my ($nick, $user, $host) = IRC::Utils::parse_user($msg->{prefix});
$self->emit(state => quit => {nick => $nick, message => join ' ', @{$msg->{params}}});
}
sub _irc_event_rpl_list {
my ($self, $msg) = @_;
my $conversation = {n_users => 0 + $msg->{params}[2], topic => $msg->{params}[3]};
$conversation->{name} = $msg->{params}[1];
$conversation->{conversation_id} = lc $conversation->{name};
$conversation->{topic} =~ s!^(\[\+[a-z]+\])\s?!!; # remove mode from topic, such as [+nt]
$self->_available_conversations->{conversations}{$conversation->{name}} = $conversation;
}
sub _irc_event_rpl_listend {
my ($self, $msg) = @_;
$self->_available_conversations->{done} = true;
}
# :hybrid8.debian.local 004 superman hybrid8.debian.local hybrid-1:8.2.0+dfsg.1-2 DFGHRSWabcdefgijklnopqrsuwxy bciklmnoprstveIMORS bkloveIh
sub _irc_event_rpl_myinfo {
my ($self, $msg) = @_;
my @keys = qw(nick real_host version available_user_modes available_channel_modes);
my $i = 0;
$self->info->{$_} = $msg->{params}[$i++] // '' for @keys;
$self->emit(state => info => $self->info);
}
sub _irc_event_rpl_motdstart { }
sub _irc_event_authenticate {
my ($self, $msg) = @_;
$self->_irc_event_fallback($msg);
return unless $msg->{raw_line} =~ m!AUTHENTICATE \+$!;
my ($mech, $url) = ($self->_sasl_mechanism, $self->url);
my $username = $url->username || $self->nick;
if ($mech eq 'EXTERNAL') {
$self->_write(sprintf "AUTHENTICATE %s\r\n", b64_encode $username);
}
elsif ($mech eq 'PLAIN') {
my @auth = grep {length} $url->query->param('authname') || $username, $username, $url->password;
$self->_write(sprintf "AUTHENTICATE %s\r\n", b64_encode join "\0", @auth) if @auth == 3;
}
}
sub _irc_event_rpl_channelmodeis {
my ($self, $msg) = @_;
my @params = @{$msg->{params}};
shift @params unless $params[0] =~ $CHANNEL_RE;
$self->_notice("$params[0] has mode $params[1].");
}
sub _irc_event_rpl_notopic {
my ($self, $msg) = @_;
$self->_irc_event_rpl_topic({%$msg, params => [$msg->{params}[0], $msg->{params}[0], '']});
}
sub _irc_event_rpl_topic {
my ($self, $msg) = @_;
return unless my $conversation = $self->get_conversation($msg->{params}[1]);
return if $conversation->topic eq $msg->{params}[2];
$self->emit(state => frozen => $conversation->topic($msg->{params}[2])->TO_JSON);
}
sub _irc_event_rpl_umodeis {
my ($self, $msg) = @_;
$self->_is_current_nick($msg->{params}[0])
? $self->_notice("You ($msg->{params}[0]) have mode $msg->{params}[1].")
: $self->_notice("$msg->{params}[0] has mode $msg->{params}[1].");
}
# :hybrid8.debian.local 001 superman :Welcome to the debian Internet Relay Chat Network superman
sub _irc_event_rpl_welcome {
my ($self, $msg) = @_;
$self->info->{real_host} = $msg->{prefix};
$self->info->{nick} = $msg->{params}[0];
$self->_message($msg->{params}[1]); # Welcome to the debian Internet Relay Chat Network superman
$self->emit(state => info => $self->info);
$self->reconnect_delay(0);
my @commands = (
(grep {/\S/} @{$self->on_connect_commands}),
map {
$_->is_private ? [_send_whois_p => $_->{name}]
: $_->password ? [_send_join_p => "$_->{name} $_->{password}"]
: [_send_join_p => $_->{name}]
} sort { $a->id cmp $b->id } @{$self->conversations}
);
Scalar::Util::weaken($self);
my $i = (0);
(sub {
$i++;
return unless $self and @commands;
my $command = shift @commands;
my $p;
if (ref $command eq 'ARRAY') {
my $method = shift @$command;
$p = $self->$method(@$command);
}
elsif ($command =~ m!^/sleep\s+(\d+\.?\d*)!i) {
$p = Mojo::Promise->timer($1);
}
else {
$p = $self->send_p('', $command)
->catch(sub { $self->_message("On-connect command #$i failed: @_", type => 'error') });
}
$p->finally(__SUB__);
})->();
}
sub _irc_event_topic {
my ($self, $msg) = @_;
my ($nick, $user, $host) = IRC::Utils::parse_user($msg->{prefix});
$self->_irc_event_rpl_topic({%$msg, params => [$nick, $msg->{params}[0], $msg->{params}[1]]});
}
# Ignore these events
sub _irc_event_rpl_namreply { }
sub _irc_event_rpl_topicwhotime { }
sub _is_current_nick { lc $_[0]->nick eq lc $_[1] }
sub _make_away_response {
my ($self, $msg, $res, $p) = @_;
$p->resolve(
{away => $msg->{command} eq 'rpl_unaway' ? false : true, reason => $msg->{params}[1] // ''});
}
sub _make_ctcp_string {
my $self = shift;
local $_ = join ' ', @_;
s/([\012\015\0\cP])/\cP$CTCP_QUOTE{$1}/g;
s/\001/\\a/g;
return ":\001${_}\001";
}
sub _make_default_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
return $p->resolve($res);
}
sub _make_invite_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
$self->_notice("Invitation sent to $msg->{params}[1].");
$p->resolve({conversation_id => $msg->{params}[2], invited => $msg->{params}[1]});
}
sub _make_invalid_target_p {
my ($self, $target) = @_;
# err_norecipient and err_notexttosend
return Mojo::Promise->reject('Cannot send without target.')
if !$$target
or !($$target = trim $$target);
return Mojo::Promise->reject('Cannot send message to target with spaces or comma.')
if $$target =~ /[,\s]/;
return;
}
sub _make_ison_response {
my ($self, $msg, $res, $p) = @_; # No need to get ($res, $p) here
$msg->{ison} ||= {map { (lc($_) => $_) } split /\s+/, +($msg->{params}[1] || '')};
$res->{online} = $msg->{ison}{lc($res->{nick})} ? true : false;
my $conversation = $self->get_conversation($res->{nick});
$self->emit(state => frozen => $conversation->frozen('')->TO_JSON) if $conversation;
$p->resolve($res);
}
sub _make_join_response {
my ($self, $msg, $res, $p) = @_;
if ($msg->{command} eq '470') {
$self->_notice("Forwarding $msg->{params}[1] to $msg->{params}[2].");
return $self->_send_join_p("$msg->{params}[2]")->then(sub { $p->resolve($_[0]) });
}
if ($msg->{command} eq 'err_badchannelkey') {
my $conversation = $self->conversation({name => $msg->{params}[1]});
$self->emit(state => frozen => $conversation->frozen('Invalid password.')->TO_JSON);
return $p->reject($msg->{params}[2]);
}
if ($msg->{command} eq 'err_inviteonlychan') {
my $conversation = $self->conversation({name => $msg->{params}[1]});
$self->emit(
state => frozen => $conversation->frozen('This channel requires an invitation.')->TO_JSON);
return $p->reject($msg->{params}[2]);
}
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
return $self->_make_users_response($msg, $res->{participants} ||= [])
if $msg->{command} eq 'rpl_namreply';
return $res->{topic} = $msg->{params}[2] if $msg->{command} eq 'rpl_topic';
return $res->{topic_by} = $msg->{params}[2] if $msg->{command} eq 'rpl_topicwhotime';
if ($msg->{command} eq 'rpl_endofnames') {
my $conversation = $self->get_conversation($msg->{params}[1]);
$conversation->frozen('') if $conversation;
$res->{topic} //= '';
$res->{topic_by} //= '';
$res->{users} ||= {};
$p->resolve($res);
}
}
sub _make_mode_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_! or $msg->{command} eq '697';
$msg->{handled} = 1;
if ($msg->{command} eq 'mode') {
$res->{from} = IRC::Utils::parse_user($msg->{prefix});
$res->{mode} = $msg->{params}[1] // '';
$res->{mode_changed} = 1;
$res->{nick} = $msg->{params}[2] if $res->{mode} =~ /(o|v)$/ and $msg->{params}[2];
$res->{target} = $msg->{params}[0];
return $p->resolve($res);
}
if ($msg->{command} =~ m!^rpl_endof(\w+list)!) {
$res->{$1} ||= [];
return $p->resolve($res);
}
if ($msg->{command} =~ /^rpl_(\w+list)$/) {
push @{$res->{$1}},
{by => $msg->{params}[3] // '', mask => $msg->{params}[2], ts => $msg->{params}[4] || 0};
}
if ($msg->{command} eq 'rpl_channelmodeis') {
my @params = @{$msg->{params}};
shift @params unless $params[0] =~ $CHANNEL_RE;
@$res{qw(target mode)} = (shift @params, shift @params);
return $p->resolve($res);
}
if ($msg->{command} eq 'rpl_umodeis') {
@$res{qw(target mode)} = @{$msg->{params}};
return $p->resolve($res);
}
}
sub _make_names_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
return $p->resolve($res) if $msg->{command} eq 'rpl_endofnames';
return $self->_make_users_response($msg, $res->{participants} ||= [])
if $msg->{command} eq 'rpl_namreply';
}
sub _make_nick_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject(sprintf '%s: %s', $msg->{params}[-1], $res->{nick})
if $msg->{command} =~ m!^err_!;
return $p->resolve($res);
}
sub _make_oper_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
$self->info->{server_op} = true;
$self->emit(state => info => $self->info);
return $p->resolve($self->info);
}
sub _make_part_response {
my ($self, $msg, $res, $p) = @_;
$self->_remove_conversation(delete $res->{target})->save_p if $res->{target};
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
return $p->resolve($res);
}
sub _make_topic_response {
my ($self, $msg, $res, $p) = @_;
return $p->reject($msg->{params}[-1]) if $msg->{command} =~ m!^err_!;
$res->{topic} = '' if $msg->{command} eq 'rpl_notopic';
$res->{topic} = $msg->{params}[2] // '' if $msg->{command} eq 'rpl_topic';
$res->{topic} = $msg->{params}[1] // '' if $msg->{command} eq 'topic';
$p->resolve($res);
my $conversation = $self->get_conversation($msg->{params}[0]);
$self->emit(state => frozen => $conversation->topic($res->{topic})->TO_JSON)
if $conversation and $conversation->topic ne $res->{topic};
}
sub _make_whois_response {
my ($self, $msg, $res, $p) = @_;
if ($msg->{command} =~ m!^err_!) {
my $conversation = $self->get_conversation($msg->{params}[1]);
$self->emit(state => frozen => $conversation->frozen($msg->{params}[-1])->TO_JSON)
if $conversation;
return $p->reject($msg->{params}[-1]);
}
if ($msg->{command} eq 'rpl_endofwhois') {
my $conversation = $self->get_conversation($msg->{params}[1]);
my $info = $conversation && $conversation->info || {};
$res->{$_} //= '' for qw(away fingerprint host name nick server server_info user);
$res->{channels} //= [];
$res->{idle_for} //= 0;
$res->{ts} = time;
$info->{$_} = $res->{$_} for keys %$res;
$self->emit(state => frozen => $conversation->frozen('')->TO_JSON) if $conversation;
return $p->resolve($res);
}
if ($msg->{command} eq 'rpl_away' or $msg->{command} eq '301') {
my @msg = @{$msg->{params}};
return $res->{away} = join ' ', splice @msg, 2; # remove nick information
}
return $res->{idle_for} = 0 + ($msg->{params}[2] // 0) if $msg->{command} eq 'rpl_whoisidle';
return @$res{qw(server server_info)} = @{$msg->{params}}[2, 3]
if $msg->{command} eq 'rpl_whoisserver';
return @$res{qw(nick user host name)} = @{$msg->{params}}[1, 2, 3, 5]
if $msg->{command} eq 'rpl_whoisuser';
if ($msg->{command} eq '276') {
$res->{fingerprint} = $1 if $msg->{raw_line} =~ m!fingerprint\s(\S+)!;
}
if ($msg->{command} eq 'rpl_whoischannels') {
for (split /\s+/, $msg->{params}[2] || '') {
my ($mode, $channel) = $self->_parse_mode($_);
$res->{channels}{$channel} = {mode => $mode};
}
}
}
sub _make_users_response {
my ($self, $msg, $users) = @_;
for (split /\s+/, $msg->{params}[3]) {
my ($mode, $nick) = $self->_parse_mode($_);
push @$users, {nick => $nick, mode => $mode};
}
}
sub _message {
my ($self, $message) = (shift, shift);
my $from = $self->info->{real_host} || $self->id;
$self->emit(
message => $self->messages,
{from => $from, highlight => false, type => 'private', @_, message => $message, ts => time},
);
}
sub _message_type {
return 'private' if $_[0]->{command} =~ /privmsg/i;
return 'action' if $_[0]->{command} =~ /action/i;
return 'notice';
}
sub _parse {
state $parser = Parse::IRC->new(ctcp => 1);
return $parser->parse($_[1]);
}
sub _parse_mode {
state $modes = {'%' => 'h', '&' => 'a', '+' => 'v', '@' => 'o', '~' => 'q'};
return $_[1] =~ m!^([%&+@~])(.+)! ? ($modes->{$1}, $2) : ('', $_[1]);
}
sub _periodic_events {
my $self = shift;
my $tid;
Scalar::Util::weaken($self);
$tid = $self->{periodic_tid} //= Mojo::IOLoop->recurring(
PERIDOC_INTERVAL,
sub {
return shift->remove($tid) unless $self;
# Save unread count and other potential changes
$self->save_p;
# Try to get the nick you want
my $nick = $self->url->query->param('nick');
$self->_write("NICK $nick\r\n") if $nick and !$self->_is_current_nick($nick);
# Keep the connection alive
$self->_write("PING $self->info->{real_host}\r\n") if $self->info->{real_host};
}
);
}
sub _sasl_mechanism {
my $self = shift;
my $mech = uc($self->url->query->param('sasl') || '');
return $mech =~ m!^(EXTERNAL|PLAIN)$! ? $mech : '';
}
sub _send_away_p {
my ($self, $away_message) = @_;
$away_message = trim $away_message // '';
$away_message = ":$away_message" if length $away_message;
return $self->_write_and_wait_p(
"AWAY $away_message", {away => false},
rpl_nowaway => {},
rpl_unaway => {},
'_make_away_response',
);
}
sub _send_clear_p {
my ($self, $what, $target) = @_;
if (!$what or $what ne 'history' or !$target) {
return Mojo::Promise->reject(
'WARNING! /clear history [name] will delete all messages in the backend!');
}
my $conversation = $self->get_conversation($target);
return $target
? $self->user->core->backend->delete_messages_p($conversation)
: Mojo::Promise->reject('Unknown conversation.');
}
sub _send_invite_p {
my ($self, $target, $command) = @_;
my ($nick, $conversation_id) = split /\s/, ($command || ''), 2;
$conversation_id ||= $target;
return $self->_write_and_wait_p(
"INVITE $nick $conversation_id", {conversation_id => lc $conversation_id},
err_chanoprivsneeded => {1 => $target},
err_needmoreparams => {1 => $target},
err_nosuchnick => {1 => $nick},
err_notonchannel => {1 => $nick},
err_useronchannel => {1 => $target},
rpl_inviting => {1 => $nick},
'_make_invite_response',
);
}
sub _send_ison_p {
my ($self, $target) = @_;
return Mojo::Promise->reject('Cannot send without target.') unless $target;
return $self->_write_and_wait_p(
"ISON $target", {nick => $target},
rpl_ison => {},
'_make_ison_response',
);
}
sub _send_join_p {
my ($self, $command) = @_;
my ($conversation_id, $password) = (split(/\s/, ($command || ''), 2), '', '');
return $self->_send_query_p($conversation_id)->then(
sub {
my $conversation = shift;
$conversation->password($password) if $conversation and length $password;
return $conversation->TO_JSON if $command =~ m!^\w!; # A bit more sloppy than is_private
return !$conversation->frozen ? $conversation->TO_JSON : $self->_write_and_wait_p(
"JOIN $command", {conversation_id => lc $conversation_id},
470 => {1 => $conversation_id}, # Link channel
479 => {1 => $conversation_id}, # Illegal channel name
err_badchanmask => {1 => $conversation_id},
err_badchannelkey => {1 => $conversation_id},
err_bannedfromchan => {1 => $conversation_id},
err_channelisfull => {1 => $conversation_id},
err_inviteonlychan => {1 => $conversation_id},
err_nosuchchannel => {1 => $conversation_id},
err_toomanychannels => {1 => $conversation_id},
err_toomanytargets => {1 => $conversation_id},
err_unavailresource => {1 => $conversation_id},
rpl_endofnames => {1 => $conversation_id},
rpl_namreply => {1 => $conversation_id},
rpl_topic => {2 => $conversation_id},
rpl_topicwhotime => {1 => $conversation_id},
'_make_join_response',
);
},
sub {
return $self->_write_p("JOIN $command\r\n");
}
);
}
sub _send_kick_p {
my ($self, $target, $command) = @_;
my ($nick, $reason) = split /\s/, $command, 2;
for my $t ($target, $nick) {
my $invalid_target_p = $self->_make_invalid_target_p(\$t);
return $invalid_target_p if $invalid_target_p;
}
my $cmd = "KICK $target $nick";
$cmd .= " :$reason" if length $reason;
return $self->_write_and_wait_p(
$cmd, {},
err_nosuchchannel => {1 => $target},
err_nosuchnick => {1 => $nick},
err_badchanmask => {1 => $target},
err_chanoprivsneeded => {1 => $target},
err_usernotinchannel => {1 => $nick},
err_notonchannel => {1 => $nick},
kick => {0 => $target, 1 => $nick},
'_make_default_response',
);
}
sub _send_list_p {
my ($self, $extra) = @_;
return Mojo::Promise->reject('Not connected.') unless $self->state eq 'connected';
my $store = $self->_available_conversations;
my @found;
# Refresh conversation list
if ($extra =~ m!\brefresh\b! or !$store->{ts}) {
$store->{conversations} = {};
$store->{done} = false;
$store->{ts} = time;
$self->_write("LIST\r\n");
}
# Search for a specific channel - only works for cached channels
# IMPORTANT! Make sure the filter cannot execute code inside the regex!
if ($extra =~ m!/(\W?[\w-]+)/(\S*)!) {
my ($filter, $re_modifiers, $by, @by_name, @by_topic) = ($1, $2);
$re_modifiers = 'i' unless $re_modifiers;
$by = $re_modifiers =~ s!([nt])!! ? $1 : 'nt'; # name or topic
$filter = qr{(?$re_modifiers:$filter)} if $filter; # (?i:foo_bar)
for my $conversation (sort { $a->{name} cmp $b->{name} } values %{$store->{conversations}}) {
push @by_name, $conversation and next if $conversation->{name} =~ $filter;
push @by_topic, $conversation and next if $conversation->{topic} =~ $filter;
}
@found = ($by =~ /n/ ? @by_name : (), $by =~ /t/ ? @by_topic : ());
}
else {
@found = sort { $b->{n_users} <=> $a->{n_users} } values %{$store->{conversations}};
}
return Mojo::Promise->resolve({
n_conversations => int(keys %{$store->{conversations}}),
conversations => [splice @found, 0, 200],
done => $store->{done},
});
}
sub _send_message_p {
my $self = shift;
my $target = shift;
my $message = shift // '';
my $invalid_target_p = $self->_make_invalid_target_p(\$target);
return $invalid_target_p if $invalid_target_p;
my $messages = $self->profile->split_message($message);
return Mojo::Promise->reject('Cannot send empty message.') unless @$messages;
if ($self->profile->too_long_messages($messages)) {
return $self->user->core->backend->emit_p(message_to_paste => $self, $message)
->then(sub { $self->_send_message_p($target, shift) });
}
for (@$messages) {
$_ = $self->_parse(sprintf ':%s PRIVMSG %s :%s', $self->nick, $target, $_);
return Mojo::Promise->reject('Unable to construct PRIVMSG.') unless ref $_;
}
# Seems like there is no way to know if a message is delivered
# Instead, there might be some errors occuring if the message had issues:
# err_cannotsendtochan, err_nosuchnick, err_notoplevel, err_toomanytargets,
# err_wildtoplevel, irc_rpl_away
my $nick = $self->nick;
my $user = $self->url->username || $nick;
return Mojo::Promise->all(map { $self->_write_p($_->{raw_line}) } @$messages)->then(sub {
for my $msg (@$messages) {
$msg->{prefix} = sprintf '%s!%s@%s', $nick, $user, $self->url->host;
$msg->{event} = lc $msg->{command};
$self->_irc_event_privmsg($msg);
}
return {};
});
}
sub _send_mode_p {
my ($self, $target) = (shift, shift);
my @args = split /\s+/, shift;
$target ||= shift @args // '';
$target = shift @args if $args[0] and $args[0] =~ $CHANNEL_RE;
my $invalid_target_p = $self->_make_invalid_target_p(\$target);
return $invalid_target_p if $invalid_target_p;
my $res = {};
$res->{banlist} = [] if $args[0] and $args[0] eq 'b';
$res->{exceptlist} = [] if $args[0] and $args[0] eq 'e';
unshift @args, $target if $target;
return $self->_write_and_wait_p(
join(' ', MODE => @args), $res,
err_chanoprivsneeded => {1 => $target},
err_keyset => {1 => $target},
err_needmoreparams => {1 => $target},