/[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 33 by dpavlin, Sat Jun 24 22:15:47 2006 UTC revision 37 by dpavlin, Sun Jun 25 17:40:59 2006 UTC
# Line 10  irc-logger.pl Line 10  irc-logger.pl
10    
11  ./irc-logger.pl  ./irc-logger.pl
12    
13    =head2 Options
14    
15    =over 4
16    
17    =item --import-dircproxy=filename
18    
19    Import log from C<dircproxy> to C<irc-logger> database
20    
21  =head1 DESCRIPTION  =head1 DESCRIPTION
22    
23  log all conversation on irc channel  log all conversation on irc channel
# Line 40  my %FOLLOWS = Line 48  my %FOLLOWS =
48  my $DSN = 'DBI:Pg:dbname=' . $NICK;  my $DSN = 'DBI:Pg:dbname=' . $NICK;
49    
50  my $ENCODING = 'ISO-8859-2';  my $ENCODING = 'ISO-8859-2';
51    my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';
52    
53  ## END CONFIG  ## END CONFIG
54    
# Line 52  use Encode qw/from_to is_utf8/; Line 61  use Encode qw/from_to is_utf8/;
61  use Regexp::Common qw /URI/;  use Regexp::Common qw /URI/;
62  use CGI::Simple;  use CGI::Simple;
63  use HTML::TagCloud;  use HTML::TagCloud;
64    use POSIX qw/strftime/;
65    use HTML::CalendarMonthSimple;
66    use Getopt::Long;
67    use DateTime;
68    
69    my $import_dircproxy;
70    GetOptions(
71            'import-dircproxy:s' => \$import_dircproxy,
72    );
73    
74  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;  my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
75    
# Line 82  _SQL_SCHEMA_ Line 100  _SQL_SCHEMA_
100    
101  my $sth = $dbh->prepare(qq{  my $sth = $dbh->prepare(qq{
102  insert into log  insert into log
103          (channel, me, nick, message)          (channel, me, nick, message, time)
104  values (?,?,?,?)  values (?,?,?,?,?)
105  });  });
106    
107  my $tags;  my $tags;
# Line 120  C<context> defines number of messages ar Line 138  C<context> defines number of messages ar
138  sub get_from_log {  sub get_from_log {
139          my $args = {@_};          my $args = {@_};
140    
         $args->{limit} ||= 10;  
   
141          $args->{fmt} ||= {          $args->{fmt} ||= {
142                  date => '[%s] ',                  date => '[%s] ',
143                  time => '{%s} ',                  time => '{%s} ',
# Line 154  sub get_from_log { Line 170  sub get_from_log {
170    
171          $sql .= " where message ilike ? or nick ilike ? " if ($args->{search});          $sql .= " where message ilike ? or nick ilike ? " if ($args->{search});
172          $sql .= " where id in (" . join(",", @{ $tags->{ $args->{tag} } }) . ") " if ($args->{tag} && $tags->{ $args->{tag} });          $sql .= " where id in (" . join(",", @{ $tags->{ $args->{tag} } }) . ") " if ($args->{tag} && $tags->{ $args->{tag} });
173            $sql .= " where date(time) = ? " if ($args->{date});
174          $sql .= " order by log.time desc";          $sql .= " order by log.time desc";
175          $sql .= " limit " . $args->{limit};          $sql .= " limit " . $args->{limit} if ($args->{limit});
176    
177          my $sth = $dbh->prepare( $sql );          my $sth = $dbh->prepare( $sql );
178          if (my $search = $args->{search}) {          if (my $search = $args->{search}) {
# Line 166  sub get_from_log { Line 183  sub get_from_log {
183          } elsif (my $tag = $args->{tag}) {          } elsif (my $tag = $args->{tag}) {
184                  $sth->execute();                  $sth->execute();
185                  warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";                  warn "tag '$tag' returned ", $sth->rows, " results ", $context || '', "\n";
186            } elsif (my $date = $args->{date}) {
187                    $sth->execute($date);
188                    warn "found ", $sth->rows, " messages for date $date ", $context || '', "\n";
189          } else {          } else {
190                  $sth->execute();                  $sth->execute();
191          }          }
# Line 210  sub get_from_log { Line 230  sub get_from_log {
230                  }                  }
231          }          }
232    
233            # sprintf which can take coderef as first parametar
234            sub cr_sprintf {
235                    my $fmt = shift || return;
236                    if (ref($fmt) eq 'CODE') {
237                            $fmt->(@_);
238                    } else {
239                            sprintf($fmt, @_);
240                    }
241            }
242    
243          foreach my $row (@rows) {          foreach my $row (@rows) {
244    
245                  $row->{time} =~ s#\.\d+##;                  $row->{time} =~ s#\.\d+##;
246    
247                  my $msg = '';                  my $msg = '';
248    
249                  $msg = sprintf($args->{fmt}->{date}, $row->{date}) . ' ' if ($last_row->{date} ne $row->{date});                  $msg = cr_sprintf($args->{fmt}->{date}, $row->{date}) . ' ' if ($last_row->{date} ne $row->{date});
250                  my $t = $row->{time};                  my $t = $row->{time};
251    
252                  if ($last_row->{channel} ne $row->{channel}) {                  if ($last_row->{channel} ne $row->{channel}) {
253                          $msg .= sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});                          $msg .= cr_sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});
254                  } else {                  } else {
255                          $msg .= sprintf($args->{fmt}->{time}, $t);                          $msg .= cr_sprintf($args->{fmt}->{time}, $t);
256                  }                  }
257    
258                  my $append = 1;                  my $append = 1;
# Line 239  sub get_from_log { Line 269  sub get_from_log {
269    
270                          $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');                          $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');
271    
272                          $msg .= sprintf( $fmt, $nick );                          $msg .= cr_sprintf( $fmt, $nick );
273                          $append = 0;                          $append = 0;
274                  }                  }
275    
276                  $args->{fmt}->{message} ||= '%s';                  $args->{fmt}->{message} ||= '%s';
277                  if (ref($args->{filter}->{message}) eq 'CODE') {                  if (ref($args->{filter}->{message}) eq 'CODE') {
278                          $msg .= sprintf($args->{fmt}->{message},                          $msg .= cr_sprintf($args->{fmt}->{message},
279                                  $args->{filter}->{message}->(                                  $args->{filter}->{message}->(
280                                          $row->{message}                                          $row->{message}
281                                  )                                  )
282                          );                          );
283                  } else {                  } else {
284                          $msg .= sprintf($args->{fmt}->{message}, $row->{message});                          $msg .= cr_sprintf($args->{fmt}->{message}, $row->{message});
285                  }                  }
286    
287                  if ($append && @msgs) {                  if ($append && @msgs) {
# Line 266  sub get_from_log { Line 296  sub get_from_log {
296          return @msgs;          return @msgs;
297  }  }
298    
299    # tags support
300    
301    my $cloud = HTML::TagCloud->new;
302    
303    =head2 add_tag
304    
305     add_tag( id => 42, message => 'irc message' );
306    
307    =cut
308    
309    sub add_tag {
310            my $arg = {@_};
311    
312            return unless ($arg->{id} && $arg->{message});
313    
314            my $m = $arg->{message};
315            from_to('UTF-8', 'iso-8859-2', $m) if (is_utf8($m));
316    
317            while ($m =~ s#$tag_regex##s) {
318                    my $tag = $1;
319                    next if (! $tag || $tag =~ m/https?:/i);
320                    push @{ $tags->{$tag} }, $arg->{id};
321                    #warn "+tag $tag: $arg->{id}\n";
322                    $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
323            }
324    }
325    
326    =head2 seed_tags
327    
328    Read all tags from database and create in-memory cache for tags
329    
330    =cut
331    
332    sub seed_tags {
333            my $sth = $dbh->prepare(qq{ select id,message from log where message like '%//%' });
334            $sth->execute;
335            while (my $row = $sth->fetchrow_hashref) {
336                    add_tag( %$row );
337            }
338    
339            foreach my $tag (keys %$tags) {
340                    $cloud->add($tag, "?tag=$tag", scalar @{$tags->{$tag}} + 1);
341            }
342    }
343    
344    seed_tags;
345    
346    
347    =head2 save_message
348    
349      save_message(
350            channel => '#foobar',
351            me => 0,
352            nick => 'dpavlin',
353            msg => 'test message',
354            time => '2006-06-25 18:57:18',
355      );
356    
357    C<time> is optional, it will use C<< now() >> if it's not available.
358    
359    C<me> if not specified will be C<0> (not C</me> message)
360    
361    =cut
362    
363    sub save_message {
364            my $a = {@_};
365            $a->{me} ||= 0;
366    
367            print
368                    $a->{time} ? $a->{time} . " " : strftime($TIMESTAMP,localtime()),
369                    $a->{channel}, " ",
370                    $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
371                    " " . $a->{msg} . "\n";
372    
373            from_to($a->{msg}, 'UTF-8', $ENCODING);
374    
375            $sth->execute($a->{channel}, $a->{me}, $a->{nick}, $a->{msg}, $a->{time});
376            add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef),
377                    message => $a->{msg});
378    }
379    
380    if ($import_dircproxy) {
381            open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
382            warn "importing $import_dircproxy...\n";
383            my $tz_offset = 2 * 60 * 60;    # TZ GMT+2
384            while(<$l>) {
385                    chomp;
386                    if (/^@(\d+)\s(\S+)\s(.+)$/) {
387                            my ($time, $nick, $msg) = ($1,$2,$3);
388    
389                            my $dt = DateTime->from_epoch( epoch => $time + $tz_offset );
390    
391                            my $me = 0;
392                            $me = 1 if ($nick =~ m/^\[\S+]/);
393                            $nick =~ s/^[\[<]([^!]+).*$/$1/;
394    
395                            $msg =~ s/^ACTION\s+// if ($me);
396    
397                            save_message(
398                                    channel => $CHANNEL,
399                                    me => $me,
400                                    nick => $nick,
401                                    msg => $msg,
402                                    time => $dt->ymd . " " . $dt->hms,
403                            ) if ($nick !~ m/^-/);
404    
405                    } else {
406                            warn "can't parse: $_\n";
407                    }
408            }
409            close($l);
410            warn "import over\n";
411            exit;
412    }
413    
414    
415    #
416    # POE handing part
417    #
418    
419  my $SKIPPING = 0;               # if skipping, how many we've done  my $SKIPPING = 0;               # if skipping, how many we've done
420  my $SEND_QUEUE;                 # cache  my $SEND_QUEUE;                 # cache
421    
422  POE::Component::IRC->new($IRC_ALIAS);  POE::Component::IRC->new($IRC_ALIAS);
423    
424  POE::Session->create  POE::Session->create( inline_states =>
   (inline_states =>  
425     {_start => sub {           {_start => sub {      
426                  $_[KERNEL]->post($IRC_ALIAS => register => 'all');                  $_[KERNEL]->post($IRC_ALIAS => register => 'all');
427                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);                  $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
# Line 291  POE::Session->create Line 439  POE::Session->create
439                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
440                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
441    
442                  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);  
443      },      },
444      irc_ctcp_action => sub {      irc_ctcp_action => sub {
445                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 304  POE::Session->create Line 447  POE::Session->create
447                  my $channel = $_[ARG1]->[0];                  my $channel = $_[ARG1]->[0];
448                  my $msg = $_[ARG2];                  my $msg = $_[ARG2];
449    
450                  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);  
451      },      },
452          irc_msg => sub {          irc_msg => sub {
453                  my $kernel = $_[KERNEL];                  my $kernel = $_[KERNEL];
# Line 399  POE::Session->create Line 537  POE::Session->create
537  #               warn "## indetify $NICK\n";  #               warn "## indetify $NICK\n";
538  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );  #               $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
539  #       },  #       },
         irc_372 => sub {  
                 print "MOTD: ", $_[ARG1], "\n";  
         },  
         irc_snotice => sub {  
                 print "(server notice): ", $_[ARG0], "\n";  
         },  
     (map  
      {  
        ;"irc_$_" => sub { }}  
      qw(  
                 )),  
 #       join  
 #       ctcp_version  
 #       connected snotice ctcp_action ping notice mode part quit  
 #       001 002 003 004 005  
 #       250 251 252 253 254 265 266  
 #       332 333 353 366 372 375 376  
 #       477  
540      _child => sub {},      _child => sub {},
541      _default => sub {      _default => sub {
542        printf "%s: session %s caught an unhandled %s event.\n",                  printf "%s #%s %s %s\n",
543          scalar localtime(), $_[SESSION]->ID, $_[ARG0];                          strftime($TIMESTAMP,localtime()), $_[SESSION]->ID, $_[ARG0],
544        print "The $_[ARG0] event was given these parameters: ",                          ref($_[ARG1]) eq "ARRAY"        ?       join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] })     :
545          join(" ", map({"ARRAY" eq ref $_ ? "[@$_]" : "$_"} @{$_[ARG1]})), "\n";                          $_[ARG1]                                        ?       $_[ARG1]                                        :
546                            "";
547        0;                        # false for signals        0;                        # false for signals
548      },      },
549      my_add => sub {      my_add => sub {
# Line 488  POE::Session->create Line 609  POE::Session->create
609     },     },
610    );    );
611    
 # 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;  
   
