source: perl/modules/IRC/lib/BarnOwl/Module/IRC.pm @ e0a5480

release-1.10
Last change on this file since e0a5480 was 4f7b1f4, checked in by Edward Z. Yang <ezyang@mit.edu>, 11 years ago
Support channel-or-user IRC commands, and setup irc-msg to use it. Signed-off-by: Edward Z. Yang <ezyang@mit.edu>
  • Property mode set to 100644
File size: 18.2 KB
Line 
1use strict;
2use warnings;
3
4package BarnOwl::Module::IRC;
5
6=head1 NAME
7
8BarnOwl::Module::IRC
9
10=head1 DESCRIPTION
11
12This module implements IRC support for BarnOwl.
13
14=cut
15
16use BarnOwl;
17use BarnOwl::Hooks;
18use BarnOwl::Message::IRC;
19use BarnOwl::Module::IRC::Connection qw(is_private);
20use BarnOwl::Module::IRC::Completion;
21
22use AnyEvent::IRC;
23use Getopt::Long;
24use Encode;
25use Text::Wrap;
26
27our $VERSION = 0.02;
28
29our $irc;
30
31# Hash alias -> BarnOwl::Module::IRC::Connection object
32our %ircnets;
33
34sub startup {
35    BarnOwl::new_variable_string('irc:nick', {
36        default     => $ENV{USER},
37        summary     => 'The default IRC nickname',
38        description => 'By default, irc-connect will use this nick '  .
39        'when connecting to a new server. See :help irc-connect for ' .
40        'more information.'
41       });
42
43    BarnOwl::new_variable_string('irc:user', {
44        default => $ENV{USER},
45        summary => 'The IRC "username" field'
46       });
47        BarnOwl::new_variable_string('irc:name', {
48        default => "",
49        summary     => 'A short name field for IRC',
50        description => 'A short (maybe 60 or so chars) piece of text, ' .
51        'originally intended to display your real name, which people '  .
52        'often use for pithy quotes and URLs.'
53       });
54
55    BarnOwl::new_variable_bool('irc:spew', {
56        default     => 0,
57        summary     => 'Show unhandled IRC events',
58        description => 'If set, display all unrecognized IRC events as ' .
59        'admin messages. Intended for debugging and development use only.'
60       });
61
62    BarnOwl::new_variable_string('irc:skip', {
63        default     => 'welcome yourhost created ' .
64        'luserclient luserme luserop luserchannels',
65        summary     => 'Skip messages of these types',
66        description => 'If set, each (space-separated) message type ' .
67        'provided will be hidden and ignored if received.'
68       });
69
70    BarnOwl::new_variable_int('irc:max-message-length', {
71        default     => 450,
72        summary     => 'Split messages to at most this many characters.' .
73                       "If non-positive, don't split messages",
74        description => 'If set to a positive number, any paragraph in an ' .
75                       'IRC message will be split after this many characters.'
76       });
77
78    register_commands();
79    BarnOwl::filter(qw{irc type ^IRC$ or ( type ^admin$ and adminheader ^IRC$ )});
80}
81
82sub shutdown {
83    for my $conn (values %ircnets) {
84        $conn->conn->disconnect('Quitting');
85    }
86}
87
88sub quickstart {
89    return <<'END_QUICKSTART';
90@b[IRC:]
91Use ':irc-connect @b[server]' to connect to an IRC server, and
92':irc-join @b[#channel]' to join a channel. ':irc-msg @b[#channel]
93@b[message]' sends a message to a channel.
94END_QUICKSTART
95}
96
97sub buddylist {
98    my $list = "";
99
100    for my $net (sort keys %ircnets) {
101        my $conn = $ircnets{$net};
102        my ($nick, $server) = ($conn->nick, $conn->server);
103        $list .= BarnOwl::Style::boldify("IRC channels for $net ($nick\@$server)");
104        $list .= "\n";
105
106        for my $chan (keys %{$conn->conn->{channel_list}}) {
107            $list .= "  $chan\n";
108        }
109    }
110
111    return $list;
112}
113
114sub skip_msg {
115    my $class = shift;
116    my $type = lc shift;
117    my $skip = lc BarnOwl::getvar('irc:skip');
118    return grep {$_ eq $type} split ' ', $skip;
119}
120
121=head2 mk_irc_command SUB FLAGS
122
123Return a subroutine that can be bound as a an IRC command. The
124subroutine will be called with arguments (COMMAND-NAME,
125IRC-CONNECTION, [CHANNEL], ARGV...).
126
127C<IRC-CONNECTION> and C<CHANNEL> will be inferred from arguments to
128the command and the current message if appropriate.
129
130The bitwise C<or> of zero or more C<FLAGS> can be passed in as a
131second argument to alter the behavior of the returned commands:
132
133=over 4
134
135=item C<CHANNEL_ARG>
136
137This command accepts the name of a channel. Pass in the C<CHANNEL>
138argument listed above, and die if no channel argument can be found.
139
140=item C<CHANNEL_OR_USER>
141
142Pass the channel argument, but accept it if it's a username (e.g.
143has no hash).  Only relevant with C<CHANNEL_ARG>.
144
145=item C<CHANNEL_OPTIONAL>
146
147Pass the channel argument, but don't die if not present. Only relevant
148with C<CHANNEL_ARG>.
149
150=item C<ALLOW_DISCONNECTED>
151
152C<IRC-CONNECTION> may be a disconnected connection object that is
153currently pending a reconnect.
154
155=back
156
157=cut
158
159use constant CHANNEL_ARG        => 1;
160use constant CHANNEL_OPTIONAL   => 2;
161use constant CHANNEL_OR_USER    => 4;
162
163use constant ALLOW_DISCONNECTED => 8;
164
165sub register_commands {
166    BarnOwl::new_command(
167        'irc-connect' => \&cmd_connect,
168        {
169            summary => 'Connect to an IRC server',
170            usage =>
171'irc-connect [-a ALIAS ] [-s] [-p PASSWORD] [-n NICK] SERVER [port]',
172            description => <<END_DESCR
173Connect to an IRC server. Supported options are:
174
175 -a <alias>          Define an alias for this server
176 -s                  Use SSL
177 -p <password>       Specify the password to use
178 -n <nick>           Use a non-default nick
179
180The -a option specifies an alias to use for this connection. This
181alias can be passed to the '-a' argument of any other IRC command to
182control which connection it operates on.
183
184For servers with hostnames of the form "irc.FOO.{com,org,...}", the
185alias will default to "FOO"; For other servers the full hostname is
186used.
187END_DESCR
188        }
189    );
190
191    BarnOwl::new_command(
192        'irc-disconnect' => mk_irc_command( \&cmd_disconnect, ALLOW_DISCONNECTED ),
193        {
194            summary => 'Disconnect from an IRC server',
195            usage   => 'irc-disconnect [-a ALIAS]',
196
197            description => <<END_DESCR
198Disconnect from an IRC server. You can specify a specific server with
199"-a SERVER-ALIAS" if necessary.
200END_DESCR
201        }
202    );
203
204    BarnOwl::new_command(
205        'irc-msg' => mk_irc_command( \&cmd_msg, CHANNEL_OR_USER|CHANNEL_ARG|CHANNEL_OPTIONAL ),
206        {
207            summary => 'Send an IRC message',
208            usage   => 'irc-msg [-a ALIAS] DESTINATION MESSAGE',
209
210            description => <<END_DESCR
211Send an IRC message.
212END_DESCR
213        }
214    );
215
216    BarnOwl::new_command(
217        'irc-mode' => mk_irc_command( \&cmd_mode, CHANNEL_OPTIONAL|CHANNEL_ARG ),
218        {
219            summary => 'Change an IRC channel or user mode',
220            usage   => 'irc-mode [-a ALIAS] TARGET [+-]MODE OPTIONS',
221
222            description => <<END_DESCR
223Change the mode of an IRC user or channel.
224END_DESCR
225        }
226    );
227
228    BarnOwl::new_command(
229        'irc-join' => mk_irc_command( \&cmd_join ),
230        {
231            summary => 'Join an IRC channel',
232            usage   => 'irc-join [-a ALIAS] #channel [KEY]',
233
234            description => <<END_DESCR
235Join an IRC channel.
236END_DESCR
237        }
238    );
239
240    BarnOwl::new_command(
241        'irc-part' => mk_irc_command( \&cmd_part, CHANNEL_ARG ),
242        {
243            summary => 'Leave an IRC channel',
244            usage   => 'irc-part [-a ALIAS] #channel',
245
246            description => <<END_DESCR
247Part from an IRC channel.
248END_DESCR
249        }
250    );
251
252    BarnOwl::new_command(
253        'irc-nick' => mk_irc_command( \&cmd_nick ),
254        {
255            summary => 'Change your IRC nick on an existing connection.',
256            usage   => 'irc-nick [-a ALIAS] NEW-NICK',
257
258            description => <<END_DESCR
259Set your IRC nickname on an existing connect. To change it prior to
260connecting, adjust the `irc:nick' variable.
261END_DESCR
262        }
263    );
264
265    BarnOwl::new_command(
266        'irc-names' => mk_irc_command( \&cmd_names, CHANNEL_ARG ),
267        {
268            summary => 'View the list of users in a channel',
269            usage   => 'irc-names [-a ALIAS] #channel',
270
271            description => <<END_DESCR
272`irc-names' displays the list of users in a given channel in a pop-up
273window.
274END_DESCR
275        }
276    );
277
278    BarnOwl::new_command(
279        'irc-whois' => mk_irc_command( \&cmd_whois ),
280        {
281            summary => 'Displays information about a given IRC user',
282            usage   => 'irc-whois [-a ALIAS] NICK',
283
284            description => <<END_DESCR
285Pops up information about a given IRC user.
286END_DESCR
287        }
288    );
289
290    BarnOwl::new_command(
291        'irc-motd' => mk_irc_command( \&cmd_motd ),
292        {
293            summary => 'Displays an IRC server\'s MOTD (Message of the Day)',
294            usage   => 'irc-motd [-a ALIAS]',
295
296            description => <<END_DESCR
297Displays an IRC server's message of the day.
298END_DESCR
299        }
300    );
301
302    BarnOwl::new_command(
303        'irc-list' => \&cmd_list,
304        {
305            summary => 'Show all the active IRC connections.',
306            usage   => 'irc-list',
307
308            description => <<END_DESCR
309Show all the currently active IRC connections with their aliases and
310server names.
311END_DESCR
312        }
313    );
314
315    BarnOwl::new_command( 'irc-who'   => mk_irc_command( \&cmd_who ) );
316    BarnOwl::new_command( 'irc-stats' => mk_irc_command( \&cmd_stats ) );
317
318    BarnOwl::new_command(
319        'irc-topic' => mk_irc_command( \&cmd_topic, CHANNEL_ARG ),
320        {
321            summary => 'View or change the topic of an IRC channel',
322            usage   => 'irc-topic [-a ALIAS] #channel [TOPIC]',
323
324            description => <<END_DESCR
325Without extra arguments, fetches and displays a given channel's topic.
326
327With extra arguments, changes the target channel's topic string. This
328may require +o on some channels.
329END_DESCR
330        }
331    );
332
333    BarnOwl::new_command(
334        'irc-quote' => mk_irc_command( \&cmd_quote ),
335        {
336            summary => 'Send a raw command to the IRC servers.',
337            usage   => 'irc-quote [-a ALIAS] TEXT',
338
339            description => <<END_DESCR
340Send a raw command line to an IRC server.
341
342This can be used to perform some operation not yet supported by
343BarnOwl, or to define new IRC commands.
344END_DESCR
345        }
346    );
347}
348
349
350$BarnOwl::Hooks::startup->add('BarnOwl::Module::IRC::startup');
351$BarnOwl::Hooks::shutdown->add('BarnOwl::Module::IRC::shutdown');
352$BarnOwl::Hooks::getQuickstart->add('BarnOwl::Module::IRC::quickstart');
353$BarnOwl::Hooks::getBuddyList->add("BarnOwl::Module::IRC::buddylist");
354
355################################################################################
356######################## Owl command handlers ##################################
357################################################################################
358
359sub cmd_connect {
360    my $cmd = shift;
361
362    my $nick = BarnOwl::getvar('irc:nick');
363    my $username = BarnOwl::getvar('irc:user');
364    my $ircname = BarnOwl::getvar('irc:name');
365    my $host;
366    my $port;
367    my $alias;
368    my $ssl;
369    my $password = undef;
370
371    {
372        local @ARGV = @_;
373        GetOptions(
374            "alias=s"    => \$alias,
375            "ssl"        => \$ssl,
376            "password=s" => \$password,
377            "nick=s"     => \$nick,
378        );
379        $host = shift @ARGV or die("Usage: $cmd HOST\n");
380        if(!$alias) {
381            if($host =~ /^(?:irc[.])?([\w-]+)[.]\w+$/) {
382                $alias = $1;
383            } else {
384                $alias = $host;
385            }
386        }
387        $ssl ||= 0;
388        $port = shift @ARGV || ($ssl ? 6697 : 6667);
389    }
390
391    if(exists $ircnets{$alias}) {
392        die("Already connected to a server with alias '$alias'. Either disconnect or specify an alias with -a.\n");
393    }
394
395    my $conn = BarnOwl::Module::IRC::Connection->new($alias, $host, $port, {
396        nick      => $nick,
397        user      => $username,
398        real      => $ircname,
399        password  => $password,
400        SSL       => $ssl,
401        timeout   => sub {0}
402       });
403    $ircnets{$alias} = $conn;
404    return;
405}
406
407sub cmd_disconnect {
408    my $cmd = shift;
409    my $conn = shift;
410    if ($conn->conn->{socket}) {
411        $conn->did_quit(1);
412        $conn->conn->disconnect("Goodbye!");
413    } elsif ($conn->{reconnect_timer}) {
414        BarnOwl::admin_message('IRC',
415                               "[" . $conn->alias . "] Reconnect cancelled");
416        $conn->cancel_reconnect;
417        delete $ircnets{$conn->alias};
418    }
419}
420
421sub cmd_msg {
422    my $cmd  = shift;
423    my $conn = shift;
424    my $to = shift or die("Usage: $cmd [NICK|CHANNEL]\n");
425    # handle multiple recipients?
426    if(@_) {
427        process_msg($conn, $to, join(" ", @_));
428    } else {
429        BarnOwl::start_edit_win(BarnOwl::quote('/msg', '-a', $conn->alias, $to), sub {process_msg($conn, $to, @_)});
430    }
431    return;
432}
433
434sub process_msg {
435    my $conn = shift;
436    my $to = shift;
437    my $fullbody = shift;
438    my @msgs;
439    # Require the user to send in paragraphs (double-newline between) to
440    # actually send multiple PRIVMSGs, in order to play nice with autofill.
441    $fullbody =~ s/\r//g;
442    @msgs = split "\n\n", $fullbody;
443    map { tr/\n/ / } @msgs;
444    # split each body at irc:max-message-length characters, if that number
445    # is positive.  Only split at space boundaries.  Start counting a-fresh
446    # at the beginning of each paragraph
447    my $max_len = BarnOwl::getvar('irc:max-message-length');
448    if ($max_len > 0) {
449        local($Text::Wrap::columns) = $max_len;
450        @msgs = split "\n", wrap("", "", join "\n", @msgs);
451    }
452    for my $body (@msgs) {
453        if ($body =~ /^\/me (.*)/) {
454            $conn->me($to, Encode::encode('utf-8', $1));
455            $body = '* '.$conn->nick.' '.$1;
456        } else {
457            $conn->conn->send_msg('privmsg', $to, Encode::encode('utf-8', $body));
458        }
459        my $msg = BarnOwl::Message->new(
460            type        => 'IRC',
461            direction   => is_private($to) ? 'out' : 'in',
462            server      => $conn->server,
463            network     => $conn->alias,
464            recipient   => $to,
465            body        => $body,
466            sender      => $conn->nick,
467            is_private($to) ?
468              (isprivate  => 'true') : (channel => $to),
469            replycmd    => BarnOwl::quote('irc-msg',  '-a', $conn->alias, $to),
470            replysendercmd => BarnOwl::quote('irc-msg', '-a', $conn->alias, $to),
471        );
472        BarnOwl::queue_message($msg);
473    }
474    return;
475}
476
477sub cmd_mode {
478    my $cmd = shift;
479    my $conn = shift;
480    my $target = shift;
481    $target ||= shift;
482    $conn->conn->send_msg(mode => $target, @_);
483    return;
484}
485
486sub cmd_join {
487    my $cmd = shift;
488    my $conn = shift;
489    my $chan = shift or die("Usage: $cmd channel\n");
490    $conn->conn->send_msg(join => $chan, @_);
491    return;
492}
493
494sub cmd_part {
495    my $cmd = shift;
496    my $conn = shift;
497    my $chan = shift;
498    $conn->conn->send_msg(part => $chan);
499    return;
500}
501
502sub cmd_nick {
503    my $cmd = shift;
504    my $conn = shift;
505    my $nick = shift or die("Usage: $cmd <new nick>\n");
506    $conn->conn->send_msg(nick => $nick);
507    return;
508}
509
510sub cmd_names {
511    my $cmd = shift;
512    my $conn = shift;
513    my $chan = shift;
514    $conn->names_tmp([]);
515    $conn->conn->send_msg(names => $chan);
516    return;
517}
518
519sub cmd_whois {
520    my $cmd = shift;
521    my $conn = shift;
522    my $who = shift || die("Usage: $cmd <user>\n");
523    $conn->conn->send_msg(whois => $who);
524    return;
525}
526
527sub cmd_motd {
528    my $cmd = shift;
529    my $conn = shift;
530    $conn->conn->send_msg('motd');
531    return;
532}
533
534sub cmd_list {
535    my $cmd = shift;
536    my $message = BarnOwl::Style::boldify('Current IRC networks:') . "\n";
537    while (my ($alias, $conn) = each %ircnets) {
538        $message .= '  ' . $alias . ' => ' . $conn->nick . '@' . $conn->server . "\n";
539    }
540    BarnOwl::popless_ztext($message);
541    return;
542}
543
544sub cmd_who {
545    my $cmd = shift;
546    my $conn = shift;
547    my $who = shift || die("Usage: $cmd <user>\n");
548    $conn->conn->send_msg(who => $who);
549    return;
550}
551
552sub cmd_stats {
553    my $cmd = shift;
554    my $conn = shift;
555    my $type = shift || die("Usage: $cmd <chiklmouy> [server] \n");
556    $conn->conn->send_msg(stats => $type, @_);
557    return;
558}
559
560sub cmd_topic {
561    my $cmd = shift;
562    my $conn = shift;
563    my $chan = shift;
564    $conn->conn->send_msg(topic => $chan, @_ ? join(" ", @_) : undef);
565    return;
566}
567
568sub cmd_quote {
569    my $cmd = shift;
570    my $conn = shift;
571    $conn->conn->send_msg(@_);
572    return;
573}
574
575################################################################################
576########################### Utilities/Helpers ##################################
577################################################################################
578
579sub find_channel {
580    my $channel = shift;
581    my @found;
582    for my $conn (values %ircnets) {
583        if($conn->conn->{channel_list}{lc $channel}) {
584            push @found, $conn;
585        }
586    }
587    return $found[0] if(scalar @found == 1);
588}
589
590sub mk_irc_command {
591    my $sub = shift;
592    my $flags = shift || 0;
593    return sub {
594        my $cmd = shift;
595        my $conn;
596        my $alias;
597        my $channel;
598        my $getopt = Getopt::Long::Parser->new;
599        my $m = BarnOwl::getcurmsg();
600
601        local @ARGV = @_;
602        $getopt->configure(qw(pass_through permute no_getopt_compat prefix_pattern=-|--));
603        $getopt->getoptions("alias=s" => \$alias);
604
605        if(defined($alias)) {
606            $conn = get_connection_by_alias($alias,
607                                            $flags & ALLOW_DISCONNECTED);
608        }
609        if($flags & CHANNEL_ARG) {
610            $channel = $ARGV[0];
611            if(defined($channel) && $channel =~ /^#/) {
612                if(my $c = find_channel($channel)) {
613                    shift @ARGV;
614                    $conn ||= $c;
615                }
616            } elsif (defined($channel) && ($flags & CHANNEL_OR_USER)) {
617                shift @ARGV;
618            } elsif ($m && $m->type eq 'IRC' && !$m->is_private) {
619                $channel = $m->channel;
620            } else {
621                undef $channel;
622            }
623        }
624
625        if(!defined($channel) &&
626           ($flags & CHANNEL_ARG) &&
627           !($flags & CHANNEL_OPTIONAL)) {
628            die("Usage: $cmd <channel>\n");
629        }
630        if(!$conn) {
631            if($m && $m->type eq 'IRC') {
632                $conn = get_connection_by_alias($m->network,
633                                               $flags & ALLOW_DISCONNECTED);
634            }
635        }
636        if(!$conn && scalar keys %ircnets == 1) {
637            $conn = [values(%ircnets)]->[0];
638        }
639        if(!$conn) {
640            die("You must specify an IRC network using -a.\n");
641        }
642        if($flags & CHANNEL_ARG) {
643            $sub->($cmd, $conn, $channel, @ARGV);
644        } else {
645            $sub->($cmd, $conn, @ARGV);
646        }
647    };
648}
649
650sub get_connection_by_alias {
651    my $key = shift;
652    my $allow_disconnected = shift;
653
654    my $conn = $ircnets{$key};
655    die("No such ircnet: $key\n") unless $conn;
656    if ($conn->conn->{registered} || $allow_disconnected) {
657        return $conn;
658    }
659    die("[@{[$conn->alias]}] Not currently connected.");
660}
661
6621;
Note: See TracBrowser for help on using the repository browser.