/[irc-logger]/trunk/bin/irc-logger.pl
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /trunk/bin/irc-logger.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 43 - (hide annotations)
Fri Feb 2 22:27:36 2007 UTC (13 years, 11 months ago) by dpavlin
Original Path: trunk/irc-logger.pl
File MIME type: text/plain
File size: 20471 byte(s)
count pings and ignore them, be very liberal about invitations, slightly better poll output

1 dpavlin 4 #!/usr/bin/perl -w
2     use strict;
3     $|++;
4    
5 dpavlin 5 =head1 NAME
6    
7     irc-logger.pl
8    
9     =head1 SYNOPSIS
10    
11     ./irc-logger.pl
12    
13 dpavlin 37 =head2 Options
14    
15     =over 4
16    
17     =item --import-dircproxy=filename
18    
19     Import log from C<dircproxy> to C<irc-logger> database
20    
21 dpavlin 5 =head1 DESCRIPTION
22    
23     log all conversation on irc channel
24    
25     =cut
26    
27 dpavlin 4 ## CONFIG
28    
29 dpavlin 33 my $HOSTNAME = `hostname`;
30    
31 dpavlin 29 my $NICK = 'irc-logger';
32 dpavlin 33 $NICK .= '-dev' if ($HOSTNAME =~ m/llin/);
33 dpavlin 4 my $CONNECT =
34     {Server => 'irc.freenode.net',
35     Nick => $NICK,
36 dpavlin 8 Ircname => "try /msg $NICK help",
37 dpavlin 4 };
38     my $CHANNEL = '#razmjenavjestina';
39 dpavlin 33 $CHANNEL = '#irc-logger' if ($HOSTNAME =~ m/llin/);
40 dpavlin 4 my $IRC_ALIAS = "log";
41    
42     my %FOLLOWS =
43     (
44     ACCESS => "/var/log/apache/access.log",
45     ERROR => "/var/log/apache/error.log",
46     );
47    
48 dpavlin 19 my $DSN = 'DBI:Pg:dbname=' . $NICK;
49 dpavlin 5
50 dpavlin 14 my $ENCODING = 'ISO-8859-2';
51 dpavlin 34 my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';
52 dpavlin 14
53 dpavlin 41 my $sleep_on_error = 5;
54    
55 dpavlin 4 ## END CONFIG
56    
57 dpavlin 5
58    
59 dpavlin 13 use POE qw(Component::IRC Wheel::FollowTail Component::Server::HTTP);
60     use HTTP::Status;
61 dpavlin 5 use DBI;
62 dpavlin 30 use Encode qw/from_to is_utf8/;
63 dpavlin 15 use Regexp::Common qw /URI/;
64 dpavlin 16 use CGI::Simple;
65 dpavlin 28 use HTML::TagCloud;
66 dpavlin 34 use POSIX qw/strftime/;
67 dpavlin 35 use HTML::CalendarMonthSimple;
68 dpavlin 37 use Getopt::Long;
69     use DateTime;
70 dpavlin 43 use Data::Dump qw/dump/;
71 dpavlin 5
72 dpavlin 37 my $import_dircproxy;
73     GetOptions(
74     'import-dircproxy:s' => \$import_dircproxy,
75     );
76    
77 dpavlin 5 my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
78    
79 dpavlin 19 eval {
80     $dbh->do(qq{ select count(*) from log });
81     };
82 dpavlin 5
83 dpavlin 19 if ($@) {
84     warn "creating database table in $DSN\n";
85     $dbh->do(<<'_SQL_SCHEMA_');
86    
87 dpavlin 5 create table log (
88     id serial,
89     time timestamp default now(),
90     channel text not null,
91 dpavlin 19 me boolean default false,
92 dpavlin 5 nick text not null,
93     message text not null,
94     primary key(id)
95     );
96    
97     create index log_time on log(time);
98     create index log_channel on log(channel);
99     create index log_nick on log(nick);
100    
101 dpavlin 19 _SQL_SCHEMA_
102     }
103 dpavlin 5
104     my $sth = $dbh->prepare(qq{
105     insert into log
106 dpavlin 37 (channel, me, nick, message, time)
107     values (?,?,?,?,?)
108 dpavlin 5 });
109    
110 dpavlin 28 my $tags;
111 dpavlin 31 my $tag_regex = '\b([\w-_]+)//';
112 dpavlin 28
113 dpavlin 11 =head2 get_from_log
114 dpavlin 5
115 dpavlin 11 my @messages = get_from_log(
116     limit => 42,
117     search => '%what to stuff in ilike%',
118 dpavlin 13 fmt => {
119     time => '{%s} ',
120     time_channel => '{%s %s} ',
121     nick => '%s: ',
122 dpavlin 20 me_nick => '***%s ',
123 dpavlin 13 message => '%s',
124     },
125 dpavlin 20 filter => {
126     message => sub {
127     # modify message content
128     return shift;
129     }
130 dpavlin 21 },
131     context => 5,
132 dpavlin 42 full_rows => 1,
133 dpavlin 11 );
134    
135 dpavlin 20 Order is important. Fields are first passed through C<filter> (if available) and
136     then throgh C<< sprintf($fmt->{message}, $message >> if available.
137    
138 dpavlin 21 C<context> defines number of messages around each search hit for display.
139    
140 dpavlin 42 C<full_rows> will return database rows for each result with C<date>, C<time>, C<channel>,
141     C<me>, C<nick> and C<message> keys.
142    
143 dpavlin 11 =cut
144    
145     sub get_from_log {
146     my $args = {@_};
147    
148 dpavlin 13 $args->{fmt} ||= {
149 dpavlin 26 date => '[%s] ',
150 dpavlin 13 time => '{%s} ',
151     time_channel => '{%s %s} ',
152     nick => '%s: ',
153 dpavlin 20 me_nick => '***%s ',
154 dpavlin 13 message => '%s',
155     };
156    
157 dpavlin 21 my $sql_message = qq{
158 dpavlin 11 select
159     time::date as date,
160     time::time as time,
161     channel,
162 dpavlin 20 me,
163 dpavlin 11 nick,
164     message
165     from log
166     };
167 dpavlin 21
168     my $sql_context = qq{
169     select
170     id
171     from log
172     };
173    
174     my $context = $1 if ($args->{search} && $args->{search} =~ s/\s*\+(\d+)\s*/ /);
175    
176     my $sql = $context ? $sql_context : $sql_message;
177    
178 dpavlin 25 $sql .= " where message ilike ? or nick ilike ? " if ($args->{search});
179 dpavlin 28 $sql .= " where id in (" . join(",", @{ $tags->{ $args->{tag} } }) . ") " if ($args->{tag} && $tags->{ $args->{tag} });
180 dpavlin 35 $sql .= " where date(time) = ? " if ($args->{date});
181 dpavlin 11 $sql .= " order by log.time desc";
182 dpavlin 35 $sql .= " limit " . $args->{limit} if ($args->{limit});
183 dpavlin 11
184     my $sth = $dbh->prepare( $sql );
185 dpavlin 21 if (my $search = $args->{search}) {
186     $search =~ s/^\s+//;
187     $search =~ s/\s+$//;
188 dpavlin 25 $sth->execute( ( '%' . $search . '%' ) x 2 );
189 dpavlin 21 warn "search for '$search' returned ", $sth->rows, " results ", $context || '', "\n";
190 dpavlin 28 } elsif (my $tag = $args->{tag}) {
191     $sth->execute();
192     warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";
193 dpavlin 35 } elsif (my $date = $args->{date}) {
194     $sth->execute($date);
195     warn "found ", $sth->rows, " messages for date $date ", $context || '', "\n";
196 dpavlin 11 } else {
197     $sth->execute();
198     }
199     my $last_row = {
200     date => '',
201     time => '',
202     channel => '',
203     nick => '',
204     };
205    
206     my @rows;
207    
208     while (my $row = $sth->fetchrow_hashref) {
209     unshift @rows, $row;
210     }
211    
212 dpavlin 42 # normalize nick names
213     map {
214     $_->{nick} =~ s/^_*(.*?)_*$/$1/
215     } @rows;
216    
217     return @rows if ($args->{full_rows});
218    
219 dpavlin 16 my @msgs = (
220     "Showing " . ($#rows + 1) . " messages..."
221     );
222 dpavlin 11
223 dpavlin 21 if ($context) {
224     my @ids = @rows;
225     @rows = ();
226    
227     my $last_to = 0;
228    
229     my $sth = $dbh->prepare( $sql_message . qq{ where id >= ? and id < ? } );
230     foreach my $row_id (sort { $a->{id} <=> $b->{id} } @ids) {
231     my $id = $row_id->{id} || die "can't find id in row";
232    
233     my ($from, $to) = ($id - $context, $id + $context);
234     $from = $last_to if ($from < $last_to);
235     $last_to = $to;
236     $sth->execute( $from, $to );
237    
238     #warn "## id: $id from: $from to: $to returned: ", $sth->rows, "\n";
239    
240     while (my $row = $sth->fetchrow_hashref) {
241     push @rows, $row;
242     }
243    
244     }
245     }
246    
247 dpavlin 35 # sprintf which can take coderef as first parametar
248     sub cr_sprintf {
249     my $fmt = shift || return;
250     if (ref($fmt) eq 'CODE') {
251     $fmt->(@_);
252     } else {
253     sprintf($fmt, @_);
254     }
255     }
256    
257 dpavlin 11 foreach my $row (@rows) {
258    
259     $row->{time} =~ s#\.\d+##;
260    
261     my $msg = '';
262    
263 dpavlin 35 $msg = cr_sprintf($args->{fmt}->{date}, $row->{date}) . ' ' if ($last_row->{date} ne $row->{date});
264 dpavlin 26 my $t = $row->{time};
265    
266 dpavlin 13 if ($last_row->{channel} ne $row->{channel}) {
267 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});
268 dpavlin 13 } else {
269 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{time}, $t);
270 dpavlin 13 }
271 dpavlin 11
272 dpavlin 12 my $append = 1;
273 dpavlin 11
274 dpavlin 22 my $nick = $row->{nick};
275 dpavlin 42 # if ($nick =~ s/^_*(.*?)_*$/$1/) {
276     # $row->{nick} = $nick;
277     # }
278 dpavlin 24
279 dpavlin 22 if ($last_row->{nick} ne $nick) {
280 dpavlin 20 # obfu way to find format for me_nick if needed or fallback to default
281     my $fmt = $row->{me} ? ( $args->{fmt}->{me_nick} || $args->{fmt}->{nick} ) : $args->{fmt}->{nick};
282     $fmt ||= '%s';
283    
284     $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');
285    
286 dpavlin 35 $msg .= cr_sprintf( $fmt, $nick );
287 dpavlin 12 $append = 0;
288     }
289    
290 dpavlin 20 $args->{fmt}->{message} ||= '%s';
291     if (ref($args->{filter}->{message}) eq 'CODE') {
292 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{message},
293 dpavlin 20 $args->{filter}->{message}->(
294 dpavlin 15 $row->{message}
295     )
296     );
297     } else {
298 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{message}, $row->{message});
299 dpavlin 15 }
300 dpavlin 11
301 dpavlin 12 if ($append && @msgs) {
302     $msgs[$#msgs] .= " " . $msg;
303     } else {
304     push @msgs, $msg;
305     }
306 dpavlin 11
307     $last_row = $row;
308     }
309    
310     return @msgs;
311     }
312    
313 dpavlin 37 # tags support
314 dpavlin 11
315 dpavlin 37 my $cloud = HTML::TagCloud->new;
316 dpavlin 4
317 dpavlin 37 =head2 add_tag
318 dpavlin 4
319 dpavlin 37 add_tag( id => 42, message => 'irc message' );
320    
321     =cut
322    
323     sub add_tag {
324     my $arg = {@_};
325    
326     return unless ($arg->{id} && $arg->{message});
327    
328     my $m = $arg->{message};
329     from_to('UTF-8', 'iso-8859-2', $m) if (is_utf8($m));
330    
331     while ($m =~ s#$tag_regex##s) {
332     my $tag = $1;
333     next if (! $tag || $tag =~ m/https?:/i);
334     push @{ $tags->{$tag} }, $arg->{id};
335     #warn "+tag $tag: $arg->{id}\n";
336     $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
337     }
338     }
339    
340     =head2 seed_tags
341    
342     Read all tags from database and create in-memory cache for tags
343    
344     =cut
345    
346     sub seed_tags {
347     my $sth = $dbh->prepare(qq{ select id,message from log where message like '%//%' });
348     $sth->execute;
349     while (my $row = $sth->fetchrow_hashref) {
350     add_tag( %$row );
351     }
352    
353     foreach my $tag (keys %$tags) {
354     $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
355     }
356     }
357    
358     seed_tags;
359    
360    
361 dpavlin 36 =head2 save_message
362    
363 dpavlin 37 save_message(
364     channel => '#foobar',
365     me => 0,
366     nick => 'dpavlin',
367     msg => 'test message',
368     time => '2006-06-25 18:57:18',
369     );
370 dpavlin 36
371 dpavlin 37 C<time> is optional, it will use C<< now() >> if it's not available.
372    
373     C<me> if not specified will be C<0> (not C</me> message)
374    
375 dpavlin 36 =cut
376    
377     sub save_message {
378 dpavlin 37 my $a = {@_};
379     $a->{me} ||= 0;
380 dpavlin 38 $a->{time} ||= strftime($TIMESTAMP,localtime());
381 dpavlin 37
382     print
383 dpavlin 38 $a->{time}, " ",
384 dpavlin 37 $a->{channel}, " ",
385     $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
386     " " . $a->{msg} . "\n";
387    
388     from_to($a->{msg}, 'UTF-8', $ENCODING);
389    
390     $sth->execute($a->{channel}, $a->{me}, $a->{nick}, $a->{msg}, $a->{time});
391 dpavlin 36 add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),
392 dpavlin 37 message => $a->{msg});
393 dpavlin 36 }
394    
395 dpavlin 37 if ($import_dircproxy) {
396     open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
397     warn "importing $import_dircproxy...\n";
398     my $tz_offset = 2 * 60 * 60; # TZ GMT+2
399     while(<$l>) {
400     chomp;
401     if (/^@(\d+)\s(\S+)\s(.+)$/) {
402     my ($time, $nick, $msg) = ($1,$2,$3);
403    
404     my $dt = DateTime->from_epoch( epoch => $time + $tz_offset );
405    
406     my $me = 0;
407     $me = 1 if ($nick =~ m/^\[\S+]/);
408     $nick =~ s/^[\[<]([^!]+).*$/$1/;
409    
410     $msg =~ s/^ACTION\s+// if ($me);
411    
412     save_message(
413     channel => $CHANNEL,
414     me => $me,
415     nick => $nick,
416     msg => $msg,
417     time => $dt->ymd . " " . $dt->hms,
418     ) if ($nick !~ m/^-/);
419    
420     } else {
421     warn "can't parse: $_\n";
422     }
423     }
424     close($l);
425     warn "import over\n";
426     exit;
427     }
428    
429    
430     #
431     # POE handing part
432     #
433    
434     my $SKIPPING = 0; # if skipping, how many we've done
435     my $SEND_QUEUE; # cache
436 dpavlin 43 my $ping; # ping stats
437 dpavlin 37
438     POE::Component::IRC->new($IRC_ALIAS);
439    
440 dpavlin 34 POE::Session->create( inline_states =>
441 dpavlin 4 {_start => sub {
442 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => register => 'all');
443     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
444 dpavlin 4 },
445 dpavlin 9 irc_255 => sub { # server is done blabbing
446 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => join => $CHANNEL);
447     $_[KERNEL]->post($IRC_ALIAS => join => '#logger');
448     $_[KERNEL]->yield("heartbeat"); # start heartbeat
449     # $_[KERNEL]->yield("my_add", $_) for keys %FOLLOWS;
450 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
451 dpavlin 4 },
452     irc_public => sub {
453 dpavlin 7 my $kernel = $_[KERNEL];
454     my $nick = (split /!/, $_[ARG0])[0];
455     my $channel = $_[ARG1]->[0];
456     my $msg = $_[ARG2];
457 dpavlin 4
458 dpavlin 37 save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
459 dpavlin 4 },
460 dpavlin 19 irc_ctcp_action => sub {
461     my $kernel = $_[KERNEL];
462     my $nick = (split /!/, $_[ARG0])[0];
463     my $channel = $_[ARG1]->[0];
464     my $msg = $_[ARG2];
465    
466 dpavlin 37 save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
467 dpavlin 19 },
468 dpavlin 43 irc_ping => sub {
469     warn "pong ", $_[ARG0], $/;
470     $ping->{$_[ARG0]++};
471     },
472     irc_invite => sub {
473     my $kernel = $_[KERNEL];
474     my $nick = (split /!/, $_[ARG0])[0];
475     my $channel = $_[ARG1];
476    
477    
478     warn "invited to $channel by $nick";
479    
480     $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, "how nice of you to invite me to $channel, I'll be right there..." );
481     $_[KERNEL]->post($IRC_ALIAS => join => $channel);
482    
483     },
484 dpavlin 7 irc_msg => sub {
485     my $kernel = $_[KERNEL];
486     my $nick = (split /!/, $_[ARG0])[0];
487     my $msg = $_[ARG2];
488 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
489 dpavlin 7
490 dpavlin 8 my $res = "unknown command '$msg', try /msg $NICK help!";
491 dpavlin 11 my @out;
492 dpavlin 7
493     print "<< $msg\n";
494    
495 dpavlin 8 if ($msg =~ m/^help/i) {
496 dpavlin 7
497 dpavlin 11 $res = "usage: /msg $NICK comand | commands: stat - user/message stat | last - show backtrace | grep foobar - find foobar";
498 dpavlin 8
499 dpavlin 10 } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
500    
501     print ">> /msg $1 $2\n";
502     $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
503     $res = '';
504    
505 dpavlin 8 } elsif ($msg =~ m/^stat.*?\s*(\d*)/i) {
506    
507 dpavlin 7 my $nr = $1 || 10;
508    
509     my $sth = $dbh->prepare(qq{
510 dpavlin 40 select
511     nick,
512     count(*) as count,
513     sum(length(message)) as len
514     from log
515     group by nick
516     order by len desc,count desc
517     limit $nr
518 dpavlin 7 });
519     $sth->execute();
520     $res = "Top $nr users: ";
521 dpavlin 8 my @users;
522 dpavlin 7 while (my $row = $sth->fetchrow_hashref) {
523 dpavlin 40 push @users,$row->{nick} . ': ' . $row->{count} . '/' . $row->{len} . '=' . sprintf("%.2f", $row->{len}/$row->{count});
524 dpavlin 7 }
525 dpavlin 8 $res .= join(" | ", @users);
526     } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
527    
528 dpavlin 39 foreach my $res (get_from_log( limit => ($1 || 100) )) {
529 dpavlin 11 print "last: $res\n";
530 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
531 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
532 dpavlin 8 }
533    
534 dpavlin 11 $res = '';
535 dpavlin 8
536 dpavlin 21 } elsif ($msg =~ m/^(search|grep)\s+(.*)\s*$/i) {
537 dpavlin 8
538 dpavlin 11 my $what = $2;
539 dpavlin 8
540 dpavlin 21 foreach my $res (get_from_log(
541     limit => 20,
542     search => $what,
543     )) {
544 dpavlin 11 print "search [$what]: $res\n";
545 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
546 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
547     }
548    
549     $res = '';
550 dpavlin 11
551 dpavlin 42 } elsif ($msg =~ m/^(?:count|poll)\s+(.*)(?:\s+(\d+))?\s*$/i) {
552    
553     my ($what,$limit) = ($1,$2);
554     $limit ||= 100;
555    
556     my $stat;
557    
558     foreach my $res (get_from_log(
559     limit => $limit,
560     search => $what,
561     full_rows => 1,
562     )) {
563     while ($res->{message} =~ s/\Q$what\E(\+|\-)//) {
564     $stat->{vote}->{$1}++;
565     $stat->{from}->{ $res->{nick} }++;
566     }
567     }
568    
569     my @nicks;
570 dpavlin 43 foreach my $nick (sort { $stat->{from}->{$a} <=> $stat->{from}->{$b} } keys %{ $stat->{from} }) {
571     push @nicks, $nick . ( $stat->{from}->{$nick} == 1 ? '' :
572     "(" . $stat->{from}->{$nick} . ")"
573     );
574 dpavlin 42 }
575    
576     $res =
577 dpavlin 43 "$what ++ " . ( $stat->{vote}->{'+'} || 0 ) .
578     " : " . ( $stat->{vote}->{'-'} || 0 ) . " --" .
579 dpavlin 42 " from " . ( join(", ", @nicks) || 'nobody' );
580    
581 dpavlin 43 $_[KERNEL]->post( $IRC_ALIAS => notice => $nick, $res );
582    
583     } elsif ($msg =~ m/^ping/) {
584     $res = "ping = " . dump( $ping );
585 dpavlin 7 }
586    
587 dpavlin 8 if ($res) {
588     print ">> [$nick] $res\n";
589 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
590 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
591     }
592 dpavlin 7
593     },
594 dpavlin 10 irc_477 => sub {
595     print "# irc_477: ",$_[ARG1], "\n";
596     $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
597     },
598 dpavlin 7 irc_505 => sub {
599 dpavlin 10 print "# irc_505: ",$_[ARG1], "\n";
600 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
601 dpavlin 10 # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
602     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
603 dpavlin 8 },
604     irc_registered => sub {
605 dpavlin 10 warn "## indetify $NICK\n";
606 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
607 dpavlin 10 },
608 dpavlin 41 irc_disconnected => sub {
609     warn "## disconnected, reconnecting again\n";
610     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
611     },
612     irc_socketerr => sub {
613     warn "## socket error... sleeping for $sleep_on_error seconds and retry";
614     sleep($sleep_on_error);
615     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
616     },
617 dpavlin 11 # irc_433 => sub {
618     # print "# irc_433: ",$_[ARG1], "\n";
619     # warn "## indetify $NICK\n";
620     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
621     # },
622 dpavlin 4 _child => sub {},
623     _default => sub {
624 dpavlin 34 printf "%s #%s %s %s\n",
625     strftime($TIMESTAMP,localtime()), $_[SESSION]->ID, $_[ARG0],
626     ref($_[ARG1]) eq "ARRAY" ? join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] }) :
627     $_[ARG1] ? $_[ARG1] :
628     "";
629 dpavlin 4 0; # false for signals
630     },
631     my_add => sub {
632     my $trailing = $_[ARG0];
633     my $session = $_[SESSION];
634     POE::Session->create
635     (inline_states =>
636     {_start => sub {
637     $_[HEAP]->{wheel} =
638     POE::Wheel::FollowTail->new
639     (
640     Filename => $FOLLOWS{$trailing},
641     InputEvent => 'got_line',
642     );
643     },
644     got_line => sub {
645     $_[KERNEL]->post($session => my_tailed =>
646     time, $trailing, $_[ARG0]);
647     },
648     },
649     );
650    
651     },
652     my_tailed => sub {
653     my ($time, $file, $line) = @_[ARG0..ARG2];
654     ## $time will be undef on a probe, or a time value if a real line
655    
656     ## PoCo::IRC has throttling built in, but no external visibility
657     ## so this is reaching "under the hood"
658     $SEND_QUEUE ||=
659     $_[KERNEL]->alias_resolve($IRC_ALIAS)->get_heap->{send_queue};
660    
661     ## handle "no need to keep skipping" transition
662     if ($SKIPPING and @$SEND_QUEUE < 1) {
663     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
664     "[discarded $SKIPPING messages]");
665     $SKIPPING = 0;
666     }
667    
668     ## handle potential message display
669     if ($time) {
670     if ($SKIPPING or @$SEND_QUEUE > 3) { # 3 msgs per 10 seconds
671     $SKIPPING++;
672     } else {
673     my @time = localtime $time;
674     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
675     sprintf "%02d:%02d:%02d: %s: %s",
676     ($time[2] + 11) % 12 + 1, $time[1], $time[0],
677     $file, $line);
678     }
679     }
680    
681     ## handle re-probe/flush if skipping
682     if ($SKIPPING) {
683     $_[KERNEL]->delay($_[STATE] => 0.5); # $time will be undef
684     }
685    
686     },
687     my_heartbeat => sub {
688     $_[KERNEL]->yield(my_tailed => time, "heartbeat", "beep");
689     $_[KERNEL]->delay($_[STATE] => 10);
690     }
691     },
692     );
693    
694 dpavlin 13 # http server
695    
696     my $httpd = POE::Component::Server::HTTP->new(
697 dpavlin 14 Port => $NICK =~ m/-dev/ ? 8001 : 8000,
698 dpavlin 13 ContentHandler => { '/' => \&root_handler },
699     Headers => { Server => 'irc-logger' },
700     );
701    
702 dpavlin 18 my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
703     my $escape_re = join '|' => keys %escape;
704    
705 dpavlin 13 my $style = <<'_END_OF_STYLE_';
706 dpavlin 16 p { margin: 0; padding: 0.1em; }
707 dpavlin 13 .time, .channel { color: #808080; font-size: 60%; }
708 dpavlin 28 .date { float: right; background: #e0e0e0; color: #404040; font-size: 120%; padding: 0.25em; border: 1px dashed #808080; }
709 dpavlin 20 .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }
710 dpavlin 13 .message { color: #000000; font-size: 100%; }
711 dpavlin 16 .search { float: right; }
712 dpavlin 20 .col-0 { background: #ffff66 }
713     .col-1 { background: #a0ffff }
714     .col-2 { background: #99ff99 }
715     .col-3 { background: #ff9999 }
716     .col-4 { background: #ff66ff }
717 dpavlin 31 a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }
718     a:hover.tag { border: 1px solid #eee }
719 dpavlin 35 hr { border: 1px dashed #ccc; height: 1px; clear: both; }
720 dpavlin 13 _END_OF_STYLE_
721    
722 dpavlin 20 my $max_color = 4;
723    
724     my %nick_enumerator;
725    
726 dpavlin 13 sub root_handler {
727     my ($request, $response) = @_;
728     $response->code(RC_OK);
729 dpavlin 14 $response->content_type("text/html; charset=$ENCODING");
730 dpavlin 16
731     my $q;
732    
733     if ( $request->method eq 'POST' ) {
734     $q = new CGI::Simple( $request->content );
735     } elsif ( $request->uri =~ /\?(.+)$/ ) {
736     $q = new CGI::Simple( $1 );
737     } else {
738     $q = new CGI::Simple;
739     }
740    
741     my $search = $q->param('search') || $q->param('grep') || '';
742    
743 dpavlin 35 my $html =
744 dpavlin 28 qq{<html><head><title>$NICK</title><style type="text/css">$style} .
745     $cloud->css .
746     qq{</style></head><body>} .
747     qq{
748 dpavlin 32 <form method="post" class="search" action="/">
749 dpavlin 16 <input type="text" name="search" value="$search" size="10">
750     <input type="submit" value="search">
751     </form>
752     } .
753 dpavlin 31 $cloud->html(500) .
754 dpavlin 35 qq{<p>};
755     if ($request->url =~ m#/history#) {
756     my $sth = $dbh->prepare(qq{
757     select date(time) as date,count(*) as nr
758     from log
759     group by date(time)
760     order by date(time) desc
761     });
762     $sth->execute();
763     my ($l_yyyy,$l_mm) = (0,0);
764     my $cal;
765     while (my $row = $sth->fetchrow_hashref) {
766     # this is probably PostgreSQL specific, expects ISO date
767     my ($yyyy,$mm,$dd) = split(/-/, $row->{date});
768     if ($yyyy != $l_yyyy || $mm != $l_mm) {
769     $html .= $cal->as_HTML() if ($cal);
770     $cal = new HTML::CalendarMonthSimple('month'=>$mm,'year'=>$yyyy);
771     $cal->border(2);
772     ($l_yyyy,$l_mm) = ($yyyy,$mm);
773     }
774     $cal->setcontent($dd, qq{
775     <a href="/?date=$row->{date}">$row->{nr}</a>
776     });
777     }
778     $html .= $cal->as_HTML() if ($cal);
779    
780     } else {
781     $html .= join("</p><p>",
782 dpavlin 13 get_from_log(
783 dpavlin 35 limit => $q->param('last') || $q->param('date') ? undef : 100,
784 dpavlin 28 search => $search || undef,
785 dpavlin 29 tag => $q->param('tag') || undef,
786 dpavlin 35 date => $q->param('date') || undef,
787 dpavlin 13 fmt => {
788 dpavlin 35 date => sub {
789     my $date = shift || return;
790 dpavlin 37 qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div>};
791 dpavlin 35 },
792 dpavlin 13 time => '<span class="time">%s</span> ',
793     time_channel => '<span class="channel">%s %s</span> ',
794 dpavlin 20 nick => '%s:&nbsp;',
795     me_nick => '***%s&nbsp;',
796 dpavlin 13 message => '<span class="message">%s</span>',
797     },
798 dpavlin 20 filter => {
799     message => sub {
800     my $m = shift || return;
801     $m =~ s/($escape_re)/$escape{$1}/gs;
802     $m =~ s#($RE{URI}{HTTP})#<a href="$1">$1</a>#gs;
803 dpavlin 31 $m =~ s#$tag_regex#<a href="?tag=$1" class="tag">$1</a>#g;
804 dpavlin 20 return $m;
805     },
806     nick => sub {
807     my $n = shift || return;
808     if (! $nick_enumerator{$n}) {
809     my $max = scalar keys %nick_enumerator;
810     $nick_enumerator{$n} = $max + 1;
811     }
812     return '<span class="nick col-' .
813     ( $nick_enumerator{$n} % $max_color ) .
814     '">' . $n . '</span>';
815     },
816 dpavlin 15 },
817 dpavlin 13 )
818 dpavlin 35 );
819     }
820    
821     $html .= qq{</p>
822     <hr/>
823     <p>See <a href="/history">history</a> of all messages.</p>
824     </body></html>};
825    
826     $response->content( $html );
827 dpavlin 13 return RC_OK;
828     }
829    
830 dpavlin 4 POE::Kernel->run;

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26