/[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 43 by dpavlin, Fri Feb 2 22:27:36 2007 UTC trunk/bin/irc-logger.pl revision 61 by dpavlin, Sat Apr 21 12:10:23 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 67  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 URI::Escape;
77  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
78    
79    my $use_twitter = 1;
80    eval { require Net::Twitter; };
81    $use_twitter = 0 if ($@);
82    
83  my $import_dircproxy;  my $import_dircproxy;
84    my $log_path;
85  GetOptions(  GetOptions(
86          'import-dircproxy:s' => \$import_dircproxy,          'import-dircproxy:s' => \$import_dircproxy,
87            'log:s' => \$log_path,
88  );  );
89    
90  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";
91    
92  eval {  sub _log {
93          $dbh->do(qq{ select count(*) from log });          print strftime($TIMESTAMP,localtime()), ' ', join(" ",@_), $/;
94  };  }
95    
96  if ($@) {  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
         warn "creating database table in $DSN\n";  
         $dbh->do(<<'_SQL_SCHEMA_');  
97    
98    my $sql_schema = {
99            log => '
100  create table log (  create table log (
101          id serial,          id serial,
102          time timestamp default now(),          time timestamp default now(),
# Line 97  create table log ( Line 110  create table log (
110  create index log_time on log(time);  create index log_time on log(time);
111  create index log_channel on log(channel);  create index log_channel on log(channel);
112  create index log_nick on log(nick);  create index log_nick on log(nick);
113            ',
114            meta => '
115    create table meta (
116            nick text not null,
117            channel text not null,
118            name text not null,
119            value text,
120            changed timestamp default now(),
121            primary key(nick,channel,name)
122    );
123            ',
124    };
125    
126    foreach my $table ( keys %$sql_schema ) {
127    
128            eval {
129                    $dbh->do(qq{ select count(*) from $table });
130            };
131    
132            if ($@) {
133                    warn "creating database table $table in $DSN\n";
134                    $dbh->do( $sql_schema->{ $table } );
135            }
136    }
137    
138    
139    =head2 meta
140    
141    Set or get some meta data into database
142    
143            meta('nick','channel','var_name', $var_value );
144    
145            $var_value = meta('nick','channel','var_name');
146            ( $var_value, $changed ) = meta('nick','channel','var_name');
147    
148    =cut
149    
150    sub meta {
151            my ($nick,$channel,$name,$value) = @_;
152    
153            # normalize channel name
154            $channel =~ s/^#//;
155    
156            if (defined($value)) {
157    
158                    my $sth = $dbh->prepare(qq{ update meta set value = ?, changed = now() where nick = ? and channel = ? and name = ? });
159    
160                    eval { $sth->execute( $value, $nick, $channel, $name ) };
161    
162                    # error or no result
163                    if ( $@ || ! $sth->rows ) {
164                            $sth = $dbh->prepare(qq{ insert into meta (value,nick,channel,name,changed) values (?,?,?,?,now()) });
165                            $sth->execute( $value, $nick, $channel, $name );
166                            _log "created $nick/$channel/$name = $value";
167                    } else {
168                            _log "updated $nick/$channel/$name = $value ";
169                    }
170    
171                    return $value;
172    
173            } else {
174    
175  _SQL_SCHEMA_                  my $sth = $dbh->prepare(qq{ select value,changed from meta where nick = ? and channel = ? and name = ? });
176                    $sth->execute( $nick, $channel, $name );
177                    my ($v,$c) = $sth->fetchrow_array;
178                    _log "fetched $nick/$channel/$name = $v [$c]";
179                    return ($v,$c) if wantarray;
180                    return $v;
181    
182            }
183  }  }
184    
185    
186    
187  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
188  insert into log  insert into log
189          (channel, me, nick, message, time)          (channel, me, nick, message, time)
190  values (?,?,?,?,?)  values (?,?,?,?,?)
191  });  });
192    
193    
194  my $tags;  my $tags;
195  my $tag_regex = '\b([\w-_]+)//';  my $tag_regex = '\b([\w-_]+)//';
196    
# Line 186  sub get_from_log { Line 270  sub get_from_log {
270                  $search =~ s/^\s+//;                  $search =~ s/^\s+//;
271                  $search =~ s/\s+$//;                  $search =~ s/\s+$//;
272                  $sth->execute( ( '%' . $search . '%' ) x 2 );                  $sth->execute( ( '%' . $search . '%' ) x 2 );
273                  warn "search for '$search' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "search for '$search' returned ", $sth->rows, " results ", $context || '';
274          } elsif (my $tag = $args->{tag}) {          } elsif (my $tag = $args->{tag}) {
275                  $sth->execute();                  $sth->execute();
276                  warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";                  _log "tag '$tag' returned ", $sth->rows, " results ", $context || '';
277          } elsif (my $date = $args->{date}) {          } elsif (my $date = $args->{date}) {
278                  $sth->execute($date);                  $sth->execute($date);
279                  warn "found ", $sth->rows, " messages for date $date ", $context || '', "\n";                  _log "found ", $sth->rows, " messages for date $date ", $context || '';
280          } else {          } else {
281                  $sth->execute();                  $sth->execute();
282          }          }
# Line 379  sub save_message { Line 463  sub save_message {
463          $a->{me} ||= 0;          $a->{me} ||= 0;
464          $a->{time} ||= strftime($TIMESTAMP,localtime());          $a->{time} ||= strftime($TIMESTAMP,localtime());
465    
466          print          _log
                 $a->{time}, " ",  
