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

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26