/[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 46 by dpavlin, Sat Feb 3 12:28:17 2007 UTC revision 69 by dpavlin, Fri Dec 7 12:51:55 2007 UTC
# Line 73  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    use DateTime::Format::ISO8601;
79    use Carp qw/confess/;
80    
81    my $use_twitter = 1;
82    eval { require Net::Twitter; };
83    $use_twitter = 0 if ($@);
84    
85  my $import_dircproxy;  my $import_dircproxy;
86  my $log_path;  my $log_path;
# Line 82  GetOptions( Line 89  GetOptions(
89          'log:s' => \$log_path,          'log:s' => \$log_path,
90  );  );
91    
92    $SIG{__DIE__} = sub {
93            confess "fatal error";
94    };
95    
96  open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";  open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";
97    
98  sub _log {  sub _log {
# Line 90  sub _log { Line 101  sub _log {
101    
102  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
103    
104  eval {  my $sql_schema = {
105          $dbh->do(qq{ select count(*) from log });          log => '
 };  
   
 if ($@) {  
         warn "creating database table in $DSN\n";  
         $dbh->do(<<'_SQL_SCHEMA_');  
   
106  create table log (  create table log (
107          id serial,          id serial,
108          time timestamp default now(),          time timestamp default now(),
# Line 111  create table log ( Line 116  create table log (
116  create index log_time on log(time);  create index log_time on log(time);
117  create index log_channel on log(channel);  create index log_channel on log(channel);
118  create index log_nick on log(nick);  create index log_nick on log(nick);
119            ',
120            meta => '
121    create table meta (
122            nick text not null,
123            channel text not null,
124            name text not null,
125            value text,
126            changed timestamp default now(),
127            primary key(nick,channel,name)
128    );
129            ',
130    };
131    
132    foreach my $table ( keys %$sql_schema ) {
133    
134            eval {
135                    $dbh->do(qq{ select count(*) from $table });
136            };
137    
138            if ($@) {
139                    warn "creating database table $table in $DSN\n";
140                    $dbh->do( $sql_schema->{ $table } );
141            }
142    }
143    
144    
145    =head2 meta
146    
147    Set or get some meta data into database
148    
149            meta('nick','channel','var_name', $var_value );
150    
151            $var_value = meta('nick','channel','var_name');
152            ( $var_value, $changed ) = meta('nick','channel','var_name');
153    
154    =cut
155    
156  _SQL_SCHEMA_  sub meta {
157            my ($nick,$channel,$name,$value) = @_;
158    
159            # normalize channel name
160            $channel =~ s/^#//;
161    
162            if (defined($value)) {
163    
164                    my $sth = $dbh->prepare(qq{ update meta set value = ?, changed = now() where nick = ? and channel = ? and name = ? });
165    
166                    eval { $sth->execute( $value, $nick, $channel, $name ) };
167    
168                    # error or no result
169                    if ( $@ || ! $sth->rows ) {
170                            $sth = $dbh->prepare(qq{ insert into meta (value,nick,channel,name,changed) values (?,?,?,?,now()) });
171                            $sth->execute( $value, $nick, $channel, $name );
172                            _log "created $nick/$channel/$name = $value";
173                    } else {
174                            _log "updated $nick/$channel/$name = $value ";
175                    }
176    
177                    return $value;
178    
179            } else {
180    
181                    my $sth = $dbh->prepare(qq{ select value,changed from meta where nick = ? and channel = ? and name = ? });
182                    $sth->execute( $nick, $channel, $name );
183                    my ($v,$c) = $sth->fetchrow_array;
184                    _log "fetched $nick/$channel/$name = $v [$c]";
185                    return ($v,$c) if wantarray;
186                    return $v;
187    
188            }
189  }  }
190    
191    
192    
193  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
194  insert into log  insert into log
195          (channel, me, nick, message, time)          (channel, me, nick, message, time)
196  values (?,?,?,?,?)  values (?,?,?,?,?)
197  });  });
198    
199    
200  my $tags;  my $tags;
201  my $tag_regex = '\b([\w-_]+)//';  my $tag_regex = '\b([\w-_]+)//';
202    
# Line 159  C<me>, C<nick> and C<message> keys. Line 235  C<me>, C<nick> and C<message> keys.
235  sub get_from_log {  sub get_from_log {
236          my $args = {@_};          my $args = {@_};
237    
238          $args->{fmt} ||= {          if ( ! $args->{fmt} ) {
239                  date => '[%s] ',                  $args->{fmt} = {
240                  time => '{%s} ',                          date => '[%s] ',
241                  time_channel => '{%s %s} ',                          time => '{%s} ',
242                  nick => '%s: ',                          time_channel => '{%s %s} ',
243                  me_nick => '***%s ',                          nick => '%s: ',
244                  message => '%s',                          me_nick => '***%s ',
245          };                          message => '%s',
246                    };
247            }
248    
249          my $sql_message = qq{          my $sql_message = qq{
250                  select                  select
# Line 189  sub get_from_log { Line 267  sub get_from_log {
267    
268          my $sql = $context ? $sql_context : $sql_message;          my $sql = $context ? $sql_context : $sql_message;
269    
270          $sql .= " where message ilike ? or nick ilike ? " if ($args->{search});          sub check_date {
271          $sql .= " where id in (" . join(",", @{ $tags->{ $args->{tag} } }) . ") " if ($args->{tag} && $tags->{ $args->{tag} });                  my $date = shift || return;
272          $sql .= " where date(time) = ? " if ($args->{date});                  my $new_date = eval { DateTime::Format::ISO8601->parse_datetime( $date )->ymd; };
273          $sql .= " order by log.time desc";                  if ( $@ ) {
274          $sql .= " limit " . $args->{limit} if ($args->{limit});                          warn "invalid date $date\n";
275                            $new_date = DateTime->now->ymd;
276                    }
277                    return $new_date;
278            }
279    
280            my @where;
281            my @args;
282    
         my $sth = $dbh->prepare( $sql );  
283          if (my $search = $args->{search}) {          if (my $search = $args->{search}) {
284                  $search =~ s/^\s+//;                  $search =~ s/^\s+//;
285                  $search =~ s/\s+$//;                  $search =~ s/\s+$//;
286                  $sth->execute( ( '%' . $search . '%' ) x 2 );                  push @where, 'message ilike ? or nick ilike ?';
287                  _log "search for '$search' returned ", $sth->rows, " results ", $context || '';                  push @args, ( ( '%' . $search . '%' ) x 2 );
288          } elsif (my $tag = $args->{tag}) {                  _log "search for '$search'";
                 $sth->execute();  
                 _log "tag '$tag' returned ", $sth->rows, " results ", $context || '';  
         } elsif (my $date = $args->{date}) {  
                 $sth->execute($date);  
                 _log "found ", $sth->rows, " messages for date $date ", $context || '';  
         } else {  
                 $sth->execute();  
289          }          }
290    
291            if ($args->{tag} && $tags->{ $args->{tag} }) {
292                    push @where, 'id in (' . join(',', @{ $tags->{ $args->{tag} } }) . ')';
293                    _log "search for tags $args->{tag}";
294            }
295    
296            if (my $date = $args->{date} ) {
297                    $date = check_date( $date );
298                    push @where, 'date(time) = ?';
299                    push @args, $date;
300                    _log "search for date $date";
301            }
302    
303            $sql .= " where " . join(" and ", @where) if @where;
304    
305            $sql .= " order by log.time desc";
306            $sql .= " limit " . $args->{limit} if ($args->{limit});
307    
308            #warn "### sql: $sql ", dump( @args );
309    
310            my $sth = $dbh->prepare( $sql );
311            eval { $sth->execute( @args ) };
312            return if $@;
313    
314          my $last_row = {          my $last_row = {
315                  date => '',                  date => '',
316                  time => '',                  time => '',
# Line 405  sub save_message { Line 506  sub save_message {
506                  message => $a->{msg});                  message => $a->{msg});
507  }  }
508    
509    
510  if ($import_dircproxy) {  if ($import_dircproxy) {
511          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";          open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
512          warn "importing $import_dircproxy...\n";          warn "importing $import_dircproxy...\n";
513          my $tz_offset = 2 * 60 * 60;    # TZ GMT+2          my $tz_offset = 1 * 60 * 60;    # TZ GMT+2
514          while(<$l>) {          while(<$l>) {
515                  chomp;                  chomp;
516                  if (/^@(\d+)\s(\S+)\s(.+)$/) {                  if (/^@(\d+)\s(\S+)\s(.+)$/) {
# Line 469  POE::Session->create( inline_states => Line 571  POE::Session->create( inline_states =>
571                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
572    
573                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 0, nick => $nick, msg => $msg);
574                    meta( $nick, $channel, 'last-msg', $msg );
575      },      },
576      irc_ctcp_action => sub {      irc_ctcp_action => sub {
577                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 477  POE::Session->create( inline_states => Line 580  POE::Session->create( inline_states =>
580                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
581    
582                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);                  save_message( channel => $channel, me => 1, nick => $nick, msg => $msg);
583    
584                    if ( $use_twitter ) {
585                            if ( my $twitter = meta( $nick, $NICK, 'twitter' ) ) {
586                                    my ($login,$passwd) = split(/\s+/,$twitter,2);
587                                    _log("sending twitter for $nick/$login on $channel ");
588                                    my $bot = Net::Twitter->new( username=>$login, password=>$passwd );
589                                    $bot->update("<${channel}> $msg");
590                            }
591                    }
592    
593      },      },
594          irc_ping => sub {          irc_ping => sub {
595                  warn "pong ", $_[ARG0], $/;                  warn "pong ", $_[ARG0], $/;
596                  $ping->{$_[ARG0]++};                  $ping->{ $_[ARG0] }++;
597          },          },
598          irc_invite => sub {          irc_invite => sub {
599                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
600                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
601                  my $channel = $_[ARG1];                  my $channel = $_[ARG1];
                   
602    
603                  warn "invited to $channel by $nick";                  warn "invited to $channel by $nick";
604    
# Line 498  POE::Session->create( inline_states => Line 610  POE::Session->create( inline_states =>
610                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
611                  my $nick = (split /!/, $_[ARG0])[0];                  my $nick = (split /!/, $_[ARG0])[0];
612                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
613                    my $channel = $_[ARG1]->[0];
614                  from_to($msg, 'UTF-8', $ENCODING);                  from_to($msg, 'UTF-8', $ENCODING);
615    
616                  my $res = "unknown command '$msg', try /msg $NICK help!";                  my $res = "unknown command '$msg', try /msg $NICK help!";
# Line 521  POE::Session->create( inline_states => Line 634  POE::Session->create( inline_states =>
634    
635                          my $sth = $dbh->prepare(qq{                          my $sth = $dbh->prepare(qq{
636                                  select                                  select
637                                          nick,                                          trim(both '_' from nick) as nick,
638                                          count(*) as count,                                          count(*) as count,
639                                          sum(length(message)) as len                                          sum(length(message)) as len
640                                  from log                                  from log
641                                  group by nick                                  group by trim(both '_' from nick)
642                                  order by len desc,count desc                                  order by len desc,count desc
643                                  limit $nr                                  limit $nr
644                          });                          });
# Line 538  POE::Session->create( inline_states => Line 651  POE::Session->create( inline_states =>
651                          $res .= join(" | ", @users);                          $res .= join(" | ", @users);
652                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {                  } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
653    
654                          foreach my $res (get_from_log( limit => ($1 || 100) )) {                          my $limit = $1 || meta( $nick, $channel, 'last-size' ) || 10;
655    
656                            foreach my $res (get_from_log( limit => $limit )) {
657                                  _log "last: $res";                                  _log "last: $res";
658                                  from_to($res, $ENCODING, 'UTF-8');                                  from_to($res, $ENCODING, 'UTF-8');
659                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );                                  $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
# Line 595  POE::Session->create( inline_states => Line 710  POE::Session->create( inline_states =>
710    
711                  } elsif ($msg =~ m/^ping/) {                  } elsif ($msg =~ m/^ping/) {
712                          $res = "ping = " . dump( $ping );                          $res = "ping = " . dump( $ping );
713                    } elsif ($msg =~ m/^conf(?:ig)*\s*(last-size|twitter)*\s*(.*)/) {
714                            if ( ! defined( $1 ) ) {
715                                    my $sth = $dbh->prepare(qq{ select name,value,changed from meta where nick = ? and channel = ? });
716                                    $sth->execute( $nick, $channel );
717                                    $res = "config for $nick on $channel";
718                                    while ( my ($n,$v) = $sth->fetchrow_array ) {
719                                            $res .= " | $n = $v";
720                                    }
721                            } elsif ( ! $2 ) {
722                                    my $val = meta( $nick, $channel, $1 );
723                                    $res = "current $1 = " . ( $val ? $val : 'undefined' );
724                            } else {
725                                    my $validate = {
726                                            'last-size' => qr/^\d+/,
727                                            'twitter' => qr/^\w+\s+\w+/,
728                                    };
729    
730                                    my ( $op, $val ) = ( $1, $2 );
731    
732                                    if ( my $regex = $validate->{$op} ) {
733                                            if ( $val =~ $regex ) {
734                                                    meta( $nick, $channel, $op, $val );
735                                                    $res = "saved $op = $val";
736                                            } else {
737                                                    $res = "config option $op = $val doesn't validate against $regex";
738                                            }
739                                    } else {
740                                            $res = "config option $op doesn't exist";
741                                    }
742                            }
743                  }                  }
744    
745                  if ($res) {                  if ($res) {
# Line 722  p { margin: 0; padding: 0.1em; } Line 867  p { margin: 0; padding: 0.1em; }
867  .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 ; }
868  .message { color: #000000; font-size: 100%; }  .message { color: #000000; font-size: 100%; }
869  .search { float: right; }  .search { float: right; }
870    a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }
871    a:hover.tag { border: 1px solid #eee }
872    hr { border: 1px dashed #ccc; height: 1px; clear: both; }
873    /*
874  .col-0 { background: #ffff66 }  .col-0 { background: #ffff66 }
875  .col-1 { background: #a0ffff }  .col-1 { background: #a0ffff }
876  .col-2 { background: #99ff99 }  .col-2 { background: #99ff99 }
877  .col-3 { background: #ff9999 }  .col-3 { background: #ff9999 }
878  .col-4 { background: #ff66ff }  .col-4 { background: #ff66ff }
879  a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }  */
880  a:hover.tag { border: 1px solid #eee }  .calendar { border: 1px solid red; width: 100%; }
881  hr { border: 1px dashed #ccc; height: 1px; clear: both; }  .month { border: 0px; width: 100%; }
882  _END_OF_STYLE_  _END_OF_STYLE_
883    
884  my $max_color = 4;  my $max_color = 4;
885    
886    my @cols = qw(
887            #ffcccc #ccffe6 #ccccff #e6ccff #ffccff #ffcce6 #ff9999 #ffcc99 #ffff99
888            #ccff99 #99ff99 #99ffcc #99ccff #9999ff #cc99ff #ff6666 #ffb366 #ffff66
889            #66ff66 #66ffb3 #66b3ff #6666ff #ff3333 #33ff33 #3399ff #3333ff #ff3399
890            #a0a0a0 #ff0000 #ffff00 #80ff00 #0000ff #8000ff #ff00ff #ff0080 #994d00
891            #999900 #009900 #cc0066 #c0c0c0 #ccff99 #99ff33 #808080 #660033 #ffffff
892    );
893    
894    $max_color = 0;
895    foreach my $c (@cols) {
896            $style .= ".col-${max_color} { background: $c }\n";
897            $max_color++;
898    }
899    warn "defined $max_color colors for users...\n";
900    
901  my %nick_enumerator;  my %nick_enumerator;
902    
903  sub root_handler {  sub root_handler {
# Line 767  sub root_handler { Line 931  sub root_handler {
931                  qq{<p>};                  qq{<p>};
932          if ($request->url =~ m#/history#) {          if ($request->url =~ m#/history#) {
933                  my $sth = $dbh->prepare(qq{                  my $sth = $dbh->prepare(qq{
934                          select date(time) as date,count(*) as nr                          select date(time) as date,count(*) as nr,sum(length(message)) as len
935                                  from log                                  from log
936                                  group by date(time)                                  group by date(time)
937                                  order by date(time) desc                                  order by date(time) desc
938                  });                  });
939                  $sth->execute();                  $sth->execute();
940                  my ($l_yyyy,$l_mm) = (0,0);                  my ($l_yyyy,$l_mm) = (0,0);
941                    $html .= qq{<table class="calendar"><tr>};
942                  my $cal;                  my $cal;
943                    my $ord = 0;
944                  while (my $row = $sth->fetchrow_hashref) {                  while (my $row = $sth->fetchrow_hashref) {
945                          # this is probably PostgreSQL specific, expects ISO date                          # this is probably PostgreSQL specific, expects ISO date
946                          my ($yyyy,$mm,$dd) = split(/-/, $row->{date});                          my ($yyyy,$mm,$dd) = split(/-/, $row->{date});
947                          if ($yyyy != $l_yyyy || $mm != $l_mm) {                          if ($yyyy != $l_yyyy || $mm != $l_mm) {
948                                  $html .= $cal->as_HTML() if ($cal);                                  if ( $cal ) {
949                                            $html .= qq{<td valign="top">} . $cal->as_HTML() . qq{</td>};
950                                            $ord++;
951                                            $html .= qq{</tr><tr>} if ( $ord % 3 == 0 );
952                                    }
953                                  $cal = new HTML::CalendarMonthSimple('month'=>$mm,'year'=>$yyyy);                                  $cal = new HTML::CalendarMonthSimple('month'=>$mm,'year'=>$yyyy);
954                                  $cal->border(2);                                  $cal->border(1);
955                                    $cal->width('30%');
956                                    $cal->cellheight('5em');
957                                    $cal->tableclass('month');
958                                    #$cal->cellclass('day');
959                                    $cal->sunday('SUN');
960                                    $cal->saturday('SAT');
961                                    $cal->weekdays('MON','TUE','WED','THU','FRI');
962                                  ($l_yyyy,$l_mm) = ($yyyy,$mm);                                  ($l_yyyy,$l_mm) = ($yyyy,$mm);
963                          }                          }
964                          $cal->setcontent($dd, qq{                          $cal->setcontent($dd, qq{
965                                  <a href="/?date=$row->{date}">$row->{nr}</a>                                  <a href="/?date=$row->{date}">$row->{nr}</a><br/>$row->{len}
966                          });                          });
967                            
968                  }                  }
969                  $html .= $cal->as_HTML() if ($cal);                  $html .= qq{<td valign="top">} . $cal->as_HTML() . qq{</td></tr></table>};
970    
971          } else {          } else {
972                  $html .= join("</p><p>",                  $html .= join("</p><p>",
973                          get_from_log(                          get_from_log(
974                                  limit => $q->param('last') || $q->param('date') ? undef : 100,                                  limit => ( $q->param('last') || $q->param('date') ) ? undef : 100,
975                                  search => $search || undef,                                  search => $search || undef,
976                                  tag => $q->param('tag') || undef,                                  tag => $q->param('tag') || undef,
977                                  date => $q->param('date') || undef,                                  date => $q->param('date') || undef,
# Line 811  sub root_handler { Line 989  sub root_handler {
989                                  filter => {                                  filter => {
990                                          message => sub {                                          message => sub {
991                                                  my $m = shift || return;                                                  my $m = shift || return;
992    
993                                                    # protect HTML from wiki modifications
994                                                    sub e {
995                                                            my $t = shift;
996                                                            return 'uri_unescape{' . uri_escape($t) . '}';
997                                                    }
998    
999                                                  $m =~ s/($escape_re)/$escape{$1}/gs;                                                  $m =~ s/($escape_re)/$escape{$1}/gs;
1000                                                  $m =~ s#($RE{URI}{HTTP})#<a href="$1">$1</a>#gs;                                                  $m =~ s#($RE{URI}{HTTP})#e(qq{<a href="$1">$1</a>})#egs;
1001                                                  $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;
1002                                                    $m =~ s#\*(\w+)\*#<b>$1</b>#gs;
1003                                                    $m =~ s#_(\w+)_#<u>$1</u>#gs;
1004                                                    $m =~ s#\/(\w+)\/#<i>$1</i>#gs;
1005    
1006                                                    $m =~ s#uri_unescape{([^}]+)}#uri_unescape($1)#egs;
1007                                                  return $m;                                                  return $m;
1008                                          },                                          },
1009                                          nick => sub {                                          nick => sub {

Legend:
Removed from v.46  
changed lines
  Added in v.69

  ViewVC Help
Powered by ViewVC 1.1.26