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

Annotation of /trunk/bin/irc-logger.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 20 - (hide annotations)
Tue Mar 14 17:17:53 2006 UTC (14 years, 10 months ago) by dpavlin
Original Path: trunk/irc-logger.pl
File MIME type: text/plain
File size: 12665 byte(s)
colorize nicks in web output, support for multiple filters (for now, message and nick)
1 dpavlin 4 #!/usr/bin/perl -w
2     use strict;
3     $|++;
4    
5 dpavlin 5 =head1 NAME
6    
7     irc-logger.pl
8    
9     =head1 SYNOPSIS
10    
11     ./irc-logger.pl
12    
13     =head1 DESCRIPTION
14    
15     log all conversation on irc channel
16    
17     =cut
18    
19 dpavlin 4 ## CONFIG
20    
21 dpavlin 20 my $NICK = 'irc-logger';
22 dpavlin 4 my $CONNECT =
23     {Server => 'irc.freenode.net',
24     Nick => $NICK,
25 dpavlin 8 Ircname => "try /msg $NICK help",
26 dpavlin 4 };
27     my $CHANNEL = '#razmjenavjestina';
28     my $IRC_ALIAS = "log";
29    
30     my %FOLLOWS =
31     (
32     ACCESS => "/var/log/apache/access.log",
33     ERROR => "/var/log/apache/error.log",
34     );
35    
36 dpavlin 19 my $DSN = 'DBI:Pg:dbname=' . $NICK;
37 dpavlin 5
38 dpavlin 14 my $ENCODING = 'ISO-8859-2';
39    
40 dpavlin 4 ## END CONFIG
41    
42 dpavlin 5
43    
44 dpavlin 13 use POE qw(Component::IRC Wheel::FollowTail Component::Server::HTTP);
45     use HTTP::Status;
46 dpavlin 5 use DBI;
47 dpavlin 6 use Encode qw/from_to/;
48 dpavlin 15 use Regexp::Common qw /URI/;
49 dpavlin 16 use CGI::Simple;
50 dpavlin 5
51    
52     my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
53    
54 dpavlin 19 eval {
55     $dbh->do(qq{ select count(*) from log });
56     };
57 dpavlin 5
58 dpavlin 19 if ($@) {
59     warn "creating database table in $DSN\n";
60     $dbh->do(<<'_SQL_SCHEMA_');
61    
62 dpavlin 5 create table log (
63     id serial,
64     time timestamp default now(),
65     channel text not null,
66 dpavlin 19 me boolean default false,
67 dpavlin 5 nick text not null,
68     message text not null,
69     primary key(id)
70     );
71    
72     create index log_time on log(time);
73     create index log_channel on log(channel);
74     create index log_nick on log(nick);
75    
76 dpavlin 19 _SQL_SCHEMA_
77     }
78 dpavlin 5
79     my $sth = $dbh->prepare(qq{
80     insert into log
81 dpavlin 19 (channel, me, nick, message)
82     values (?,?,?,?)
83 dpavlin 5 });
84    
85 dpavlin 11 =head2 get_from_log
86 dpavlin 5
87 dpavlin 11 my @messages = get_from_log(
88     limit => 42,
89     search => '%what to stuff in ilike%',
90 dpavlin 13 fmt => {
91     time => '{%s} ',
92     time_channel => '{%s %s} ',
93     nick => '%s: ',
94 dpavlin 20 me_nick => '***%s ',
95 dpavlin 13 message => '%s',
96     },
97 dpavlin 20 filter => {
98     message => sub {
99     # modify message content
100     return shift;
101     }
102 dpavlin 15 }
103 dpavlin 11 );
104    
105 dpavlin 20 Order is important. Fields are first passed through C<filter> (if available) and
106     then throgh C<< sprintf($fmt->{message}, $message >> if available.
107    
108 dpavlin 11 =cut
109    
110     sub get_from_log {
111     my $args = {@_};
112    
113     $args->{limit} ||= 10;
114    
115 dpavlin 13 $args->{fmt} ||= {
116     time => '{%s} ',
117     time_channel => '{%s %s} ',
118     nick => '%s: ',
119 dpavlin 20 me_nick => '***%s ',
120 dpavlin 13 message => '%s',
121     };
122    
123 dpavlin 11 my $sql = qq{
124     select
125     time::date as date,
126     time::time as time,
127     channel,
128 dpavlin 20 me,
129 dpavlin 11 nick,
130     message
131     from log
132     };
133     $sql .= " where message ilike ? " if ($args->{search});
134     $sql .= " order by log.time desc";
135     $sql .= " limit " . $args->{limit};
136    
137     my $sth = $dbh->prepare( $sql );
138     if ($args->{search}) {
139 dpavlin 17 $sth->execute( '%' . $args->{search} . '%' );
140 dpavlin 16 warn "search for '$args->{search}' returned ", $sth->rows, " results\n";
141 dpavlin 11 } else {
142     $sth->execute();
143     }
144     my $last_row = {
145     date => '',
146     time => '',
147     channel => '',
148     nick => '',
149     };
150    
151     my @rows;
152    
153     while (my $row = $sth->fetchrow_hashref) {
154     unshift @rows, $row;
155     }
156    
157 dpavlin 16 my @msgs = (
158     "Showing " . ($#rows + 1) . " messages..."
159     );
160 dpavlin 11
161     foreach my $row (@rows) {
162    
163     $row->{time} =~ s#\.\d+##;
164    
165     my $t;
166     $t = $row->{date} . ' ' if ($last_row->{date} ne $row->{date});
167     $t .= $row->{time};
168    
169     my $msg = '';
170    
171 dpavlin 13 if ($last_row->{channel} ne $row->{channel}) {
172     $msg .= sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});
173     } else {
174     $msg .= sprintf($args->{fmt}->{time}, $t);
175     }
176 dpavlin 11
177 dpavlin 12 my $append = 1;
178 dpavlin 11
179 dpavlin 12 if ($last_row->{nick} ne $row->{nick}) {
180 dpavlin 20 # obfu way to find format for me_nick if needed or fallback to default
181     my $fmt = $row->{me} ? ( $args->{fmt}->{me_nick} || $args->{fmt}->{nick} ) : $args->{fmt}->{nick};
182     $fmt ||= '%s';
183    
184     my $nick = $row->{nick};
185     $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');
186    
187     $msg .= sprintf( $fmt, $nick );
188 dpavlin 12 $append = 0;
189     }
190    
191 dpavlin 20 $args->{fmt}->{message} ||= '%s';
192     if (ref($args->{filter}->{message}) eq 'CODE') {
193 dpavlin 15 $msg .= sprintf($args->{fmt}->{message},
194 dpavlin 20 $args->{filter}->{message}->(
195 dpavlin 15 $row->{message}
196     )
197     );
198     } else {
199     $msg .= sprintf($args->{fmt}->{message}, $row->{message});
200     }
201 dpavlin 11
202 dpavlin 12 if ($append && @msgs) {
203     $msgs[$#msgs] .= " " . $msg;
204     } else {
205     push @msgs, $msg;
206     }
207 dpavlin 11
208     $last_row = $row;
209     }
210    
211     return @msgs;
212     }
213    
214    
215 dpavlin 4 my $SKIPPING = 0; # if skipping, how many we've done
216     my $SEND_QUEUE; # cache
217    
218     POE::Component::IRC->new($IRC_ALIAS);
219    
220     POE::Session->create
221     (inline_states =>
222     {_start => sub {
223 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => register => 'all');
224     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
225 dpavlin 4 },
226 dpavlin 9 irc_255 => sub { # server is done blabbing
227 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => join => $CHANNEL);
228     $_[KERNEL]->post($IRC_ALIAS => join => '#logger');
229     $_[KERNEL]->yield("heartbeat"); # start heartbeat
230     # $_[KERNEL]->yield("my_add", $_) for keys %FOLLOWS;
231 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
232 dpavlin 4 },
233     irc_public => sub {
234 dpavlin 7 my $kernel = $_[KERNEL];
235     my $nick = (split /!/, $_[ARG0])[0];
236     my $channel = $_[ARG1]->[0];
237     my $msg = $_[ARG2];
238 dpavlin 4
239 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
240 dpavlin 6
241 dpavlin 7 print "$channel: <$nick> $msg\n";
242 dpavlin 19 $sth->execute($channel, 0, $nick, $msg);
243 dpavlin 4 },
244 dpavlin 19 irc_ctcp_action => sub {
245     my $kernel = $_[KERNEL];
246     my $nick = (split /!/, $_[ARG0])[0];
247     my $channel = $_[ARG1]->[0];
248     my $msg = $_[ARG2];
249    
250     from_to($msg, 'UTF-8', $ENCODING);
251    
252     print "$channel ***$nick $msg\n";
253     $sth->execute($channel, 1, $nick, $msg);
254     },
255 dpavlin 7 irc_msg => sub {
256     my $kernel = $_[KERNEL];
257     my $nick = (split /!/, $_[ARG0])[0];
258     my $msg = $_[ARG2];
259 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
260 dpavlin 7
261 dpavlin 8 my $res = "unknown command '$msg', try /msg $NICK help!";
262 dpavlin 11 my @out;
263 dpavlin 7
264     print "<< $msg\n";
265    
266 dpavlin 8 if ($msg =~ m/^help/i) {
267 dpavlin 7
268 dpavlin 11 $res = "usage: /msg $NICK comand | commands: stat - user/message stat | last - show backtrace | grep foobar - find foobar";
269 dpavlin 8
270 dpavlin 10 } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
271    
272     print ">> /msg $1 $2\n";
273     $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
274     $res = '';
275    
276 dpavlin 8 } elsif ($msg =~ m/^stat.*?\s*(\d*)/i) {
277    
278 dpavlin 7 my $nr = $1 || 10;
279    
280     my $sth = $dbh->prepare(qq{
281     select nick,count(*) from log group by nick order by count desc limit $nr
282     });
283     $sth->execute();
284     $res = "Top $nr users: ";
285 dpavlin 8 my @users;
286 dpavlin 7 while (my $row = $sth->fetchrow_hashref) {
287 dpavlin 8 push @users,$row->{nick} . ': ' . $row->{count};
288 dpavlin 7 }
289 dpavlin 8 $res .= join(" | ", @users);
290     } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
291    
292 dpavlin 11 foreach my $res (get_from_log( limit => $1 )) {
293     print "last: $res\n";
294 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
295 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
296 dpavlin 8 }
297    
298 dpavlin 11 $res = '';
299 dpavlin 8
300 dpavlin 11 } elsif ($msg =~ m/^(search|grep)\s+(.*)$/i) {
301 dpavlin 8
302 dpavlin 11 my $what = $2;
303 dpavlin 8
304 dpavlin 16 foreach my $res (get_from_log( limit => 20, search => $what )) {
305 dpavlin 11 print "search [$what]: $res\n";
306 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
307 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
308     }
309    
310     $res = '';
311 dpavlin 11
312 dpavlin 7 }
313    
314 dpavlin 8 if ($res) {
315     print ">> [$nick] $res\n";
316 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
317 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
318     }
319 dpavlin 7
320     },
321 dpavlin 10 irc_477 => sub {
322     print "# irc_477: ",$_[ARG1], "\n";
323     $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
324     },
325 dpavlin 7 irc_505 => sub {
326 dpavlin 10 print "# irc_505: ",$_[ARG1], "\n";
327 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
328 dpavlin 10 # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
329     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
330 dpavlin 8 },
331     irc_registered => sub {
332 dpavlin 10 warn "## indetify $NICK\n";
333 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
334 dpavlin 10 },
335 dpavlin 11 # irc_433 => sub {
336     # print "# irc_433: ",$_[ARG1], "\n";
337     # warn "## indetify $NICK\n";
338     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
339     # },
340 dpavlin 10 irc_372 => sub {
341     print "MOTD: ", $_[ARG1], "\n";
342     },
343     irc_snotice => sub {
344     print "(server notice): ", $_[ARG0], "\n";
345     },
346 dpavlin 4 (map
347     {
348     ;"irc_$_" => sub { }}
349 dpavlin 10 qw(
350 dpavlin 5 )),
351 dpavlin 10 # join
352     # ctcp_version
353     # connected snotice ctcp_action ping notice mode part quit
354     # 001 002 003 004 005
355     # 250 251 252 253 254 265 266
356     # 332 333 353 366 372 375 376
357     # 477
358 dpavlin 4 _child => sub {},
359     _default => sub {
360     printf "%s: session %s caught an unhandled %s event.\n",
361     scalar localtime(), $_[SESSION]->ID, $_[ARG0];
362     print "The $_[ARG0] event was given these parameters: ",
363     join(" ", map({"ARRAY" eq ref $_ ? "[@$_]" : "$_"} @{$_[ARG1]})), "\n";
364     0; # false for signals
365     },
366     my_add => sub {
367     my $trailing = $_[ARG0];
368     my $session = $_[SESSION];
369     POE::Session->create
370     (inline_states =>
371     {_start => sub {
372     $_[HEAP]->{wheel} =
373     POE::Wheel::FollowTail->new
374     (
375     Filename => $FOLLOWS{$trailing},
376     InputEvent => 'got_line',
377     );
378     },
379     got_line => sub {
380     $_[KERNEL]->post($session => my_tailed =>
381     time, $trailing, $_[ARG0]);
382     },
383     },
384     );
385    
386     },
387     my_tailed => sub {
388     my ($time, $file, $line) = @_[ARG0..ARG2];
389     ## $time will be undef on a probe, or a time value if a real line
390    
391     ## PoCo::IRC has throttling built in, but no external visibility
392     ## so this is reaching "under the hood"
393     $SEND_QUEUE ||=
394     $_[KERNEL]->alias_resolve($IRC_ALIAS)->get_heap->{send_queue};
395    
396     ## handle "no need to keep skipping" transition
397     if ($SKIPPING and @$SEND_QUEUE < 1) {
398     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
399     "[discarded $SKIPPING messages]");
400     $SKIPPING = 0;
401     }
402    
403     ## handle potential message display
404     if ($time) {
405     if ($SKIPPING or @$SEND_QUEUE > 3) { # 3 msgs per 10 seconds
406     $SKIPPING++;
407     } else {
408     my @time = localtime $time;
409     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
410     sprintf "%02d:%02d:%02d: %s: %s",
411     ($time[2] + 11) % 12 + 1, $time[1], $time[0],
412     $file, $line);
413     }
414     }
415    
416     ## handle re-probe/flush if skipping
417     if ($SKIPPING) {
418     $_[KERNEL]->delay($_[STATE] => 0.5); # $time will be undef
419     }
420    
421     },
422     my_heartbeat => sub {
423     $_[KERNEL]->yield(my_tailed => time, "heartbeat", "beep");
424     $_[KERNEL]->delay($_[STATE] => 10);
425     }
426     },
427     );
428    
429 dpavlin 13 # http server
430    
431     my $httpd = POE::Component::Server::HTTP->new(
432 dpavlin 14 Port => $NICK =~ m/-dev/ ? 8001 : 8000,
433 dpavlin 13 ContentHandler => { '/' => \&root_handler },
434     Headers => { Server => 'irc-logger' },
435     );
436    
437 dpavlin 18 my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
438     my $escape_re = join '|' => keys %escape;
439    
440 dpavlin 13 my $style = <<'_END_OF_STYLE_';
441 dpavlin 16 p { margin: 0; padding: 0.1em; }
442 dpavlin 13 .time, .channel { color: #808080; font-size: 60%; }
443 dpavlin 20 .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }
444 dpavlin 13 .message { color: #000000; font-size: 100%; }
445 dpavlin 16 .search { float: right; }
446 dpavlin 20 .col-0 { background: #ffff66 }
447     .col-1 { background: #a0ffff }
448     .col-2 { background: #99ff99 }
449     .col-3 { background: #ff9999 }
450     .col-4 { background: #ff66ff }
451 dpavlin 13 _END_OF_STYLE_
452    
453 dpavlin 20 my $max_color = 4;
454    
455     my %nick_enumerator;
456    
457 dpavlin 13 sub root_handler {
458     my ($request, $response) = @_;
459     $response->code(RC_OK);
460 dpavlin 14 $response->content_type("text/html; charset=$ENCODING");
461 dpavlin 16
462     my $q;
463    
464     if ( $request->method eq 'POST' ) {
465     $q = new CGI::Simple( $request->content );
466     } elsif ( $request->uri =~ /\?(.+)$/ ) {
467     $q = new CGI::Simple( $1 );
468     } else {
469     $q = new CGI::Simple;
470     }
471    
472     my $search = $q->param('search') || $q->param('grep') || '';
473    
474 dpavlin 13 $response->content(
475 dpavlin 16 qq{<html><head><title>$NICK</title><style type="text/css">$style</style></head><body>
476     <form method="post" class="search">
477     <input type="text" name="search" value="$search" size="10">
478     <input type="submit" value="search">
479     </form>
480     <p>
481     } .
482     join("</p><p>",
483 dpavlin 13 get_from_log(
484 dpavlin 16 limit => $q->param('limit') || 100,
485     search => $q->param('search') || $q->param('grep') || undef,
486 dpavlin 13 fmt => {
487     time => '<span class="time">%s</span> ',
488     time_channel => '<span class="channel">%s %s</span> ',
489 dpavlin 20 nick => '%s:&nbsp;',
490     me_nick => '***%s&nbsp;',
491 dpavlin 13 message => '<span class="message">%s</span>',
492     },
493 dpavlin 20 filter => {
494     message => sub {
495     my $m = shift || return;
496     $m =~ s/($escape_re)/$escape{$1}/gs;
497     $m =~ s#($RE{URI}{HTTP})#<a href="$1">$1</a>#gs;
498     return $m;
499     },
500     nick => sub {
501     my $n = shift || return;
502     if (! $nick_enumerator{$n}) {
503     my $max = scalar keys %nick_enumerator;
504     $nick_enumerator{$n} = $max + 1;
505     }
506     return '<span class="nick col-' .
507     ( $nick_enumerator{$n} % $max_color ) .
508     '">' . $n . '</span>';
509     },
510 dpavlin 15 },
511 dpavlin 13 )
512     ) .
513 dpavlin 16 qq{</p></body></html>}
514 dpavlin 13 );
515     return RC_OK;
516     }
517    
518 dpavlin 4 POE::Kernel->run;

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26