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

release-1.10release-1.8release-1.9
Last change on this file since 7659079 was fb6e8e3, checked in by Nelson Elhage <nelhage@mit.edu>, 13 years ago
Sort the output of :irc-names
  • Property mode set to 100644
File size: 12.4 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 cmp_user {
263    my ($lhs, $rhs) = @_;
264    my ($sigil_l) = ($lhs =~ m{^([+@]?)});
265    my ($sigil_r) = ($rhs =~ m{^([+@]?)});
266    my %rank = ('@' => 1, '+' => 2, '' => 3);
267    return ($rank{$sigil_l} <=> $rank{$sigil_r}) ||
268            $lhs cmp $rhs;
269}
270
271sub on_endofnames {
272    my ($self, $evt) = @_;
273    return unless $self->names_tmp;
274    my $names = BarnOwl::Style::boldify("Members of " . [$evt->args]->[1] . ":\n");
275    for my $name (sort {cmp_user($a, $b)} @{$self->names_tmp}) {
276        $names .= "  $name\n";
277    }
278    BarnOwl::popless_ztext($names);
279    $self->names_tmp(0);
280}
281
282sub on_whois {
283    my ($self, $evt) = @_;
284    $self->whois_tmp(
285      $self->whois_tmp . "\n" . $evt->type . ":\n  " .
286      join("\n  ", cdr(cdr($evt->args))) . "\n"
287    );
288}
289
290sub on_endofwhois {
291    my ($self, $evt) = @_;
292    BarnOwl::popless_ztext(
293        BarnOwl::Style::boldify("/whois for " . [$evt->args]->[1] . ":\n") .
294        $self->whois_tmp
295    );
296    $self->whois_tmp('');
297}
298
299sub on_mode {
300    my ($self, $evt) = @_;
301    BarnOwl::admin_message("IRC",
302                           "[" . $self->alias . "] User " . ($evt->nick) . + " set mode " .
303                           join(" ", $evt->args) . "on " . $evt->to->[0]
304                          );
305}
306
307sub on_nosuchchannel {
308    my ($self, $evt) = @_;
309    BarnOwl::admin_message("IRC",
310                           "[" . $self->alias . "] " .
311                           "No such channel: " . [$evt->args]->[1])
312}
313
314sub on_event {
315    my ($self, $evt) = @_;
316    return on_whois(@_) if ($evt->type =~ /^whois/);
317    BarnOwl::admin_message("IRC",
318            "[" . $self->alias . "] Unhandled IRC event of type " . $evt->type . ":\n"
319            . strip_irc_formatting(join("\n", $evt->args)))
320        if BarnOwl::getvar('irc:spew') eq 'on';
321}
322
323sub schedule_reconnect {
324    my $self = shift;
325    my $interval = shift || 5;
326    delete $BarnOwl::Module::IRC::ircnets{$self->alias};
327    $BarnOwl::Module::IRC::reconnect{$self->alias} = $self;
328    my $weak = $self;
329    weaken($weak);
330    if (defined $self->{reconnect_timer}) {
331        $self->{reconnect_timer}->stop;
332    }
333    $self->{reconnect_timer} = 
334        BarnOwl::Timer->new( {
335            name  => 'IRC (' . $self->alias . ') reconnect_timer',
336            after => $interval,
337            cb    => sub {
338                $weak->reconnect( $interval ) if $weak;
339            },
340        } );
341}
342
343sub cancel_reconnect {
344    my $self = shift;
345    delete $BarnOwl::Module::IRC::reconnect{$self->alias};
346    if (defined $self->{reconnect_timer}) {
347        $self->{reconnect_timer}->stop;
348    }
349    delete $self->{reconnect_timer};
350}
351
352sub connected {
353    my $self = shift;
354    my $msg = shift;
355    BarnOwl::admin_message("IRC", $msg);
356    $self->cancel_reconnect;
357    $BarnOwl::Module::IRC::ircnets{$self->alias} = $self;
358    my $fd = $self->getSocket()->fileno();
359    BarnOwl::add_io_dispatch($fd, 'r', \&BarnOwl::Module::IRC::OwlProcess);
360    $self->{FD} = $fd;
361}
362
363sub reconnect {
364    my $self = shift;
365    my $backoff = shift;
366
367    $self->conn->connect;
368    if ($self->conn->connected) {
369        $self->connected("Reconnected to ".$self->alias);
370        my @channels = @{$self->channels};
371        $self->channels([]);
372        $self->conn->join($_) for @channels;
373        return;
374    }
375
376    $backoff *= 2;
377    $backoff = 60*5 if $backoff > 60*5;
378    $self->schedule_reconnect( $backoff );
379}
380
381################################################################################
382########################### Utilities/Helpers ##################################
383################################################################################
384
385sub strip_irc_formatting {
386    my $body = shift;
387    # Strip mIRC colors. If someone wants to write code to convert
388    # these to zephyr colors, be my guest.
389    $body =~ s/\cC\d+(?:,\d+)?//g;
390    $body =~ s/\cO//g;
391   
392    my @pieces = split /\cB/, $body;
393    my $out = '';
394    while(@pieces) {
395        $out .= shift @pieces;
396        $out .= BarnOwl::Style::boldify(shift @pieces) if @pieces;
397    }
398    return $out;
399}
400
401# Determines if the given message recipient is a username, as opposed to
402# a channel that starts with # or &.
403sub is_private {
404    return shift !~ /^[\#\&]/;
405}
406
407sub cdr {
408    shift;
409    return @_;
410}
411
4121;
Note: See TracBrowser for help on using the repository browser.