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

trunk/irc-logger.pl revision 37 by dpavlin, Sun Jun 25 17:40:59 2006 UTC trunk/bin/irc-logger.pl revision 53 by dpavlin, Sun Mar 18 17:00:16 2007 UTC
# Line 18  irc-logger.pl Line 18  irc-logger.pl
18    
19  Import log from C<dircproxy> to C<irc-logger> database  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 50  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 65  use POSIX qw/strftime/; Line 73  use POSIX qw/strftime/;
73  use HTML::CalendarMonthSimple;  use HTML::CalendarMonthSimple;
74  use Getopt::Long;  use Getopt::Long;
75  use DateTime;  use DateTime;
76    use Data::Dump qw/dump/;
77    use Net::Twitter;
78    
79  my $import_dircproxy;  my $import_dircproxy;
80    my $log_path;
81  GetOptions(  GetOptions(
82          'import-dircproxy:s' => \$import_dircproxy,          'import-dircproxy:s' => \$import_dircproxy,
83            'log:s' => \$log_path,
84  );  );
85    
86  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";
87    
88  eval {  sub _log {
89          $dbh->do(qq{ select count(*) from log });          print strftime($TIMESTAMP,localtime()), ' ', join(" ",@_), $/;
90  };  }
91    
92  if ($@) {  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
         warn "creating database table in $DSN\n";  
         $dbh->do(<<'_SQL_SCHEMA_');  
93    
94    my $sql_schema = {
95            log => '
96  create table log (  create table log (
97          id serial,          id serial,
98          time timestamp default now(),          time timestamp default now(),
# Line 94  create table log ( Line 106  create table log (
106  create index log_time on log(time);  create index log_time on log(time);
107  create index log_channel on log(channel);  create index log_channel on log(channel);
108  create index log_nick on log(nick);  create index log_nick on log(nick);
109            ',
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    
122    foreach my $table ( keys %$sql_schema ) {
123    
124            eval {
125                    $dbh->do(qq{ select count(*) from $table });
126            };
127    
128  _SQL_SCHEMA_          if ($@) {
129                    warn "creating database table $table in $DSN\n";
130                    $dbh->do( $sql_schema->{ $table } );
131            }
132  }  }
133    
134    
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  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
184  insert into log  insert into log
185          (channel, me, nick, message, time)          (channel, me, nick, message, time)
186  values (?,?,?,?,?)  values (?,?,?,?,?)
187  });  });
188    
189    
190  my $tags;  my $tags;
191  my $tag_regex = '\b([\w-_]+)//';  my $tag_regex = '\b([\w-_]+)//';
192    
# Line 126  my $tag_regex = '\b([\w-_]+)//'; Line 209  my $tag_regex = '\b([\w-_]+)//';
209                  }                  }
210          },          },
211          context => 5,          context => 5,
212            full_rows => 1,
213   );   );
214    
215  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 133  then throgh C<< sprintf($fmt->{message}, Line 217  then throgh C<< sprintf($fmt->{message},
217    
218  C<context> defines number of messages around each search hit for display.  C<context> defines number of messages around each search hit for display.
219    
220    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  =cut  =cut
224    
225  sub get_from_log {  sub get_from_log {
# Line 179  sub get_from_log { Line 266  sub get_from_log {
266                  $search =~ s/^\s+//;                  $search =~ s/^\s+//;
267                  $search =~ s/\s+$//;                  $search =~ s/\s+$//;
268                  $sth->execute( ( '%' . $search . '%' ) x 2 );                  $sth->execute( ( '%' . $search . '%' ) x 2 );
269                  warn "search for '$search' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "search for '$search' returned ", $sth->rows, " results ", $context || '';
270          } elsif (my $tag = $args->{tag}) {          } elsif (my $tag = $args->{tag}) {
271                  $sth->execute();                  $sth->execute();
272                  warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "tag '$tag' returned ", $sth->rows, " results ", $context || '';
273          } elsif (my $date = $args->{date}) {          } elsif (my $date = $args->{date}) {
274                  $sth->execute($date);                  $sth->execute($date);
275                  warn "found ", $sth->rows, " messages for date $date ", $context || '', "\n";                  _log "found ", $sth->rows, " messages for date $date ", $context || '';
276          } else {          } else {
277                  $sth->execute();                  $sth->execute();
278          }          }
# Line 202  sub get_from_log { Line 289  sub get_from_log {
289                  unshift @rows, $row;                  unshift @rows, $row;
290          }          }
291    
292            # normalize nick names
293            map {
294                    $_->{nick} =~ s/^_*(.*?)_*$/$1/
295            } @rows;
296    
297            return @rows if ($args->{full_rows});
298    
299          my @msgs = (          my @msgs = (
300                  "Showing " . ($#rows + 1) . " messages..."                  "Showing " . ($#rows + 1) . " messages..."
301          );          );
# Line 258  sub get_from_log { Line 352  sub get_from_log {
352                  my $append = 1;                  my $append = 1;
353    
354                  my $nick = $row->{nick};                  my $nick = $row->{nick};
355                  if ($nick =~ s/^_*(.*?)_*$/$1/) {  #               if ($nick =~ s/^_*(.*?)_*$/$1/) {
356                          $row->{nick} = $nick;  #                       $row->{nick} = $nick;
357                  }  #               }
358    
359                  if ($last_row->{nick} ne $nick) {                  if ($last_row->{nick} ne $nick) {
360                          # 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 363  C<me> if not specified will be C<0> (not Line 457  C<me> if not specified will be C<0> (not
457  sub save_message {  sub save_message {
458          my $a = {@_};          my $a = {@_};
459          $a->{me} ||= 0;          $a->{me} ||= 0;
460            $a->{time} ||= strftime($TIMESTAMP,localtime());
461    
462          print          _log
                 $a->{time} ? $a->{time} . " " : strftime($TIMESTAMP,localtime()),  
463                  $a->{channel}, " ",                  $a->{channel}, " ",
464                  $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",                  $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
465                  " " . $a->{msg} . "\n";                  " " . $a->{msg};
466    
467          from_to($a->{msg}, 'UTF-8', $ENCODING);          from_to($a->{msg}, 'UTF-8', $ENCODING);
468    
# Line 377  sub save_message { Line 471  sub save_message {
471                  message => $a->{msg});                  message => $a->{msg});
472  }  }
473    
474    
475  if ($import_dircproxy) {  if ($import_dircproxy) {
476          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
477          warn "importing $import_dircproxy...\n";          warn "importing $import_dircproxy...\n";
# Line 403  if ($import_dircproxy) { Line 498  if ($import_dircproxy) {
498                          ) if ($nick !~ m/^-/);                          ) if ($nick !~ m/^-/);
499    
500                  } else {                  } else {
501                          warn "can't parse: $_\n";                          _log "can't parse: $_";
502                  }                  }
503          }          }
504          close($l);          close($l);
# Line 418  if ($import_dircproxy) { Line 513  if ($import_dircproxy) {
513    
514  my $SKIPPING = 0;               # if skipping, how many we've done  my $SKIPPING = 0;               # if skipping, how many we've done
515  my $SEND_QUEUE;                 # cache  my $SEND_QUEUE;                 # cache
516    my $ping;                                               # ping stats
517    
518  POE::Component::IRC->new($IRC_ALIAS);  POE::Component::IRC->new($IRC_ALIAS);
519    
# Line 440  POE::Session->create( inline_states => Line 536  POE::Session->create( inline_states =>
536                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
537    
538                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
539                    meta( $nick, $channel, 'last-msg', $msg );
540      },      },
541      irc_ctcp_action => sub {      irc_ctcp_action => sub {
542                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 448  POE::Session->create( inline_states => Line 545  POE::Session->create( inline_states =>
545                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
546    
547                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
548    
549                    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                    }
555    
556      },      },
557            irc_ping => sub {
558                    warn "pong ", $_[ARG0], $/;
559                    $ping->{ $_[ARG0] }++;
560            },
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          irc_msg => sub {          irc_msg => sub {
573                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
574                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
575                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
576                    my $channel = $_[ARG1]->[0];
577                  from_to($msg, 'UTF-8', $ENCODING);                  from_to($msg, 'UTF-8', $ENCODING);
578    
579                  my $res = "unknown command '$msg', try /msg $NICK help!";                  my $res = "unknown command '$msg', try /msg $NICK help!";
580                  my @out;                  my @out;
581    
582                  print "<< $msg\n";                  _log "<< $msg";
583    
584                  if ($msg =~ m/^help/i) {                  if ($msg =~ m/^help/i) {
585    
# Line 466  POE::Session->create( inline_states => Line 587  POE::Session->create( inline_states =>
587    
588                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
589    
590                          print ">> /msg $1 $2\n";                          _log ">> /msg $1 $2";
591                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
592                          $res = '';                          $res = '';
593    
# Line 475  POE::Session->create( inline_states => Line 596  POE::Session->create( inline_states =>
596                          my $nr = $1 || 10;                          my $nr = $1 || 10;
597    
598                          my $sth = $dbh->prepare(qq{                          my $sth = $dbh->prepare(qq{
599                                  select nick,count(*) from log group by nick order by count desc limit $nr                                  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                          });                          });
608                          $sth->execute();                          $sth->execute();
609                          $res = "Top $nr users: ";                          $res = "Top $nr users: ";
610                          my @users;                          my @users;
611                          while (my $row = $sth->fetchrow_hashref) {                          while (my $row = $sth->fetchrow_hashref) {
612                                  push @users,$row->{nick} . ': ' . $row->{count};                                  push @users,$row->{nick} . ': ' . $row->{count} . '/' . $row->{len} . '=' . sprintf("%.2f", $row->{len}/$row->{count});
613                          }                          }
614                          $res .= join(" | ", @users);                          $res .= join(" | ", @users);
615                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
616    
617                          foreach my $res (get_from_log( limit => $1 )) {                          my $limit = $1 || meta( $nick, $channel, 'last-size' ) || 10;
618                                  print "last: $res\n";  
619                            foreach my $res (get_from_log( limit => $limit )) {
620                                    _log "last: $res";
621                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
622                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
623                          }                          }
# Line 502  POE::Session->create( inline_states => Line 632  POE::Session->create( inline_states =>
632                                          limit => 20,                                          limit => 20,
633                                          search => $what,                                          search => $what,
634                                  )) {                                  )) {
635                                  print "search [$what]: $res\n";                                  _log "search [$what]: $res";
636                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
637                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
638                          }                          }
639    
640                          $res = '';                          $res = '';
641    
642                    } 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                            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                            }
666    
667                            $res =
668                                    "$what ++ " . ( $stat->{vote}->{'+'} || 0 ) .
669                                    " : " . ( $stat->{vote}->{'-'} || 0 ) . " --" .
670                                    " from " . ( join(", ", @nicks) || 'nobody' );
671    
672                            $_[KERNEL]->post( $IRC_ALIAS => notice => $nick, $res );
673    
674                    } elsif ($msg =~ m/^ping/) {
675                            $res = "ping = " . dump( $ping );
676                    } elsif ($msg =~ m/^conf(?:ig)*\s*(last-size|twitter)*\s*(.*)/) {
677                            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                                    $res = "config for $nick on $channel";
681                                    while ( my ($n,$v) = $sth->fetchrow_array ) {
682                                            $res .= " | $n = $v";
683                                    }
684                            } elsif ( ! $2 ) {
685                                    my $val = meta( $nick, $channel, $1 );
686                                    $res = "current $1 = " . ( $val ? $val : 'undefined' );
687                            } 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                            }
706                  }                  }
707    
708                  if ($res) {                  if ($res) {
709                          print ">> [$nick] $res\n";                          _log ">> [$nick] $res";
710                          from_to($res, $ENCODING, 'UTF-8');                          from_to($res, $ENCODING, 'UTF-8');
711                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
712                  }                  }
713    
714          },          },
715          irc_477 => sub {          irc_477 => sub {
716                  print "# irc_477: ",$_[ARG1], "\n";                  _log "# irc_477: ",$_[ARG1];
717                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
718          },          },
719          irc_505 => sub {          irc_505 => sub {
720                  print "# irc_505: ",$_[ARG1], "\n";                  _log "# irc_505: ",$_[ARG1];
721                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
722  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
723  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
724          },          },
725          irc_registered => sub {          irc_registered => sub {
726                  warn "## indetify $NICK\n";                  _log "## registrated $NICK";
727                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
728          },          },
729            irc_disconnected => sub {
730                    _log "## disconnected, reconnecting again";
731                    $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
732            },
733            irc_socketerr => sub {
734                    _log "## socket error... sleeping for $sleep_on_error seconds and retry";
735                    sleep($sleep_on_error);
736                    $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
737            },
738  #       irc_433 => sub {  #       irc_433 => sub {
739  #               print "# irc_433: ",$_[ARG1], "\n";  #               print "# irc_433: ",$_[ARG1], "\n";
740  #               warn "## indetify $NICK\n";  #               warn "## indetify $NICK\n";
# Line 539  POE::Session->create( inline_states => Line 742  POE::Session->create( inline_states =>
742  #       },  #       },
743      _child => sub {},      _child => sub {},
744      _default => sub {      _default => sub {
745                  printf "%s #%s %s %s\n",                  _log sprintf "sID:%s %s %s",
746                          strftime($TIMESTAMP,localtime()), $_[SESSION]->ID, $_[ARG0],                          $_[SESSION]->ID, $_[ARG0],
747                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :
748                          $_[ARG1]                                        ?       $_[ARG1]                                        :                          $_[ARG1]                                        ?       $_[ARG1]                                        :
749                          "";                          "";

Legend:
Removed from v.37  
changed lines
  Added in v.53

  ViewVC Help
Powered by ViewVC 1.1.26