/[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 21 - (hide annotations)
Sat Mar 18 16:02:32 2006 UTC (14 years, 10 months ago) by dpavlin
Original Path: trunk/irc-logger.pl
File MIME type: text/plain
File size: 13611 byte(s)
implemented context search using +number in search string

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 21 my $NICK = 'irc-logger-dev';
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 21 },
103     context => 5,
104 dpavlin 11 );
105    
106 dpavlin 20 Order is important. Fields are first passed through C<filter> (if available) and
107     then throgh C<< sprintf($fmt->{message}, $message >> if available.
108    
109 dpavlin 21 C<context> defines number of messages around each search hit for display.
110    
111 dpavlin 11 =cut
112    
113     sub get_from_log {
114     my $args = {@_};
115    
116     $args->{limit} ||= 10;
117    
118 dpavlin 13 $args->{fmt} ||= {
119     time => '{%s} ',
120     time_channel => '{%s %s} ',
121     nick => '%s: ',
122 dpavlin 20 me_nick => '***%s ',
123 dpavlin 13 message => '%s',
124     };
125    
126 dpavlin 21 my $sql_message = qq{
127 dpavlin 11 select
128     time::date as date,
129     time::time as time,
130     channel,
131 dpavlin 20 me,
132 dpavlin 11 nick,
133     message
134     from log
135     };
136 dpavlin 21
137     my $sql_context = qq{
138     select
139     id
140     from log
141     };
142    
143     my $context = $1 if ($args->{search} && $args->{search} =~ s/\s*\+(\d+)\s*/ /);
144    
145     my $sql = $context ? $sql_context : $sql_message;
146    
147 dpavlin 11 $sql .= " where message ilike ? " if ($args->{search});
148     $sql .= " order by log.time desc";
149     $sql .= " limit " . $args->{limit};
150    
151     my $sth = $dbh->prepare( $sql );
152 dpavlin 21 if (my $search = $args->{search}) {
153     $search =~ s/^\s+//;
154     $search =~ s/\s+$//;
155     $sth->execute( '%' . $search . '%' );
156     warn "search for '$search' returned ", $sth->rows, " results ", $context || '', "\n";
157 dpavlin 11 } else {
158     $sth->execute();
159     }
160     my $last_row = {
161     date => '',
162     time => '',
163     channel => '',
164     nick => '',
165     };
166    
167     my @rows;
168    
169     while (my $row = $sth->fetchrow_hashref) {
170     unshift @rows, $row;
171     }
172    
173 dpavlin 16 my @msgs = (
174     "Showing " . ($#rows + 1) . " messages..."
175     );
176 dpavlin 11
177 dpavlin 21 if ($context) {
178     my @ids = @rows;
179     @rows = ();
180    
181     my $last_to = 0;
182    
183     my $sth = $dbh->prepare( $sql_message . qq{ where id >= ? and id < ? } );
184     foreach my $row_id (sort { $a->{id} <=> $b->{id} } @ids) {
185     my $id = $row_id->{id} || die "can't find id in row";
186    
187     my ($from, $to) = ($id - $context, $id + $context);
188     $from = $last_to if ($from < $last_to);
189     $last_to = $to;
190     $sth->execute( $from, $to );
191    
192     #warn "## id: $id from: $from to: $to returned: ", $sth->rows, "\n";
193    
194     while (my $row = $sth->fetchrow_hashref) {
195     push @rows, $row;
196     }
197    
198     }
199     }
200    
201 dpavlin 11 foreach my $row (@rows) {
202    
203     $row->{time} =~ s#\.\d+##;
204    
205     my $t;
206     $t = $row->{date} . ' ' if ($last_row->{date} ne $row->{date});
207     $t .= $row->{time};
208    
209     my $msg = '';
210    
211 dpavlin 13 if ($last_row->{channel} ne $row->{channel}) {
212     $msg .= sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});
213     } else {
214     $msg .= sprintf($args->{fmt}->{time}, $t);
215     }
216 dpavlin 11
217 dpavlin 12 my $append = 1;
218 dpavlin 11
219 dpavlin 12 if ($last_row->{nick} ne $row->{nick}) {
220 dpavlin 20 # obfu way to find format for me_nick if needed or fallback to default
221     my $fmt = $row->{me} ? ( $args->{fmt}->{me_nick} || $args->{fmt}->{nick} ) : $args->{fmt}->{nick};
222     $fmt ||= '%s';
223    
224     my $nick = $row->{nick};
225     $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');
226    
227     $msg .= sprintf( $fmt, $nick );
228 dpavlin 12 $append = 0;
229     }
230    
231 dpavlin 20 $args->{fmt}->{message} ||= '%s';
232     if (ref($args->{filter}->{message}) eq 'CODE') {
233 dpavlin 15 $msg .= sprintf($args->{fmt}->{message},
234 dpavlin 20 $args->{filter}->{message}->(
235 dpavlin 15 $row->{message}
236     )
237     );
238     } else {
239     $msg .= sprintf($args->{fmt}->{message}, $row->{message});
240     }
241 dpavlin 11
242 dpavlin 12 if ($append && @msgs) {
243     $msgs[$#msgs] .= " " . $msg;
244     } else {
245     push @msgs, $msg;
246     }
247 dpavlin 11
248     $last_row = $row;
249     }
250    
251     return @msgs;
252     }
253    
254    
255 dpavlin 4 my $SKIPPING = 0; # if skipping, how many we've done
256     my $SEND_QUEUE; # cache
257    
258     POE::Component::IRC->new($IRC_ALIAS);
259    
260     POE::Session->create
261     (inline_states =>
262     {_start => sub {
263 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => register => 'all');
264     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
265 dpavlin 4 },
266 dpavlin 9 irc_255 => sub { # server is done blabbing
267 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => join => $CHANNEL);
268     $_[KERNEL]->post($IRC_ALIAS => join => '#logger');
269     $_[KERNEL]->yield("heartbeat"); # start heartbeat
270     # $_[KERNEL]->yield("my_add", $_) for keys %FOLLOWS;
271 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
272 dpavlin 4 },
273     irc_public => sub {
274 dpavlin 7 my $kernel = $_[KERNEL];
275     my $nick = (split /!/, $_[ARG0])[0];
276     my $channel = $_[ARG1]->[0];
277     my $msg = $_[ARG2];
278 dpavlin 4
279 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
280 dpavlin 6
281 dpavlin 7 print "$channel: <$nick> $msg\n";
282 dpavlin 19 $sth->execute($channel, 0, $nick, $msg);
283 dpavlin 4 },
284 dpavlin 19 irc_ctcp_action => sub {
285     my $kernel = $_[KERNEL];
286     my $nick = (split /!/, $_[ARG0])[0];
287     my $channel = $_[ARG1]->[0];
288     my $msg = $_[ARG2];
289    
290     from_to($msg, 'UTF-8', $ENCODING);
291    
292     print "$channel ***$nick $msg\n";
293     $sth->execute($channel, 1, $nick, $msg);
294     },
295 dpavlin 7 irc_msg => sub {
296     my $kernel = $_[KERNEL];
297     my $nick = (split /!/, $_[ARG0])[0];
298     my $msg = $_[ARG2];
299 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
300 dpavlin 7
301 dpavlin 8 my $res = "unknown command '$msg', try /msg $NICK help!";
302 dpavlin 11 my @out;
303 dpavlin 7
304     print "<< $msg\n";
305    
306 dpavlin 8 if ($msg =~ m/^help/i) {
307 dpavlin 7
308 dpavlin 11 $res = "usage: /msg $NICK comand | commands: stat - user/message stat | last - show backtrace | grep foobar - find foobar";
309 dpavlin 8
310 dpavlin 10 } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
311    
312     print ">> /msg $1 $2\n";
313     $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
314     $res = '';
315    
316 dpavlin 8 } elsif ($msg =~ m/^stat.*?\s*(\d*)/i) {
317    
318 dpavlin 7 my $nr = $1 || 10;
319    
320     my $sth = $dbh->prepare(qq{
321     select nick,count(*) from log group by nick order by count desc limit $nr
322     });
323     $sth->execute();
324     $res = "Top $nr users: ";
325 dpavlin 8 my @users;
326 dpavlin 7 while (my $row = $sth->fetchrow_hashref) {
327 dpavlin 8 push @users,$row->{nick} . ': ' . $row->{count};
328 dpavlin 7 }
329 dpavlin 8 $res .= join(" | ", @users);
330     } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
331    
332 dpavlin 11 foreach my $res (get_from_log( limit => $1 )) {
333     print "last: $res\n";
334 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
335 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
336 dpavlin 8 }
337    
338 dpavlin 11 $res = '';
339 dpavlin 8
340 dpavlin 21 } elsif ($msg =~ m/^(search|grep)\s+(.*)\s*$/i) {
341 dpavlin 8
342 dpavlin 11 my $what = $2;
343 dpavlin 8
344 dpavlin 21 foreach my $res (get_from_log(
345     limit => 20,
346     search => $what,
347     )) {
348 dpavlin 11 print "search [$what]: $res\n";
349 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
350 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
351     }
352    
353     $res = '';
354 dpavlin 11
355 dpavlin 7 }
356    
357 dpavlin 8 if ($res) {
358     print ">> [$nick] $res\n";
359 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
360 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
361     }
362 dpavlin 7
363     },
364 dpavlin 10 irc_477 => sub {
365     print "# irc_477: ",$_[ARG1], "\n";
366     $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
367     },
368 dpavlin 7 irc_505 => sub {
369 dpavlin 10 print "# irc_505: ",$_[ARG1], "\n";
370 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
371 dpavlin 10 # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
372     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
373 dpavlin 8 },
374     irc_registered => sub {
375 dpavlin 10 warn "## indetify $NICK\n";
376 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
377 dpavlin 10 },
378 dpavlin 11 # irc_433 => sub {
379     # print "# irc_433: ",$_[ARG1], "\n";
380     # warn "## indetify $NICK\n";
381     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
382     # },
383 dpavlin 10 irc_372 => sub {
384     print "MOTD: ", $_[ARG1], "\n";
385     },
386     irc_snotice => sub {
387     print "(server notice): ", $_[ARG0], "\n";
388     },
389 dpavlin 4 (map
390     {
391     ;"irc_$_" => sub { }}
392 dpavlin 10 qw(
393 dpavlin 5 )),
394 dpavlin 10 # join
395     # ctcp_version
396     # connected snotice ctcp_action ping notice mode part quit
397     # 001 002 003 004 005
398     # 250 251 252 253 254 265 266
399     # 332 333 353 366 372 375 376
400     # 477
401 dpavlin 4 _child => sub {},
402     _default => sub {
403     printf "%s: session %s caught an unhandled %s event.\n",
404     scalar localtime(), $_[SESSION]->ID, $_[ARG0];
405     print "The $_[ARG0] event was given these parameters: ",
406     join(" ", map({"ARRAY" eq ref $_ ? "[@$_]" : "$_"} @{$_[ARG1]})), "\n";
407     0; # false for signals
408     },
409     my_add => sub {
410     my $trailing = $_[ARG0];
411     my $session = $_[SESSION];
412     POE::Session->create
413     (inline_states =>
414     {_start => sub {
415     $_[HEAP]->{wheel} =
416     POE::Wheel::FollowTail->new
417     (
418     Filename => $FOLLOWS{$trailing},
419     InputEvent => 'got_line',
420     );
421     },
422     got_line => sub {
423     $_[KERNEL]->post($session => my_tailed =>
424     time, $trailing, $_[ARG0]);
425     },
426     },
427     );
428    
429     },
430     my_tailed => sub {
431     my ($time, $file, $line) = @_[ARG0..ARG2];
432     ## $time will be undef on a probe, or a time value if a real line
433    
434     ## PoCo::IRC has throttling built in, but no external visibility
435     ## so this is reaching "under the hood"
436     $SEND_QUEUE ||=
437     $_[KERNEL]->alias_resolve($IRC_ALIAS)->get_heap->{send_queue};
438    
439     ## handle "no need to keep skipping" transition
440     if ($SKIPPING and @$SEND_QUEUE < 1) {
441     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
442     "[discarded $SKIPPING messages]");
443     $SKIPPING = 0;
444     }
445    
446     ## handle potential message display
447     if ($time) {
448     if ($SKIPPING or @$SEND_QUEUE > 3) { # 3 msgs per 10 seconds
449     $SKIPPING++;
450     } else {
451     my @time = localtime $time;
452     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
453     sprintf "%02d:%02d:%02d: %s: %s",
454     ($time[2] + 11) % 12 + 1, $time[1], $time[0],
455     $file, $line);
456     }
457     }
458    
459     ## handle re-probe/flush if skipping
460     if ($SKIPPING) {
461     $_[KERNEL]->delay($_[STATE] => 0.5); # $time will be undef
462     }
463    
464     },
465     my_heartbeat => sub {
466     $_[KERNEL]->yield(my_tailed => time, "heartbeat", "beep");
467     $_[KERNEL]->delay($_[STATE] => 10);
468     }
469     },
470     );
471    
472 dpavlin 13 # http server
473    
474     my $httpd = POE::Component::Server::HTTP->new(
475 dpavlin 14 Port => $NICK =~ m/-dev/ ? 8001 : 8000,
476 dpavlin 13 ContentHandler => { '/' => \&root_handler },
477     Headers => { Server => 'irc-logger' },
478     );
479    
480 dpavlin 18 my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
481     my $escape_re = join '|' => keys %escape;
482    
483 dpavlin 13 my $style = <<'_END_OF_STYLE_';
484 dpavlin 16 p { margin: 0; padding: 0.1em; }
485 dpavlin 13 .time, .channel { color: #808080; font-size: 60%; }
486 dpavlin 20 .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }
487 dpavlin 13 .message { color: #000000; font-size: 100%; }
488 dpavlin 16 .search { float: right; }
489 dpavlin 20 .col-0 { background: #ffff66 }
490     .col-1 { background: #a0ffff }
491     .col-2 { background: #99ff99 }
492     .col-3 { background: #ff9999 }
493     .col-4 { background: #ff66ff }
494 dpavlin 13 _END_OF_STYLE_
495    
496 dpavlin 20 my $max_color = 4;
497    
498     my %nick_enumerator;
499    
500 dpavlin 13 sub root_handler {
501     my ($request, $response) = @_;
502     $response->code(RC_OK);
503 dpavlin 14 $response->content_type("text/html; charset=$ENCODING");
504 dpavlin 16
505     my $q;
506    
507     if ( $request->method eq 'POST' ) {
508     $q = new CGI::Simple( $request->content );
509     } elsif ( $request->uri =~ /\?(.+)$/ ) {
510     $q = new CGI::Simple( $1 );
511     } else {
512     $q = new CGI::Simple;
513     }
514    
515     my $search = $q->param('search') || $q->param('grep') || '';
516    
517 dpavlin 13 $response->content(
518 dpavlin 16 qq{<html><head><title>$NICK</title><style type="text/css">$style</style></head><body>
519     <form method="post" class="search">
520     <input type="text" name="search" value="$search" size="10">
521     <input type="submit" value="search">
522     </form>
523     <p>
524     } .
525     join("</p><p>",
526 dpavlin 13 get_from_log(
527 dpavlin 16 limit => $q->param('limit') || 100,
528     search => $q->param('search') || $q->param('grep') || undef,
529 dpavlin 13 fmt => {
530     time => '<span class="time">%s</span> ',
531     time_channel => '<span class="channel">%s %s</span> ',
532 dpavlin 20 nick => '%s:&nbsp;',
533     me_nick => '***%s&nbsp;',
534 dpavlin 13 message => '<span class="message">%s</span>',
535     },
536 dpavlin 20 filter => {
537     message => sub {
538     my $m = shift || return;
539     $m =~ s/($escape_re)/$escape{$1}/gs;
540     $m =~ s#($RE{URI}{HTTP})#<a href="$1">$1</a>#gs;
541     return $m;
542     },
543     nick => sub {
544     my $n = shift || return;
545     if (! $nick_enumerator{$n}) {
546     my $max = scalar keys %nick_enumerator;
547     $nick_enumerator{$n} = $max + 1;
548     }
549     return '<span class="nick col-' .
550     ( $nick_enumerator{$n} % $max_color ) .
551     '">' . $n . '</span>';
552     },
553 dpavlin 15 },
554 dpavlin 13 )
555     ) .
556 dpavlin 16 qq{</p></body></html>}
557 dpavlin 13 );
558     return RC_OK;
559     }
560    
561 dpavlin 4 POE::Kernel->run;

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26