/[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 35 by dpavlin, Sun Jun 25 00:10:13 2006 UTC revision 45 by dpavlin, Sat Feb 3 12:18:04 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    =item --log=irc-logger.log
22    
23    Name of log file
24    
25    =back
26    
27  =head1 DESCRIPTION  =head1 DESCRIPTION
28    
29  log all conversation on irc channel  log all conversation on irc channel
# Line 42  my $DSN = 'DBI:Pg:dbname=' . $NICK; Line 56  my $DSN = 'DBI:Pg:dbname=' . $NICK;
56  my $ENCODING = 'ISO-8859-2';  my $ENCODING = 'ISO-8859-2';
57  my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';  my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';
58    
59    my $sleep_on_error = 5;
60    
61  ## END CONFIG  ## END CONFIG
62    
63    
# Line 55  use CGI::Simple; Line 71  use CGI::Simple;
71  use HTML::TagCloud;  use HTML::TagCloud;
72  use POSIX qw/strftime/;  use POSIX qw/strftime/;
73  use HTML::CalendarMonthSimple;  use HTML::CalendarMonthSimple;
74    use Getopt::Long;
75    use DateTime;
76    use Data::Dump qw/dump/;
77    
78    my $import_dircproxy;
79    my $log_path;
80    GetOptions(
81            'import-dircproxy:s' => \$import_dircproxy,
82            'log:s' => \$log_path,
83    );
84    
85    open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";
86    
87    sub _log {
88            print strftime($TIMESTAMP,localtime()), ' ', join(" ",@_), $/;
89    }
90    
91  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
92    
# Line 85  _SQL_SCHEMA_ Line 117  _SQL_SCHEMA_
117    
118  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
119  insert into log  insert into log
120          (channel, me, nick, message)          (channel, me, nick, message, time)
121  values (?,?,?,?)  values (?,?,?,?,?)
122  });  });
123    
124  my $tags;  my $tags;
# Line 111  my $tag_regex = '\b([\w-_]+)//'; Line 143  my $tag_regex = '\b([\w-_]+)//';
143                  }                  }
144          },          },
145          context => 5,          context => 5,
146            full_rows => 1,
147   );   );
148    
149  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 151  then throgh C<< sprintf($fmt->{message},
151    
152  C<context> defines number of messages around each search hit for display.  C<context> defines number of messages around each search hit for display.
153    
154    C<full_rows> will return database rows for each result with C<date>, C<time>, C<channel>,
155    C<me>, C<nick> and C<message> keys.
156    
157  =cut  =cut
158    
159  sub get_from_log {  sub get_from_log {
# Line 164  sub get_from_log { Line 200  sub get_from_log {
200                  $search =~ s/^\s+//;                  $search =~ s/^\s+//;
201                  $search =~ s/\s+$//;                  $search =~ s/\s+$//;
202                  $sth->execute( ( '%' . $search . '%' ) x 2 );                  $sth->execute( ( '%' . $search . '%' ) x 2 );
203                  warn "search for '$search' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "search for '$search' returned ", $sth->rows, " results ", $context || '';
204          } elsif (my $tag = $args->{tag}) {          } elsif (my $tag = $args->{tag}) {
205                  $sth->execute();                  $sth->execute();
206                  warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "tag '$tag' returned ", $sth->rows, " results ", $context || '';
207          } elsif (my $date = $args->{date}) {          } elsif (my $date = $args->{date}) {
208                  $sth->execute($date);                  $sth->execute($date);
209                  warn "found ", $sth->rows, " messages for date $date ", $context || '', "\n";                  _log "found ", $sth->rows, " messages for date $date ", $context || '';
210          } else {          } else {
211                  $sth->execute();                  $sth->execute();
212          }          }
# Line 187  sub get_from_log { Line 223  sub get_from_log {
223                  unshift @rows, $row;                  unshift @rows, $row;
224          }          }
225    
226            # normalize nick names
227            map {
228                    $_->{nick} =~ s/^_*(.*?)_*$/$1/
229            } @rows;
230    
231            return @rows if ($args->{full_rows});
232    
233          my @msgs = (          my @msgs = (
234                  "Showing " . ($#rows + 1) . " messages..."                  "Showing " . ($#rows + 1) . " messages..."
235          );          );
# Line 243  sub get_from_log { Line 286  sub get_from_log {
286                  my $append = 1;                  my $append = 1;
287    
288                  my $nick = $row->{nick};                  my $nick = $row->{nick};
289                  if ($nick =~ s/^_*(.*?)_*$/$1/) {  #               if ($nick =~ s/^_*(.*?)_*$/$1/) {
290                          $row->{nick} = $nick;  #                       $row->{nick} = $nick;
291                  }  #               }
292    
293                  if ($last_row->{nick} ne $nick) {                  if ($last_row->{nick} ne $nick) {
294                          # 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 324  sub get_from_log {
324          return @msgs;          return @msgs;
325  }  }
326    
327    # tags support
328    
329    my $cloud = HTML::TagCloud->new;
330    
331    =head2 add_tag
332    
333     add_tag( id => 42, message => 'irc message' );
334    
335    =cut
336    
337    sub add_tag {
338            my $arg = {@_};
339    
340            return unless ($arg->{id} && $arg->{message});
341    
342            my $m = $arg->{message};
343            from_to('UTF-8', 'iso-8859-2', $m) if (is_utf8($m));
344    
345            while ($m =~ s#$tag_regex##s) {
346                    my $tag = $1;
347                    next if (! $tag || $tag =~ m/https?:/i);
348                    push @{ $tags->{$tag} }, $arg->{id};
349                    #warn "+tag $tag: $arg->{id}\n";
350                    $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
351            }
352    }
353    
354    =head2 seed_tags
355    
356    Read all tags from database and create in-memory cache for tags
357    
358    =cut
359    
360    sub seed_tags {
361            my $sth = $dbh->prepare(qq{ select id,message from log where message like '%//%' });
362            $sth->execute;
363            while (my $row = $sth->fetchrow_hashref) {
364                    add_tag( %$row );
365            }
366    
367            foreach my $tag (keys %$tags) {
368                    $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
369            }
370    }
371    
372    seed_tags;
373    
374    
375    =head2 save_message
376    
377      save_message(
378            channel => '#foobar',
379            me => 0,
380            nick => 'dpavlin',
381            msg => 'test message',
382            time => '2006-06-25 18:57:18',
383      );
384    
385    C<time> is optional, it will use C<< now() >> if it's not available.
386    
387    C<me> if not specified will be C<0> (not C</me> message)
388    
389    =cut
390    
391    sub save_message {
392            my $a = {@_};
393            $a->{me} ||= 0;
394            $a->{time} ||= strftime($TIMESTAMP,localtime());
395    
396            _log
397                    $a->{channel}, " ",
398                    $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
399                    " " . $a->{msg};
400    
401            from_to($a->{msg}, 'UTF-8', $ENCODING);
402    
403            $sth->execute($a->{channel}, $a->{me}, $a->{nick}, $a->{msg}, $a->{time});
404            add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),
405                    message => $a->{msg});
406    }
407    
408    if ($import_dircproxy) {
409            open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
410            warn "importing $import_dircproxy...\n";
411            my $tz_offset = 2 * 60 * 60;    # TZ GMT+2
412            while(<$l>) {
413                    chomp;
414                    if (/^@(\d+)\s(\S+)\s(.+)$/) {
415                            my ($time, $nick, $msg) = ($1,$2,$3);
416    
417                            my $dt = DateTime->from_epoch( epoch => $time + $tz_offset );
418    
419                            my $me = 0;
420                            $me = 1 if ($nick =~ m/^\[\S+]/);
421                            $nick =~ s/^[\[<]([^!]+).*$/$1/;
422    
423                            $msg =~ s/^ACTION\s+// if ($me);
424    
425                            save_message(
426                                    channel => $CHANNEL,
427                                    me => $me,
428                                    nick => $nick,
429                                    msg => $msg,
430                                    time => $dt->ymd . " " . $dt->hms,
431                            ) if ($nick !~ m/^-/);
432    
433                    } else {
434                            _log "can't parse: $_";
435                    }
436            }
437            close($l);
438            warn "import over\n";
439            exit;
440    }
441    
442    
443    #
444    # POE handing part
445    #
446    
447  my $SKIPPING = 0;               # if skipping, how many we've done  my $SKIPPING = 0;               # if skipping, how many we've done
448  my $SEND_QUEUE;                 # cache  my $SEND_QUEUE;                 # cache
449    my $ping;                                               # ping stats
450    
451  POE::Component::IRC->new($IRC_ALIAS);  POE::Component::IRC->new($IRC_ALIAS);
452    
# Line 305  POE::Session->create( inline_states => Line 468  POE::Session->create( inline_states =>
468                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
469                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
470    
471                  from_to($msg, 'UTF-8', $ENCODING);                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
   
                 print "$channel: <$nick> $msg\n";  
                 $sth->execute($channel, 0, $nick, $msg);  
                 add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),  
                         message => $msg);  