467                  $a->{channel}, " ",                  $a->{channel}, " ",
468                  $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",                  $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
469                  " " . $a->{msg} . "\n";                  " " . $a->{msg};
470    
471          from_to($a->{msg}, 'UTF-8', $ENCODING);          from_to($a->{msg}, 'UTF-8', $ENCODING);
472    
# Line 392  sub save_message { Line 475  sub save_message {
475                  message => $a->{msg});                  message => $a->{msg});
476  }  }
477    
478    
479  if ($import_dircproxy) {  if ($import_dircproxy) {
480          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
481          warn "importing $import_dircproxy...\n";          warn "importing $import_dircproxy...\n";
# Line 418  if ($import_dircproxy) { Line 502  if ($import_dircproxy) {
502                          ) if ($nick !~ m/^-/);                          ) if ($nick !~ m/^-/);
503    
504                  } else {                  } else {
505                          warn "can't parse: $_\n";                          _log "can't parse: $_";
506                  }                  }
507          }          }
508          close($l);          close($l);
# Line 456  POE::Session->create( inline_states => Line 540  POE::Session->create( inline_states =>
540                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
541    
542                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
543                    meta( $nick, $channel, 'last-msg', $msg );
544      },      },
545      irc_ctcp_action => sub {      irc_ctcp_action => sub {
546                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 464  POE::Session->create( inline_states => Line 549  POE::Session->create( inline_states =>
549                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
550    
551                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
552    
553                    if ( $use_twitter ) {
554                            if ( my $twitter = meta( $nick, $NICK, 'twitter' ) ) {
555                                    my ($login,$passwd) = split(/\s+/,$twitter,2);
556                                    _log("sending twitter for $nick/$login on $channel ");
557                                    my $bot = Net::Twitter->new( username=>$login, password=>$passwd );
558                                    $bot->update("<${channel}> $msg");
559                            }
560                    }
561    
562      },      },
563          irc_ping => sub {          irc_ping => sub {
564                  warn "pong ", $_[ARG0], $/;                  warn "pong ", $_[ARG0], $/;
565                  $ping->{$_[ARG0]++};                  $ping->{ $_[ARG0] }++;
566          },          },
567          irc_invite => sub {          irc_invite => sub {
568                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
569                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
570                  my $channel = $_[ARG1];                  my $channel = $_[ARG1];
                   
571    
572                  warn "invited to $channel by $nick";                  warn "invited to $channel by $nick";
573    
# Line 485  POE::Session->create( inline_states => Line 579  POE::Session->create( inline_states =>
579                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
580                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
581                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
582                    my $channel = $_[ARG1]->[0];
583                  from_to($msg, 'UTF-8', $ENCODING);                  from_to($msg, 'UTF-8', $ENCODING);
584    
585                  my $res = "unknown command '$msg', try /msg $NICK help!";                  my $res = "unknown command '$msg', try /msg $NICK help!";
586                  my @out;                  my @out;
587    
588                  print "<< $msg\n";                  _log "<< $msg";
589    
590                  if ($msg =~ m/^help/i) {                  if ($msg =~ m/^help/i) {
591    
# Line 498  POE::Session->create( inline_states => Line 593  POE::Session->create( inline_states =>
593    
594                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {                  } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
595    
596                          print ">> /msg $1 $2\n";                          _log ">> /msg $1 $2";
597                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
598                          $res = '';                          $res = '';
599    
# Line 508  POE::Session->create( inline_states => Line 603  POE::Session->create( inline_states =>
603    
604                          my $sth = $dbh->prepare(qq{                          my $sth = $dbh->prepare(qq{
605                                  select                                  select
606                                          nick,                                          trim(both '_' from nick) as nick,
607                                          count(*) as count,                                          count(*) as count,
608                                          sum(length(message)) as len                                          sum(length(message)) as len
609                                  from log                                  from log
610                                  group by nick                                  group by trim(both '_' from nick)
611                                  order by len desc,count desc                                  order by len desc,count desc
612                                  limit $nr                                  limit $nr
613                          });                          });
# Line 525  POE::Session->create( inline_states => Line 620  POE::Session->create( inline_states =>
620                          $res .= join(" | ", @users);                          $res .= join(" | ", @users);
621                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
622    
623                          foreach my $res (get_from_log( limit => ($1 || 100) )) {                          my $limit = $1 || meta( $nick, $channel, 'last-size' ) || 10;
624                                  print "last: $res\n";  
625                            foreach my $res (get_from_log( limit => $limit )) {
626                                    _log "last: $res";
627                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
628                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
629                          }                          }
# Line 541  POE::Session->create( inline_states => Line 638  POE::Session->create( inline_states =>
638                                          limit => 20,                                          limit => 20,
639                                          search => $what,                                          search => $what,
640                                  )) {                                  )) {
641                                  print "search [$what]: $res\n";                                  _log "search [$what]: $res";
642                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
643                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
644                          }                          }
# Line 582  POE::Session->create( inline_states => Line 679  POE::Session->create( inline_states =>
679    
680                  } elsif ($msg =~ m/^ping/) {                  } elsif ($msg =~ m/^ping/) {
681                          $res = "ping = " . dump( $ping );                          $res = "ping = " . dump( $ping );
682                    } elsif ($msg =~ m/^conf(?:ig)*\s*(last-size|twitter)*\s*(.*)/) {
683                            if ( ! defined( $1 ) ) {
684                                    my $sth = $dbh->prepare(qq{ select name,value,changed from meta where nick = ? and channel = ? });
685                                    $sth->execute( $nick, $channel );
686                                    $res = "config for $nick on $channel";
687                                    while ( my ($n,$v) = $sth->fetchrow_array ) {
688                                            $res .= " | $n = $v";
689                                    }
690                            } elsif ( ! $2 ) {
691                                    my $val = meta( $nick, $channel, $1 );
692                                    $res = "current $1 = " . ( $val ? $val : 'undefined' );
693                            } else {
694                                    my $validate = {
695                                            'last-size' => qr/^\d+/,
696                                            'twitter' => qr/^\w+\s+\w+/,
697                                    };
698    
699                                    my ( $op, $val ) = ( $1, $2 );
700    
701                                    if ( my $regex = $validate->{$op} ) {
702                                            if ( $val =~ $regex ) {
703                                                    meta( $nick, $channel, $op, $val );
704                                                    $res = "saved $op = $val";
705                                            } else {
706                                                    $res = "config option $op = $val doesn't validate against $regex";
707                                            }
708                                    } else {
709                                            $res = "config option $op doesn't exist";
710                                    }
711                            }
712                  }                  }
713    
714                  if ($res) {                  if ($res) {
715                          print ">> [$nick] $res\n";                          _log ">> [$nick] $res";
716                          from_to($res, $ENCODING, 'UTF-8');                          from_to($res, $ENCODING, 'UTF-8');
717                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                          $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
718                  }                  }
719    
720          },          },
721          irc_477 => sub {          irc_477 => sub {
722                  print "# irc_477: ",$_[ARG1], "\n";                  _log "# irc_477: ",$_[ARG1];
723                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
724          },          },
725          irc_505 => sub {          irc_505 => sub {
726                  print "# irc_505: ",$_[ARG1], "\n";                  _log "# irc_505: ",$_[ARG1];
727                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
728  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
729  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
730          },          },
731          irc_registered => sub {          irc_registered => sub {
732                  warn "## indetify $NICK\n";                  _log "## registrated $NICK";
733                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
734          },          },
735          irc_disconnected => sub {          irc_disconnected => sub {
736                  warn "## disconnected, reconnecting again\n";                  _log "## disconnected, reconnecting again";
737                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
738          },          },
739          irc_socketerr => sub {          irc_socketerr => sub {
740                  warn "## socket error... sleeping for $sleep_on_error seconds and retry";                  _log "## socket error... sleeping for $sleep_on_error seconds and retry";
741                  sleep($sleep_on_error);                  sleep($sleep_on_error);
742                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
743          },          },
# Line 621  POE::Session->create( inline_states => Line 748  POE::Session->create( inline_states =>
748  #       },  #       },
749      _child => sub {},      _child => sub {},
750      _default => sub {      _default => sub {
751                  printf "%s #%s %s %s\n",                  _log sprintf "sID:%s %s %s",
752                          strftime($TIMESTAMP,localtime()), $_[SESSION]->ID, $_[ARG0],                          $_[SESSION]->ID, $_[ARG0],
753                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :
754                          $_[ARG1]                                        ?       $_[ARG1]                                        :                          $_[ARG1]                                        ?       $_[ARG1]                                        :
755                          "";                          "";
# Line 709  p { margin: 0; padding: 0.1em; } Line 836  p { margin: 0; padding: 0.1em; }
836  .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }  .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }
837  .message { color: #000000; font-size: 100%; }  .message { color: #000000; font-size: 100%; }
838  .search { float: right; }  .search { float: right; }
839    a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }
840    a:hover.tag { border: 1px solid #eee }
841    hr { border: 1px dashed #ccc; height: 1px; clear: both; }
842    /*
843  .col-0 { background: #ffff66 }  .col-0 { background: #ffff66 }
844  .col-1 { background: #a0ffff }  .col-1 { background: #a0ffff }
845  .col-2 { background: #99ff99 }  .col-2 { background: #99ff99 }
846  .col-3 { background: #ff9999 }  .col-3 { background: #ff9999 }
847  .col-4 { background: #ff66ff }  .col-4 { background: #ff66ff }
848  a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }  */
 a:hover.tag { border: 1px solid #eee }  
 hr { border: 1px dashed #ccc; height: 1px; clear: both; }  
849  _END_OF_STYLE_  _END_OF_STYLE_
850    
851  my $max_color = 4;  my $max_color = 4;
852    
853    my @cols = qw(
854            #ffcccc #ccffe6 #ccccff #e6ccff #ffccff #ffcce6 #ff9999 #ffcc99 #ffff99
855            #ccff99 #99ff99 #99ffcc #99ccff #9999ff #cc99ff #ff6666 #ffb366 #ffff66
856            #66ff66 #66ffb3 #66b3ff #6666ff #ff3333 #33ff33 #3399ff #3333ff #ff3399
857            #a0a0a0 #ff0000 #ffff00 #80ff00 #0000ff #8000ff #ff00ff #ff0080 #994d00
858            #999900 #009900 #cc0066 #c0c0c0 #ccff99 #99ff33 #808080 #660033 #ffffff
859    );
860    
861    $max_color = 0;
862    foreach my $c (@cols) {
863            $style .= ".col-${max_color} { background: $c }\n";
864            $max_color++;
865    }
866    warn "defined $max_color colors for users...\n";
867    
868  my %nick_enumerator;  my %nick_enumerator;
869    
870  sub root_handler {  sub root_handler {
# Line 798  sub root_handler { Line 942  sub root_handler {
942                                  filter => {                                  filter => {
943                                          message => sub {                                          message => sub {
944                                                  my $m = shift || return;                                                  my $m = shift || return;
945    
946                                                    # protect HTML from wiki modifications
947                                                    sub e {
948                                                            my $t = shift;
949                                                            return 'uri_unescape{' . uri_escape($t) . '}';
950                                                    }
951    
952                                                  $m =~ s/($escape_re)/$escape{$1}/gs;                                                  $m =~ s/($escape_re)/$escape{$1}/gs;
953                                                  $m =~ s#($RE{URI}{HTTP})#<a href="$1">$1</a>#gs;                                                  $m =~ s#($RE{URI}{HTTP})#e(qq{<a href="$1">$1</a>})#egs;
954                                                  $m =~ s#$tag_regex#<a href="?tag=$1" class="tag">$1</a>#g;                                                  $m =~ s#$tag_regex#e(qq{<a href="?tag=$1" class="tag">$1</a>})#egs;
955                                                    $m =~ s#\*(\w+)\*#<b>$1</b>#gs;
956                                                    $m =~ s#_(\w+)_#<u>$1</u>#gs;
957                                                    $m =~ s#\/(\w+)\/#<i>$1</i>#gs;
958    
959                                                    $m =~ s#uri_unescape{([^}]+)}#uri_unescape($1)#egs;
960                                                  return $m;                                                  return $m;
961                                          },                                          },
962                                          nick => sub {                                          nick => sub {

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

  ViewVC Help
Powered by ViewVC 1.1.26