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

release-1.10release-1.7release-1.8release-1.9
Last change on this file since c6adf17 was c6adf17, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Track names along with timers, add :show timers This will help people with BarnOwls eating CPU to diagnose timer leaks.
  • Property mode set to 100644
File size: 12.1 KB
Line 
1use strict;
2use warnings;
3
4package BarnOwl::Module::IRC::Connection;
5use BarnOwl::Timer;
6
7=head1 NAME
8
9BarnOwl::Module::IRC::Connection
10
11=head1 DESCRIPTION
12
13This module is a wrapper around Net::IRC::Connection for BarnOwl's IRC
14support
15
16=cut
17
18use Net::IRC::Connection;
19
20use base qw(Class::Accessor Exporter);
21__PACKAGE__->mk_accessors(qw(conn alias channels motd names_tmp whois_tmp));
22our @EXPORT_OK = qw(&is_private);
23
24use BarnOwl;
25use Scalar::Util qw(weaken);
26
27BEGIN {
28    no strict 'refs';
29    my @delegate = qw(nick server);
30    for my $meth (@delegate) {
31        *{"BarnOwl::Module::IRC::Connection::$meth"} = sub {
32            shift->conn->$meth(@_);
33        }
34    }
35};
36
37sub new {
38    my $class = shift;
39    my $irc = shift;
40    my $alias = shift;
41    my %args = (@_);
42    my $conn = Net::IRC::Connection->new($irc, %args);
43    my $self = bless({}, $class);
44    $self->conn($conn);
45    $self->alias($alias);
46    $self->channels([]);
47    $self->motd("");
48    $self->names_tmp(0);
49    $self->whois_tmp("");
50
51    $self->conn->add_default_handler(sub { shift; $self->on_event(@_) });
52    $self->conn->add_handler(['msg', 'notice', 'public', 'caction'],
53            sub { shift; $self->on_msg(@_) });
54    $self->conn->add_handler(['welcome', 'yourhost', 'created',
55                              'luserclient', 'luserop', 'luserchannels', 'luserme',
56                              'error'],
57            sub { shift; $self->on_admin_msg(@_) });
58    $self->conn->add_handler(['myinfo', 'map', 'n_local', 'n_global',
59            'luserconns'],
60            sub { });
61    $self->conn->add_handler(motdstart => sub { shift; $self->on_motdstart(@_) });
62    $self->conn->add_handler(motd      => sub { shift; $self->on_motd(@_) });
63    $self->conn->add_handler(endofmotd => sub { shift; $self->on_endofmotd(@_) });
64    $self->conn->add_handler(join      => sub { shift; $self->on_join(@_) });
65    $self->conn->add_handler(part      => sub { shift; $self->on_part(@_) });
66    $self->conn->add_handler(quit      => sub { shift; $self->on_quit(@_) });
67    $self->conn->add_handler(disconnect => sub { shift; $self->on_disconnect(@_) });
68    $self->conn->add_handler(nicknameinuse => sub { shift; $self->on_nickinuse(@_) });
69    $self->conn->add_handler(cping     => sub { shift; $self->on_ping(@_) });
70    $self->conn->add_handler(topic     => sub { shift; $self->on_topic(@_) });
71    $self->conn->add_handler(topicinfo => sub { shift; $self->on_topicinfo(@_) });
72    $self->conn->add_handler(namreply  => sub { shift; $self->on_namreply(@_) });
73    $self->conn->add_handler(endofnames=> sub { shift; $self->on_endofnames(@_) });
74    $self->conn->add_handler(endofwhois=> sub { shift; $self->on_endofwhois(@_) });
75    $self->conn->add_handler(mode      => sub { shift; $self->on_mode(@_) });
76    $self->conn->add_handler(nosuchchannel => sub { shift; $self->on_nosuchchannel(@_) });
77
78    return $self;
79}
80
81sub getSocket
82{
83    my $self = shift;
84    return $self->conn->socket;
85}
86
87################################################################################
88############################### IRC callbacks ##################################
89################################################################################
90
91sub new_message {
92    my $self = shift;
93    my $evt = shift;
94    return BarnOwl::Message->new(
95        type        => 'IRC',
96        server      => $self->server,
97        network     => $self->alias,
98        sender      => $evt->nick,
99        hostname    => $evt->host,
100        from        => $evt->from,
101        @_
102       );
103}
104
105sub on_msg {
106    my ($self, $evt) = @_;
107    my ($recipient) = $evt->to;
108    my $body = strip_irc_formatting([$evt->args]->[0]);
109    my $nick = $self->nick;
110    $body = '* '.$evt->nick.' '.$body if $evt->type eq 'caction';
111    my $msg = $self->new_message($evt,
112        direction   => 'in',
113        recipient   => $recipient,
114        body => $body,
115        $evt->type eq 'notice' ?
116          (notice     => 'true') : (),
117        is_private($recipient) ?
118          (private  => 'true') : (channel => $recipient),
119        replycmd    => BarnOwl::quote('irc-msg', '-a', $self->alias,
120          (is_private($recipient) ? $evt->nick : $recipient)),
121        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->nick),
122       );
123
124    BarnOwl::queue_message($msg);
125}
126
127sub on_ping {
128    my ($self, $evt) = @_;
129    $self->conn->ctcp_reply($evt->nick, join (' ', ($evt->args)));
130}
131
132sub on_admin_msg {
133    my ($self, $evt) = @_;
134    return if BarnOwl::Module::IRC->skip_msg($evt->type);
135    BarnOwl::admin_message("IRC",
136            BarnOwl::Style::boldify('IRC ' . $evt->type . ' message from '
137                . $self->alias) . "\n"
138            . strip_irc_formatting(join ' ', cdr($evt->args)));
139}
140
141sub on_motdstart {
142    my ($self, $evt) = @_;
143    $self->motd(join "\n", cdr($evt->args));
144}
145
146sub on_motd {
147    my ($self, $evt) = @_;
148    $self->motd(join "\n", $self->motd, cdr($evt->args));
149}
150
151sub on_endofmotd {
152    my ($self, $evt) = @_;
153    $self->motd(join "\n", $self->motd, cdr($evt->args));
154    BarnOwl::admin_message("IRC",
155            BarnOwl::Style::boldify('MOTD for ' . $self->alias) . "\n"
156            . strip_irc_formatting($self->motd));
157}
158
159sub on_join {
160    my ($self, $evt) = @_;
161    my $msg = $self->new_message($evt,
162        loginout   => 'login',
163        action     => 'join',
164        channel    => $evt->to,
165        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->to),
166        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->nick),
167        );
168    BarnOwl::queue_message($msg);
169    push @{$self->channels}, $evt->to;
170}
171
172sub on_part {
173    my ($self, $evt) = @_;
174    my $msg = $self->new_message($evt,
175        loginout   => 'logout',
176        action     => 'part',
177        channel    => $evt->to,
178        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->to),
179        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->nick),
180        );
181    BarnOwl::queue_message($msg);
182    $self->channels([ grep {$_ ne $evt->to} @{$self->channels}]);
183}
184
185sub on_quit {
186    my ($self, $evt) = @_;
187    my $msg = $self->new_message($evt,
188        loginout   => 'logout',
189        action     => 'quit',
190        from       => $evt->to,
191        reason     => [$evt->args]->[0],
192        replycmd   => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->nick),
193        replysendercmd => BarnOwl::quote('irc-msg', '-a', $self->alias, $evt->nick),
194        );
195    BarnOwl::queue_message($msg);
196}
197
198sub disconnect {
199    my $self = shift;
200    delete $BarnOwl::Module::IRC::ircnets{$self->alias};
201    for my $k (keys %BarnOwl::Module::IRC::channels) {
202        my @conns = grep {$_ ne $self} @{$BarnOwl::Module::IRC::channels{$k}};
203        if(@conns) {
204            $BarnOwl::Module::IRC::channels{$k} = \@conns;
205        } else {
206            delete $BarnOwl::Module::IRC::channels{$k};
207        }
208    }
209    BarnOwl::remove_io_dispatch($self->{FD});
210    $self->motd("");
211}
212
213sub on_disconnect {
214    my ($self, $evt) = @_;
215    $self->disconnect;
216    BarnOwl::admin_message('IRC',
217                           "[" . $self->alias . "] Disconnected from server");
218    if ($evt->format and $evt->format eq "error") {
219        $self->schedule_reconnect;
220    } else {
221        $self->channels([]);
222    }
223}
224
225sub on_nickinuse {
226    my ($self, $evt) = @_;
227    BarnOwl::admin_message("IRC",
228                           "[" . $self->alias . "] " .
229                           [$evt->args]->[1] . ": Nick already in use");
230    $self->disconnect unless $self->motd;
231}
232
233sub on_topic {
234    my ($self, $evt) = @_;
235    my @args = $evt->args;
236    if (scalar @args > 1) {
237        BarnOwl::admin_message("IRC",
238                "Topic for $args[1] on " . $self->alias . " is $args[2]");
239    } else {
240        BarnOwl::admin_message("IRC",
241                "Topic changed to $args[0]");
242    }
243}
244
245sub on_topicinfo {
246    my ($self, $evt) = @_;
247    my @args = $evt->args;
248    BarnOwl::admin_message("IRC",
249        "Topic for $args[1] set by $args[2] at " . localtime($args[3]));
250}
251
252# IRC gives us a bunch of namreply messages, followed by an endofnames.
253# We need to collect them from the namreply and wait for the endofnames message.
254# After this happens, the names_tmp variable is cleared.
255
256sub on_namreply {
257    my ($self, $evt) = @_;
258    return unless $self->names_tmp;
259    $self->names_tmp([@{$self->names_tmp}, split(' ', [$evt->args]->[3])]);
260}
261
262sub on_endofnames {
263    my ($self, $evt) = @_;
264    return unless $self->names_tmp;
265    my $names = BarnOwl::Style::boldify("Members of " . [$evt->args]->[1] . ":\n");
266    for my $name (@{$self->names_tmp}) {
267        $names .= "  $name\n";
268    }
269    BarnOwl::popless_ztext($names);
270    $self->names_tmp(0);
271}
272
273sub on_whois {
274    my ($self, $evt) = @_;
275    $self->whois_tmp(
276      $self->whois_tmp . "\n" . $evt->type . ":\n  " .
277      join("\n  ", cdr(cdr($evt->args))) . "\n"
278    );
279}
280
281sub on_endofwhois {
282    my ($self, $evt) = @_;
283    BarnOwl::popless_ztext(
284        BarnOwl::Style::boldify("/whois for " . [$evt->args]->[1] . ":\n") .
285        $self->whois_tmp
286    );
287    $self->whois_tmp('');
288}
289
290sub on_mode {
291    my ($self, $evt) = @_;
292    BarnOwl::admin_message("IRC",
293                           "[" . $self->alias . "] User " . ($evt->nick) . + " set mode " .
294                           join(" ", $evt->args) . "on " . $evt->to->[0]
295                          );
296}
297
298sub on_nosuchchannel {
299    my ($self, $evt) = @_;
300    BarnOwl::admin_message("IRC",
301                           "[" . $self->alias . "] " .
302                           "No such channel: " . [$evt->args]->[1])
303}
304
305sub on_event {
306    my ($self, $evt) = @_;
307    return on_whois(@_) if ($evt->type =~ /^whois/);
308    BarnOwl::admin_message("IRC",
309            "[" . $self->alias . "] Unhandled IRC event of type " . $evt->type . ":\n"
310            . strip_irc_formatting(join("\n", $evt->args)))
311        if BarnOwl::getvar('irc:spew') eq 'on';
312}
313
314sub schedule_reconnect {
315    my $self = shift;
316    my $interval = shift || 5;
317    delete $BarnOwl::Module::IRC::ircnets{$self->alias};
318    $BarnOwl::Module::IRC::reconnect{$self->alias} = $self;
319    my $weak = $self;
320    weaken($weak);
321    if (defined $self->{reconnect_timer}) {
322        $self->{reconnect_timer}->stop;
323    }
324    $self->{reconnect_timer} = 
325        BarnOwl::Timer->new( {
326            name  => 'IRC (' . $self->alias . ') reconnect_timer',
327            after => $interval,
328            cb    => sub {
329                $weak->reconnect( $interval ) if $weak;
330            },
331        } );
332}
333
334sub cancel_reconnect {
335    my $self = shift;
336    delete $BarnOwl::Module::IRC::reconnect{$self->alias};
337    if (defined $self->{reconnect_timer}) {
338        $self->{reconnect_timer}->stop;
339    }
340    delete $self->{reconnect_timer};
341}
342
343sub connected {
344    my $self = shift;
345    my $msg = shift;
346    BarnOwl::admin_message("IRC", $msg);
347    $self->cancel_reconnect;
348    $BarnOwl::Module::IRC::ircnets{$self->alias} = $self;
349    my $fd = $self->getSocket()->fileno();
350    BarnOwl::add_io_dispatch($fd, 'r', \&BarnOwl::Module::IRC::OwlProcess);
351    $self->{FD} = $fd;
352}
353
354sub reconnect {
355    my $self = shift;
356    my $backoff = shift;
357
358    $self->conn->connect;
359    if ($self->conn->connected) {
360        $self->connected("Reconnected to ".$self->alias);
361        my @channels = @{$self->channels};
362        $self->channels([]);
363        $self->conn->join($_) for @channels;
364        return;
365    }
366
367    $backoff *= 2;
368    $backoff = 60*5 if $backoff > 60*5;
369    $self->schedule_reconnect( $backoff );
370}
371
372################################################################################
373########################### Utilities/Helpers ##################################
374################################################################################
375
376sub strip_irc_formatting {
377    my $body = shift;
378    # Strip mIRC colors. If someone wants to write code to convert
379    # these to zephyr colors, be my guest.
380    $body =~ s/\cC\d+(?:,\d+)?//g;
381    $body =~ s/\cO//g;
382   
383    my @pieces = split /\cB/, $body;
384    my $out = '';
385    while(@pieces) {
386        $out .= shift @pieces;
387        $out .= BarnOwl::Style::boldify(shift @pieces) if @pieces;
388    }
389    return $out;
390}
391
392# Determines if the given message recipient is a username, as opposed to
393# a channel that starts with # or &.
394sub is_private {
395    return shift !~ /^[\#\&]/;
396}
397
398sub cdr {
399    shift;
400    return @_;
401}
402
4031;
Note: See TracBrowser for help on using the repository browser.