472      },      },
473      irc_ctcp_action => sub {      irc_ctcp_action => sub {
474                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 318  POE::Session->create( inline_states => Line 476  POE::Session->create( inline_states =>
476                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
477                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
478    
479                  from_to($msg, 'UTF-8', $ENCODING);                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
   
                 print "$channel ***$nick $msg\n";  
                 $sth->execute($channel, 1, $nick, $msg);  
                 add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),  
                         message => $msg);  
480      },      },
481            irc_ping => sub {
482                    warn "pong ", $_[ARG0], $/;
483                    $ping->{$_[ARG0]++};
484            },
485            irc_invite => sub {
486                    my $kernel = $_[KERNEL];
487                    my $nick = (split /!/, $_[ARG0])[0];
488                    my $channel = $_[ARG1];
489                    
490    
491                    warn "invited to $channel by $nick";
492    
493                    $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, "how nice of you to invite me to $channel, I'll be right there..." );
494                    $_[KERNEL]->post($IRC_ALIAS => join => $channel);
495    
496            },
497          irc_msg => sub {          irc_msg => sub {
498                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
499                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
# Line 334  POE::Session->create( inline_states => Line 503  POE::Session->create( inline_states =>
503                  my $res = "unknown command '$msg', try /msg $NICK help!";                  my $res = "unknown command '$msg', try /msg $NICK help!";
504                  my @out;                  my @out;
505    
506                  print "<< $msg\n";                  _log "<< $msg";
507    
508                  if ($msg =~ m/^help/i) {                  if ($msg =~ m/^help/i) {
509    
# Line 342  POE::Session->create( inline_states => Line 511  POE::Session->create( inline_states =>
511    
512                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
513    
514                          print ">> /msg $1 $2\n";                          _log ">> /msg $1 $2";
515                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
516                          $res = '';                          $res = '';
517    
# Line 351  POE::Session->create( inline_states => Line 520  POE::Session->create( inline_states =>
520                          my $nr = $1 || 10;                          my $nr = $1 || 10;
521    
522                          my $sth = $dbh->prepare(qq{                          my $sth = $dbh->prepare(qq{
523                                  select nick,count(*) from log group by nick order by count desc limit $nr                                  select
524                                            nick,
525                                            count(*) as count,
526                                            sum(length(message)) as len
527                                    from log
528                                    group by nick
529                                    order by len desc,count desc
530                                    limit $nr
531                          });                          });
532                          $sth->execute();                          $sth->execute();
533                          $res = "Top $nr users: ";                          $res = "Top $nr users: ";
534                          my @users;                          my @users;
535                          while (my $row = $sth->fetchrow_hashref) {                          while (my $row = $sth->fetchrow_hashref) {
536                                  push @users,$row->{nick} . ': ' . $row->{count};                                  push @users,$row->{nick} . ': ' . $row->{count} . '/' . $row->{len} . '=' . sprintf("%.2f", $row->{len}/$row->{count});
537                          }                          }
538                          $res .= join(" | ", @users);                          $res .= join(" | ", @users);
539                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
540    
541                          foreach my $res (get_from_log( limit => $1 )) {                          foreach my $res (get_from_log( limit => ($1 || 100) )) {
542                                  print "last: $res\n";                                  _log "last: $res";
543                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
544                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
545                          }                          }
# Line 378  POE::Session->create( inline_states => Line 554  POE::Session->create( inline_states =>
554                                          limit => 20,                                          limit => 20,
555                                          search => $what,                                          search => $what,
556                                  )) {                                  )) {
557                                  print "search [$what]: $res\n";                                  _log "search [$what]: $res";
558                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
559                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
560                          }                          }
561    
562                          $res = '';                          $res = '';
563    
564                    } elsif ($msg =~ m/^(?:count|poll)\s+(.*)(?:\s+(\d+))?\s*$/i) {
565    
566                            my ($what,$limit) = ($1,$2);
567                            $limit ||= 100;
568    
569                            my $stat;
570    
571                            foreach my $res (get_from_log(
572                                            limit => $limit,
573                                            search => $what,
574                                            full_rows => 1,
575                                    )) {
576                                    while ($res->{message} =~ s/\Q$what\E(\+|\-)//) {
577                                            $stat->{vote}->{$1}++;
578                                            $stat->{from}->{ $res->{nick} }++;
579                                    }
580                            }
581    
582                            my @nicks;
583                            foreach my $nick (sort { $stat->{from}->{$a} <=> $stat->{from}->{$b} } keys %{ $stat->{from} }) {
584                                    push @nicks, $nick . ( $stat->{from}->{$nick} == 1 ? '' :
585                                            "(" . $stat->{from}->{$nick} . ")"
586                                    );
587                            }
588    
589                            $res =
590                                    "$what ++ " . ( $stat->{vote}->{'+'} || 0 ) .
591                                    " : " . ( $stat->{vote}->{'-'} || 0 ) . " --" .
592                                    " from " . ( join(", ", @nicks) || 'nobody' );
593    
594                            $_[KERNEL]->post( $IRC_ALIAS => notice => $nick, $res );
595    
596                    } elsif ($msg =~ m/^ping/) {
597                            $res = "ping = " . dump( $ping );
598                  }                  }
599    
600                  if ($res) {                  if ($res) {
601                          print ">> [$nick] $res\n";                          _log ">> [$nick] $res";
602                          from_to($res, $ENCODING, 'UTF-8');                          from_to($res, $ENCODING, 'UTF-8');
603                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
604                  }                  }
605    
606          },          },
607          irc_477 => sub {          irc_477 => sub {
608                  print "# irc_477: ",$_[ARG1], "\n";                  _log "# irc_477: ",$_[ARG1];
609                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
610          },          },
611          irc_505 => sub {          irc_505 => sub {
612                  print "# irc_505: ",$_[ARG1], "\n";                  _log "# irc_505: ",$_[ARG1];
613                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
614  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
615  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
616          },          },
617          irc_registered => sub {          irc_registered => sub {
618                  warn "## indetify $NICK\n";                  _log "## registrated $NICK";
619                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
620          },          },
621            irc_disconnected => sub {
622                    _log "## disconnected, reconnecting again";
623                    $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
624            },
625            irc_socketerr => sub {
626                    _log "## socket error... sleeping for $sleep_on_error seconds and retry";
627                    sleep($sleep_on_error);
628                    $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
629            },
630  #       irc_433 => sub {  #       irc_433 => sub {
631  #               print "# irc_433: ",$_[ARG1], "\n";  #               print "# irc_433: ",$_[ARG1], "\n";
632  #               warn "## indetify $NICK\n";  #               warn "## indetify $NICK\n";
# Line 415  POE::Session->create( inline_states => Line 634  POE::Session->create( inline_states =>
634  #       },  #       },
635      _child => sub {},      _child => sub {},
636      _default => sub {      _default => sub {
637                  printf "%s #%s %s %s\n",                  _log sprintf "sID:%s %s %s",
638                          strftime($TIMESTAMP,localtime()), $_[SESSION]->ID, $_[ARG0],                          $_[SESSION]->ID, $_[ARG0],
639                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :
640                          $_[ARG1]                                        ?       $_[ARG1]                                        :                          $_[ARG1]                                        ?       $_[ARG1]                                        :
641                          "";                          "";
# Line 485  POE::Session->create( inline_states => Line 704  POE::Session->create( inline_states =>
704     },     },
705    );    );
706    
 # 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;  
   
707  # http server  # http server
708    
709  my $httpd = POE::Component::Server::HTTP->new(  my $httpd = POE::Component::Server::HTTP->new(
# Line 628  sub root_handler { Line 800  sub root_handler {
800                                  fmt => {                                  fmt => {
801                                          date => sub {                                          date => sub {
802                                                  my $date = shift || return;                                                  my $date = shift || return;
803                                                  qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div> '};                                                  qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div>};
804                                          },                                          },
805                                          time => '<span class="time">%s</span> ',                                          time => '<span class="time">%s</span> ',
806                                          time_channel => '<span class="channel">%s %s</span> ',                                          time_channel => '<span class="channel">%s %s</span> ',

Legend:
Removed from v.35  
changed lines
  Added in v.45

  ViewVC Help
Powered by ViewVC 1.1.26