612  # http server  # http server
613    
614  my $httpd = POE::Component::Server::HTTP->new(  my $httpd = POE::Component::Server::HTTP->new(
# Line 560  p { margin: 0; padding: 0.1em; } Line 634  p { margin: 0; padding: 0.1em; }
634  .col-4 { background: #ff66ff }  .col-4 { background: #ff66ff }
635  a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }  a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }
636  a:hover.tag { border: 1px solid #eee }  a:hover.tag { border: 1px solid #eee }
637    hr { border: 1px dashed #ccc; height: 1px; clear: both; }
638  _END_OF_STYLE_  _END_OF_STYLE_
639    
640  my $max_color = 4;  my $max_color = 4;
# Line 583  sub root_handler { Line 658  sub root_handler {
658    
659          my $search = $q->param('search') || $q->param('grep') || '';          my $search = $q->param('search') || $q->param('grep') || '';
660    
661          $response->content(          my $html =
662                  qq{<html><head><title>$NICK</title><style type="text/css">$style} .                  qq{<html><head><title>$NICK</title><style type="text/css">$style} .
663                  $cloud->css .                  $cloud->css .
664                  qq{</style></head><body>} .                  qq{</style></head><body>} .
# Line 594  sub root_handler { Line 669  sub root_handler {
669                  </form>                  </form>
670                  } .                  } .
671                  $cloud->html(500) .                  $cloud->html(500) .
672                  qq{<p>} .                  qq{<p>};
673                  join("</p><p>",          if ($request->url =~ m#/history#) {
674                    my $sth = $dbh->prepare(qq{
675                            select date(time) as date,count(*) as nr
676                                    from log
677                                    group by date(time)
678                                    order by date(time) desc
679                    });
680                    $sth->execute();
681                    my ($l_yyyy,$l_mm) = (0,0);
682                    my $cal;
683                    while (my $row = $sth->fetchrow_hashref) {
684                            # this is probably PostgreSQL specific, expects ISO date
685                            my ($yyyy,$mm,$dd) = split(/-/, $row->{date});
686                            if ($yyyy != $l_yyyy || $mm != $l_mm) {
687                                    $html .= $cal->as_HTML() if ($cal);
688                                    $cal = new HTML::CalendarMonthSimple('month'=>$mm,'year'=>$yyyy);
689                                    $cal->border(2);
690                                    ($l_yyyy,$l_mm) = ($yyyy,$mm);
691                            }
692                            $cal->setcontent($dd, qq{
693                                    <a href="/?date=$row->{date}">$row->{nr}</a>
694                            });
695                    }
696                    $html .= $cal->as_HTML() if ($cal);
697    
698            } else {
699                    $html .= join("</p><p>",
700                          get_from_log(                          get_from_log(
701                                  limit => $q->param('last') || 100,                                  limit => $q->param('last') || $q->param('date') ? undef : 100,
702                                  search => $search || undef,                                  search => $search || undef,
703                                  tag => $q->param('tag') || undef,                                  tag => $q->param('tag') || undef,
704                                    date => $q->param('date') || undef,
705                                  fmt => {                                  fmt => {
706                                          date => '<hr size="1" style="clear: both;"/><div class="date">%s</div> ',                                          date => sub {
707                                                    my $date = shift || return;
708                                                    qq{<hr/><div class="date"><a href="/?date=$date">$date</a></div>};
709                                            },
710                                          time => '<span class="time">%s</span> ',                                          time => '<span class="time">%s</span> ',
711                                          time_channel => '<span class="channel">%s %s</span> ',                                          time_channel => '<span class="channel">%s %s</span> ',
712                                          nick => '%s:&nbsp;',                                          nick => '%s:&nbsp;',
# Line 628  sub root_handler { Line 733  sub root_handler {
733                                          },                                          },
734                                  },                                  },
735                          )                          )
736                  ) .                  );
737                  qq{</p></body></html>}          }
738          );  
739            $html .= qq{</p>
740            <hr/>
741            <p>See <a href="/history">history</a> of all messages.</p>
742            </body></html>};
743    
744            $response->content( $html );
745          return RC_OK;          return RC_OK;
746  }  }
747    

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

  ViewVC Help
Powered by ViewVC 1.1.26