/[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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 36 by dpavlin, Sun Jun 25 16:37:39 2006 UTC revision 43 by dpavlin, Fri Feb 2 22:27:36 2007 UTC
# Line 10  irc-logger.pl Line 10  irc-logger.pl
10    
11  ./irc-logger.pl  ./irc-logger.pl
12    
13    =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  =head1 DESCRIPTION  =head1 DESCRIPTION
22    
23  log all conversation on irc channel  log all conversation on irc channel
# Line 42  my $DSN = 'DBI:Pg:dbname=' . $NICK; Line 50  my $DSN = 'DBI:Pg:dbname=' . $NICK;
50  my $ENCODING = 'ISO-8859-2';  my $ENCODING = 'ISO-8859-2';
51  my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';  my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';
52    
53    my $sleep_on_error = 5;
54    
55  ## END CONFIG  ## END CONFIG
56    
57    
# Line 55  use CGI::Simple; Line 65  use CGI::Simple;
65  use HTML::TagCloud;  use HTML::TagCloud;
66  use POSIX qw/strftime/;  use POSIX qw/strftime/;
67  use HTML::CalendarMonthSimple;  use HTML::CalendarMonthSimple;
68    use Getopt::Long;
69    use DateTime;
70    use Data::Dump qw/dump/;
71    
72    my $import_dircproxy;
73    GetOptions(
74            'import-dircproxy:s' => \$import_dircproxy,
75    );
76    
77  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
78    
# Line 85  _SQL_SCHEMA_ Line 103  _SQL_SCHEMA_
103    
104  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
105  insert into log  insert into log
106          (channel, me, nick, message)          (channel, me, nick, message, time)
107  values (?,?,?,?)  values (?,?,?,?,?)
108  });  });
109    
110  my $tags;  my $tags;
# Line 111  my $tag_regex = '\b([\w-_]+)//'; Line 129  my $tag_regex = '\b([\w-_]+)//';
129                  }                  }
130          },          },
131          context => 5,          context => 5,
132            full_rows => 1,
133   );   );
134    
135  Order is important. Fields are first passed through C<filter> (if available) and  Order is important. Fields are first passed through C<filter> (if available) and
# Line 118  then throgh C<< sprintf($fmt->{message}, Line 137  then throgh C<< sprintf($fmt->{message},
137    
138  C<context> defines number of messages around each search hit for display.  C<context> defines number of messages around each search hit for display.
139    
140    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  =cut  =cut
144    
145  sub get_from_log {  sub get_from_log {
# Line 187  sub get_from_log { Line 209  sub get_from_log {
209                  unshift @rows, $row;                  unshift @rows, $row;
210          }          }
211    
212            # normalize nick names
213            map {
214                    $_->{nick} =~ s/^_*(.*?)_*$/$1/
215            } @rows;
216    
217            return @rows if ($args->{full_rows});
218    
219          my @msgs = (          my @msgs = (
220                  "Showing " . ($#rows + 1) . " messages..."                  "Showing " . ($#rows + 1) . " messages..."
221          );          );
# Line 243  sub get_from_log { Line 272  sub get_from_log {
272                  my $append = 1;                  my $append = 1;
273    
274                  my $nick = $row->{nick};                  my $nick = $row->{nick};
275                  if ($nick =~ s/^_*(.*?)_*$/$1/) {  #               if ($nick =~ s/^_*(.*?)_*$/$1/) {
276                          $row->{nick} = $nick;  #                       $row->{nick} = $nick;
277                  }  #               }
278    
279                  if ($last_row->{nick} ne $nick) {                  if ($last_row->{nick} ne $nick) {
280                          # obfu way to find format for me_nick if needed or fallback to default                          # obfu way to find format for me_nick if needed or fallback to default
# Line 281  sub get_from_log { Line 310  sub get_from_log {
310          return @msgs;          return @msgs;
311  }  }
312    
313    # tags support
314    
315  my $SKIPPING = 0;               # if skipping, how many we've done  my $cloud = HTML::TagCloud->new;
316  my $SEND_QUEUE;                 # cache  
317    =head2 add_tag
318    
319     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    
 POE::Component::IRC->new($IRC_ALIAS);  
360    
361  =head2 save_message  =head2 save_message
362    
363    save_message($channel,$me,$nick,$msg);    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    
371    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  =cut  =cut
376    
377  sub save_message {  sub save_message {
378          my ($channel,$me,$nick,$msg) = @_;          my $a = {@_};
379          $me ||= 0;          $a->{me} ||= 0;
380          $sth->execute($channel, $me, $nick, $msg);          $a->{time} ||= strftime($TIMESTAMP,localtime());
381    
382            print
383                    $a->{time}, " ",
384                    $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          add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),          add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),
392                  message => $msg);                  message => $a->{msg});
393  }  }
394    
395    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    my $ping;                                               # ping stats
437    
438    POE::Component::IRC->new($IRC_ALIAS);
439    
440  POE::Session->create( inline_states =>  POE::Session->create( inline_states =>
441     {_start => sub {           {_start => sub {      
442                  $_[KERNEL]->post($IRC_ALIAS => register => 'all');                  $_[KERNEL]->post($IRC_ALIAS => register => 'all');
# Line 319  POE::Session->create( inline_states => Line 455  POE::Session->create( inline_states =>
455                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
456                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
457    
458                  from_to($msg, 'UTF-8', $ENCODING);                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
   
                 print "$channel: <$nick> $msg\n";  
                 save_message($channel, 0, $nick, $msg);  
459      },      },
460      irc_ctcp_action => sub {      irc_ctcp_action => sub {
461                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 330  POE::Session->create( inline_states => Line 463  POE::Session->create( inline_states =>
463                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
464                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
465    
466                  from_to($msg, 'UTF-8', $ENCODING);                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
   
                 print "$channel ***$nick $msg\n";  
                 save_message($channel, 1, $nick, $msg);  
467      },      },
468            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          irc_msg => sub {          irc_msg => sub {
485                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
486                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
# Line 361  POE::Session->create( inline_states => Line 507  POE::Session->create( inline_states =>
507                          my $nr = $1 || 10;                          my $nr = $1 || 10;
508    
509                          my $sth = $dbh->prepare(qq{                          my $sth = $dbh->prepare(qq{
510                                  select nick,count(*) from log group by nick order by count desc limit $nr                                  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                          });                          });
519                          $sth->execute();                          $sth->execute();
520                          $res = "Top $nr users: ";                          $res = "Top $nr users: ";
521                          my @users;                          my @users;
522                          while (my $row = $sth->fetchrow_hashref) {                          while (my $row = $sth->fetchrow_hashref) {
523                                  push @users,$row->{nick} . ': ' . $row->{count};                                  push @users,$row->{nick} . ': ' . $row->{count} . '/' . $row->{len} . '=' . sprintf("%.2f", $row->{len}/$row->{count});
524                          }                          }
525                          $res .= join(" | ", @users);                          $res .= join(" | ", @users);
526                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
527    
528                          foreach my $res (get_from_log( limit => $1 )) {                          foreach my $res (get_from_log( limit => ($1 || 100) )) {
529                                  print "last: $res\n";                                  print "last: $res\n";
530                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
531                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
# Line 395  POE::Session->create( inline_states => Line 548  POE::Session->create( inline_states =>
548    
549                          $res = '';                          $res = '';
550    
551                    } 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                            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                            }
575    
576                            $res =
577                                    "$what ++ " . ( $stat->{vote}->{'+'} || 0 ) .
578                                    " : " . ( $stat->{vote}->{'-'} || 0 ) . " --" .
579                                    " from " . ( join(", ", @nicks) || 'nobody' );
580    
581                            $_[KERNEL]->post( $IRC_ALIAS => notice => $nick, $res );
582    
583                    } elsif ($msg =~ m/^ping/) {
584                            $res = "ping = " . dump( $ping );
585                  }                  }
586    
587                  if ($res) {                  if ($res) {
# Line 418  POE::Session->create( inline_states => Line 605  POE::Session->create( inline_states =>
605                  warn "## indetify $NICK\n";                  warn "## indetify $NICK\n";
606                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
607          },          },
608            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  #       irc_433 => sub {  #       irc_433 => sub {
618  #               print "# irc_433: ",$_[ARG1], "\n";  #               print "# irc_433: ",$_[ARG1], "\n";
619  #               warn "## indetify $NICK\n";  #               warn "## indetify $NICK\n";
# Line 495  POE::Session->create( inline_states => Line 691  POE::Session->create( inline_states =>
691     },     },
692    );    );
693    
 # tags support  
   
 my $cloud = HTML::TagCloud->new;  
   
 =head2 add_tag  
   
  add_tag( id => 42, message => 'irc message' );  
   
 =cut  
   
 sub add_tag {  
         my $arg = {@_};  
   
         return unless ($arg->{id} && $arg->{message});  
   
         my $m = $arg->{message};  
         from_to('UTF-8', 'iso-8859-2', $m) if (is_utf8($m));  
   
         while ($m =~ s#$tag_regex##s) {  
                 my $tag = $1;  
                 next if (! $tag || $tag =~ m/https?:/i);  
                 push @{ $tags->{$tag} }, $arg->{id};  
                 #warn "+tag $tag: $arg->{id}\n";  
                 $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);  
         }  
 }  
   
 =head2 seed_tags  
   
 Read all tags from database and create in-memory cache for tags  
   
 =cut  
   
 sub seed_tags {  
         my $sth = $dbh->prepare(qq{ select id,message from log where message like '%//%' });  
         $sth->execute;  
         while (my $row = $sth->fetchrow_hashref) {  
                 add_tag( %$row );  
         }  
   
         foreach my $tag (keys %$tags) {  
                 $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);  
         }  
 }  
   
 seed_tags;  
   
694  # http server  # http server
695    
696  my $httpd = POE::Component::Server::HTTP->new(  my $httpd = POE::Component::Server::HTTP->new(
# Line 638  sub root_handler { Line 787  sub root_handler {
787                                  fmt => {                                  fmt => {
788                                          date => sub {                                          date => sub {
789                                                  my $date = shift || return;                                                  my $date = shift || return;
790                                                  qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div> '};                                                  qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div>};
791                                          },                                          },
792                                          time => '<span class="time">%s</span> ',                                          time => '<span class="time">%s</span> ',
793                                          time_channel => '<span class="channel">%s %s</span> ',                                          time_channel => '<span class="channel">%s %s</span> ',

Legend:
Removed from v.36  
changed lines
  Added in v.43

  ViewVC Help
Powered by ViewVC 1.1.26