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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26