source: perl/modules/IRC/lib/BarnOwl/Module/IRC/Connection.pm @ 851a0e0

release-1.10release-1.8release-1.9
Last change on this file since 851a0e0 was 851a0e0, checked in by Nelson Elhage <nelhage@mit.edu>, 13 years ago
IRC: Remove circular references between ::Connection and its Client.
  • Property mode set to 100644
File size: 13.3 KB
RevLine 
[b38b0b2]1use strict;
2use warnings;
3
4package BarnOwl::Module::IRC::Connection;
[3b4ba7d]5use BarnOwl::Timer;
[b38b0b2]6
7=head1 NAME
8
9BarnOwl::Module::IRC::Connection
10
11=head1 DESCRIPTION
12
[ba2ca66]13This module is a wrapper around Net::IRC::Connection for BarnOwl's IRC
[b38b0b2]14support
15
16=cut
17
[8ba9313]18use AnyEvent::IRC::Client;
19use AnyEvent::IRC::Util qw(split_prefix prefix_nick);
[ba2ca66]20
[8ba9313]21use base qw(Class::Accessor);
22use Exporter 'import';
[4787581]23__PACKAGE__->mk_accessors(qw(conn alias motd names_tmp whois_tmp server autoconnect_channels));
[8ba9313]24our @EXPORT_OK = qw(is_private);
[b38b0b2]25
26use BarnOwl;
[3acab0e]27use Scalar::Util qw(weaken);
[b38b0b2]28
29sub new {
30    my $class = shift;
31    my $alias = shift;
[8ba9313]32    my $host  = shift;
33    my $port  = shift;
34    my $args  = shift;
35    my $nick = $args->{nick};
36    my $conn = AnyEvent::IRC::Client->new();
[ba2ca66]37    my $self = bless({}, $class);
38    $self->conn($conn);
[8ba9313]39    $self->autoconnect_channels([]);
[b38b0b2]40    $self->alias($alias);
[8ba9313]41    $self->server($host);
[ba2ca66]42    $self->motd("");
[d264c6d]43    $self->names_tmp(0);
[38cfdb5d]44    $self->whois_tmp("");
[ba2ca66]45
[851a0e0]46    if(delete $args->{SSL}) {
47        $conn->enable_ssl;
48    }
49    $conn->connect($host, $port, $args);
50    $conn->{heap}{parent} = $self;
51    weaken($conn->{heap}{parent});
52
53    sub on {
54        my $meth = "on_" . shift;
55        return sub {
56            my $conn = shift;
57            return unless $conn->{heap}{parent};
58            $conn->{heap}{parent}->$meth(@_);
59        }
60    }
61
[8ba9313]62    # $self->conn->add_default_handler(sub { shift; $self->on_event(@_) });
[851a0e0]63    $self->conn->reg_cb(registered => on("connected"),
64                        connfail   => sub { BarnOwl::error("Connection to $host failed!") },
65                        disconnect => on("disconnect"),
66                        publicmsg  => on("msg"),
67                        privatemsg => on("msg"));
[8ba9313]68    for my $m (qw(welcome yourhost created
69                  luserclient luserop luserchannels luserme
70                  error)) {
[851a0e0]71        $self->conn->reg_cb("irc_$m" => on("admin_msg"));
[8ba9313]72    }
[851a0e0]73    $self->conn->reg_cb(irc_375       => on("motdstart"),
74                        irc_372       => on("motd"),
75                        irc_376       => on("endofmotd"),
76                        irc_join      => on("join"),
77                        irc_part      => on("part"),
78                        irc_quit      => on("quit"),
79                        irc_433       => on("nickinuse"),
80                        channel_topic => on("topic"),
81                        irc_333       => on("topicinfo"),
82                        irc_353       => on("namreply"),
83                        irc_366       => on("endofnames"),
84                        irc_311       => on("whois"),
85                        irc_312       => on("whois"),
86                        irc_319       => on("whois"),
87                        irc_320       => on("whois"),
88                        irc_318       => on("endofwhois"),
89                        irc_mode      => on("mode"),
90                        irc_401       => on("nosuch"),
91                        irc_402       => on("nosuch"),
92                        irc_403       => on("nosuch"),
93                        nick_change   => on("nick"),
[8ba9313]94                        'irc_*' => sub { BarnOwl::debug("IRC: " . $_[1]->{command}) });
[330c55a]95
[b38b0b2]96    return $self;
97}
98
[4787581]99sub nick {
100    my $self = shift;
101    return $self->conn->nick;
102}
103
[9c7a701]104sub getSocket
105{
106    my $self = shift;
107    return $self->conn->socket;
108}
109
[b38b0b2]110################################################################################
111############################### IRC callbacks ##################################
112################################################################################
113
[47b6a5f]114sub new_message {
115    my $self = shift;
116    my $evt = shift;
[8ba9313]117    my ($nick, $user, $host) = split_prefix($evt);
[47b6a5f]118    return BarnOwl::Message->new(
119        type        => 'IRC',
120        server      => $self->server,
121        network     => $self->alias,
[8ba9313]122        sender      => $nick,
123        defined($host) ? (hostname    => $host) : (),
124        from        => $evt->{prefix},
[47b6a5f]125        @_
126       );
127}
128
[b38b0b2]129sub on_msg {
[8ba9313]130    my ($self, $recipient, $evt) = @_;
131    my $body = strip_irc_formatting($evt->{params}->[1]);
132
[47b6a5f]133    my $msg = $self->new_message($evt,
[b38b0b2]134        direction   => 'in',
[2c40dc0]135        recipient   => $recipient,
[8ba9313]136        body        => $body,
137        $evt->{command} eq 'notice' ?
[2c40dc0]138          (notice     => 'true') : (),
139        is_private($recipient) ?
[99c1f46]140          (private  => 'true') : (channel => $recipient),
[744769e]141        replycmd    => BarnOwl::quote('irc-msg', '-a', $self->alias,
[8ba9313]142           (is_private($recipient) ? prefix_nick($evt) : $recipient)),
143        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
[b38b0b2]144       );
[47b6a5f]145
[b38b0b2]146    BarnOwl::queue_message($msg);
147}
148
[bc0d7bc]149sub on_admin_msg {
150    my ($self, $evt) = @_;
[8ba9313]151    return if BarnOwl::Module::IRC->skip_msg($evt->{command});
[bc0d7bc]152    BarnOwl::admin_message("IRC",
[8ba9313]153            BarnOwl::Style::boldify('IRC ' . $evt->{command} . ' message from '
[1951db8]154                . $self->alias) . "\n"
[8ba9313]155            . strip_irc_formatting(join ' ', cdr($evt->{params})));
[bc0d7bc]156}
157
158sub on_motdstart {
159    my ($self, $evt) = @_;
[8ba9313]160    $self->motd(join "\n", cdr(@{$evt->{params}}));
[bc0d7bc]161}
162
163sub on_motd {
164    my ($self, $evt) = @_;
[8ba9313]165    $self->motd(join "\n", $self->motd, cdr(@{$evt->{params}}));
[bc0d7bc]166}
167
168sub on_endofmotd {
169    my ($self, $evt) = @_;
[8ba9313]170    $self->motd(join "\n", $self->motd, cdr(@{$evt->{params}}));
[bc0d7bc]171    BarnOwl::admin_message("IRC",
[3baf77f]172            BarnOwl::Style::boldify('MOTD for ' . $self->alias) . "\n"
[ba2ca66]173            . strip_irc_formatting($self->motd));
[bc0d7bc]174}
175
[47b6a5f]176sub on_join {
177    my ($self, $evt) = @_;
[8ba9313]178    my $chan = $evt->{params}[0];
[47b6a5f]179    my $msg = $self->new_message($evt,
180        loginout   => 'login',
[4789b17]181        action     => 'join',
[8ba9313]182        channel    => $chan,
183        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $chan),
184        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
[47b6a5f]185        );
186    BarnOwl::queue_message($msg);
187}
188
189sub on_part {
190    my ($self, $evt) = @_;
[8ba9313]191    my $chan = $evt->{params}[0];
[47b6a5f]192    my $msg = $self->new_message($evt,
193        loginout   => 'logout',
[4789b17]194        action     => 'part',
[8ba9313]195        channel    => $chan,
196        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $chan),
197        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
[47b6a5f]198        );
199    BarnOwl::queue_message($msg);
200}
201
[4789b17]202sub on_quit {
203    my ($self, $evt) = @_;
204    my $msg = $self->new_message($evt,
205        loginout   => 'logout',
206        action     => 'quit',
[8ba9313]207        from       => $evt->{prefix},
208        reason     => $evt->{params}->[1],
209        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
210        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, prefix_nick($evt)),
[4789b17]211        );
212    BarnOwl::queue_message($msg);
213}
214
[3b4ba7d]215sub disconnect {
[9e02bb7]216    my $self = shift;
[0e8a0fc]217    for my $k (keys %BarnOwl::Module::IRC::channels) {
218        my @conns = grep {$_ ne $self} @{$BarnOwl::Module::IRC::channels{$k}};
219        if(@conns) {
220            $BarnOwl::Module::IRC::channels{$k} = \@conns;
221        } else {
222            delete $BarnOwl::Module::IRC::channels{$k};
223        }
224    }
[3b4ba7d]225    $self->motd("");
226}
227
228sub on_disconnect {
[8ba9313]229    my ($self, $why) = @_;
[3b4ba7d]230    $self->disconnect;
[9e02bb7]231    BarnOwl::admin_message('IRC',
232                           "[" . $self->alias . "] Disconnected from server");
[8ba9313]233    if ($why && $why =~ m{error in connection}) {
[3b4ba7d]234        $self->schedule_reconnect;
235    }
[9e02bb7]236}
237
238sub on_nickinuse {
239    my ($self, $evt) = @_;
240    BarnOwl::admin_message("IRC",
241                           "[" . $self->alias . "] " .
[8ba9313]242                           $evt->{params}->[1] . ": Nick already in use");
[9e02bb7]243}
244
[38d50c2]245sub on_nick {
246    my ($self, $old_nick, $new_nick, $is_me) = @_;
247    if ($is_me) {
248        BarnOwl::admin_message("IRC",
249                               "[" . $self->alias . "] " .
250                               "You are now known as $new_nick");
251    } else {
252        BarnOwl::admin_message("IRC",
253                               "[" . $self->alias . "] " .
254                               "$old_nick is now known as $new_nick");
255    }
256}
257
[3ad15ff]258sub on_topic {
[8ba9313]259    my ($self, $channel, $topic, $who) = @_;
260    if ($channel) {
[3ad15ff]261        BarnOwl::admin_message("IRC",
[8ba9313]262                "Topic for $channel on " . $self->alias . " is $topic");
[3ad15ff]263    } else {
264        BarnOwl::admin_message("IRC",
[8ba9313]265                "Topic changed to $channel");
[3ad15ff]266    }
267}
268
269sub on_topicinfo {
270    my ($self, $evt) = @_;
[8ba9313]271    my @args = @{$evt->{params}};
[3ad15ff]272    BarnOwl::admin_message("IRC",
273        "Topic for $args[1] set by $args[2] at " . localtime($args[3]));
274}
275
[38cfdb5d]276# IRC gives us a bunch of namreply messages, followed by an endofnames.
277# We need to collect them from the namreply and wait for the endofnames message.
278# After this happens, the names_tmp variable is cleared.
279
280sub on_namreply {
281    my ($self, $evt) = @_;
[d264c6d]282    return unless $self->names_tmp;
[8ba9313]283    $self->names_tmp([@{$self->names_tmp}, split(' ', $evt->{params}[3])]);
[38cfdb5d]284}
285
[fb6e8e3]286sub cmp_user {
287    my ($lhs, $rhs) = @_;
288    my ($sigil_l) = ($lhs =~ m{^([+@]?)});
289    my ($sigil_r) = ($rhs =~ m{^([+@]?)});
290    my %rank = ('@' => 1, '+' => 2, '' => 3);
291    return ($rank{$sigil_l} <=> $rank{$sigil_r}) ||
292            $lhs cmp $rhs;
293}
294
[38cfdb5d]295sub on_endofnames {
296    my ($self, $evt) = @_;
[d264c6d]297    return unless $self->names_tmp;
[8ba9313]298    my $names = BarnOwl::Style::boldify("Members of " . $evt->{params}->[1] . ":\n");
[fb6e8e3]299    for my $name (sort {cmp_user($a, $b)} @{$self->names_tmp}) {
[38cfdb5d]300        $names .= "  $name\n";
301    }
302    BarnOwl::popless_ztext($names);
[d264c6d]303    $self->names_tmp(0);
304}
305
306sub on_whois {
307    my ($self, $evt) = @_;
[8ba9313]308    my %names = (
309        311 => 'user',
310        312 => 'server',
311        319 => 'channels',
312        330 => 'whowas',
313       );
[d264c6d]314    $self->whois_tmp(
[8ba9313]315        $self->whois_tmp . "\n" . $names{$evt->{command}} . ":\n  " .
316        join("\n  ", cdr(cdr(@{$evt->{params}}))) . "\n"
317       );
[d264c6d]318}
319
320sub on_endofwhois {
321    my ($self, $evt) = @_;
322    BarnOwl::popless_ztext(
[8ba9313]323        BarnOwl::Style::boldify("/whois for " . $evt->{params}->[1] . ":\n") .
[d264c6d]324        $self->whois_tmp
325    );
[7c83a32]326    $self->whois_tmp('');
[d264c6d]327}
328
[4df2568]329sub on_mode {
330    my ($self, $evt) = @_;
331    BarnOwl::admin_message("IRC",
[8ba9313]332                           "[" . $self->alias . "] User " . (prefix_nick($evt)) . + " set mode " .
333                           join(" ", cdr(@{$evt->{params}})) . "on " . $evt->{params}->[0]
[4df2568]334                          );
335}
336
[8ba9313]337sub on_nosuch {
[7cfb1df]338    my ($self, $evt) = @_;
[8ba9313]339    my %things = (401 => 'nick', 402 => 'server', 403 => 'channel');
[7cfb1df]340    BarnOwl::admin_message("IRC",
341                           "[" . $self->alias . "] " .
[8ba9313]342                           "No such @{[$things{$evt->{command}}]}: @{[$evt->{params}->[1]]}")
[7cfb1df]343}
344
[d264c6d]345sub on_event {
346    my ($self, $evt) = @_;
347    return on_whois(@_) if ($evt->type =~ /^whois/);
348    BarnOwl::admin_message("IRC",
349            "[" . $self->alias . "] Unhandled IRC event of type " . $evt->type . ":\n"
350            . strip_irc_formatting(join("\n", $evt->args)))
351        if BarnOwl::getvar('irc:spew') eq 'on';
[38cfdb5d]352}
[9e02bb7]353
[3b4ba7d]354sub schedule_reconnect {
355    my $self = shift;
356    my $interval = shift || 5;
[3acab0e]357    $BarnOwl::Module::IRC::reconnect{$self->alias} = $self;
358    my $weak = $self;
359    weaken($weak);
[c8d9f84]360    if (defined $self->{reconnect_timer}) {
361        $self->{reconnect_timer}->stop;
362    }
[3acab0e]363    $self->{reconnect_timer} = 
[3b4ba7d]364        BarnOwl::Timer->new( {
[c6adf17]365            name  => 'IRC (' . $self->alias . ') reconnect_timer',
[3b4ba7d]366            after => $interval,
367            cb    => sub {
[3acab0e]368                $weak->reconnect( $interval ) if $weak;
[3b4ba7d]369            },
370        } );
371}
372
[416241f]373sub cancel_reconnect {
374    my $self = shift;
375    delete $BarnOwl::Module::IRC::reconnect{$self->alias};
[c8d9f84]376    if (defined $self->{reconnect_timer}) {
377        $self->{reconnect_timer}->stop;
378    }
[416241f]379    delete $self->{reconnect_timer};
380}
381
[851a0e0]382sub on_connect {
383    my $self = shift;
384    $self->connected("Connected to $self->alias as $self->nick")
385}
386
[3b4ba7d]387sub connected {
388    my $self = shift;
389    my $msg = shift;
390    BarnOwl::admin_message("IRC", $msg);
[416241f]391    $self->cancel_reconnect;
[8ba9313]392    if ($self->autoconnect_channels) {
393        for my $c (@{$self->autoconnect_channels}) {
394            $self->conn->send_msg(join => $c);
395        }
396        $self->autoconnect_channels([]);
397    }
398    $self->conn->enable_ping(60, sub {
399                                 $self->disconnect("Connection timed out.");
400                                 $self->schedule_reconnect;
401                             });
[3b4ba7d]402}
403
404sub reconnect {
405    my $self = shift;
406    my $backoff = shift;
407
[8ba9313]408    $self->autoconnect_channels([keys(%{$self->channel_list})]);
[3b4ba7d]409    $self->conn->connect;
410    if ($self->conn->connected) {
411        $self->connected("Reconnected to ".$self->alias);
412        return;
413    }
414
415    $backoff *= 2;
416    $backoff = 60*5 if $backoff > 60*5;
417    $self->schedule_reconnect( $backoff );
418}
419
[b38b0b2]420################################################################################
421########################### Utilities/Helpers ##################################
422################################################################################
423
424sub strip_irc_formatting {
425    my $body = shift;
[214b790]426    # Strip mIRC colors. If someone wants to write code to convert
427    # these to zephyr colors, be my guest.
428    $body =~ s/\cC\d+(?:,\d+)?//g;
429    $body =~ s/\cO//g;
430   
431    my @pieces = split /\cB/, $body;
[3835ae8]432    my $out = '';
[b38b0b2]433    while(@pieces) {
434        $out .= shift @pieces;
435        $out .= BarnOwl::Style::boldify(shift @pieces) if @pieces;
436    }
437    return $out;
438}
439
[2c40dc0]440# Determines if the given message recipient is a username, as opposed to
441# a channel that starts with # or &.
442sub is_private {
443    return shift !~ /^[\#\&]/;
444}
[b38b0b2]445
[bc0d7bc]446sub cdr {
447    shift;
448    return @_;
449}
450
[b38b0b2]4511;
Note: See TracBrowser for help on using the repository browser.