/[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 75 - (hide annotations)
Thu Dec 20 22:46:16 2007 UTC (14 years, 11 months ago) by dpavlin
File MIME type: text/plain
File size: 27141 byte(s)
fixed encoding of characters in RSS stream
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 dpavlin 37 =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 dpavlin 45 =item --log=irc-logger.log
22    
23     Name of log file
24    
25     =back
26    
27 dpavlin 5 =head1 DESCRIPTION
28    
29     log all conversation on irc channel
30    
31     =cut
32    
33 dpavlin 4 ## CONFIG
34    
35 dpavlin 73 my $HOSTNAME = `hostname -f`;
36     chomp($HOSTNAME);
37 dpavlin 33
38 dpavlin 29 my $NICK = 'irc-logger';
39 dpavlin 33 $NICK .= '-dev' if ($HOSTNAME =~ m/llin/);
40 dpavlin 4 my $CONNECT =
41     {Server => 'irc.freenode.net',
42     Nick => $NICK,
43 dpavlin 8 Ircname => "try /msg $NICK help",
44 dpavlin 4 };
45     my $CHANNEL = '#razmjenavjestina';
46 dpavlin 33 $CHANNEL = '#irc-logger' if ($HOSTNAME =~ m/llin/);
47 dpavlin 4 my $IRC_ALIAS = "log";
48    
49     my %FOLLOWS =
50     (
51     ACCESS => "/var/log/apache/access.log",
52     ERROR => "/var/log/apache/error.log",
53     );
54    
55 dpavlin 19 my $DSN = 'DBI:Pg:dbname=' . $NICK;
56 dpavlin 5
57 dpavlin 14 my $ENCODING = 'ISO-8859-2';
58 dpavlin 34 my $TIMESTAMP = '%Y-%m-%d %H:%M:%S';
59 dpavlin 14
60 dpavlin 41 my $sleep_on_error = 5;
61    
62 dpavlin 70 my $http_port = $NICK =~ m/-dev/ ? 8001 : 8000;
63    
64 dpavlin 73 my $url = "http://$HOSTNAME:$http_port";
65    
66 dpavlin 4 ## END CONFIG
67    
68 dpavlin 5
69    
70 dpavlin 13 use POE qw(Component::IRC Wheel::FollowTail Component::Server::HTTP);
71     use HTTP::Status;
72 dpavlin 5 use DBI;
73 dpavlin 30 use Encode qw/from_to is_utf8/;
74 dpavlin 15 use Regexp::Common qw /URI/;
75 dpavlin 16 use CGI::Simple;
76 dpavlin 28 use HTML::TagCloud;
77 dpavlin 34 use POSIX qw/strftime/;
78 dpavlin 35 use HTML::CalendarMonthSimple;
79 dpavlin 37 use Getopt::Long;
80     use DateTime;
81 dpavlin 61 use URI::Escape;
82 dpavlin 43 use Data::Dump qw/dump/;
83 dpavlin 63 use DateTime::Format::ISO8601;
84 dpavlin 68 use Carp qw/confess/;
85 dpavlin 70 use XML::Feed;
86     use DateTime::Format::Flexible;
87 dpavlin 5
88 dpavlin 54 my $use_twitter = 1;
89     eval { require Net::Twitter; };
90     $use_twitter = 0 if ($@);
91    
92 dpavlin 37 my $import_dircproxy;
93 dpavlin 45 my $log_path;
94 dpavlin 37 GetOptions(
95     'import-dircproxy:s' => \$import_dircproxy,
96 dpavlin 45 'log:s' => \$log_path,
97 dpavlin 37 );
98    
99 dpavlin 68 $SIG{__DIE__} = sub {
100     confess "fatal error";
101     };
102    
103 dpavlin 45 open(STDOUT, '>', $log_path) || warn "can't redirect log to $log_path: $!";
104    
105     sub _log {
106     print strftime($TIMESTAMP,localtime()), ' ', join(" ",@_), $/;
107     }
108    
109 dpavlin 70 # HTML formatters
110    
111     my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');
112     my $escape_re = join '|' => keys %escape;
113    
114     my $tag_regex = '\b([\w-_]+)//';
115    
116     my %nick_enumerator;
117     my $max_color = 0;
118    
119     my $filter = {
120     message => sub {
121     my $m = shift || return;
122    
123     # protect HTML from wiki modifications
124     sub e {
125     my $t = shift;
126     return 'uri_unescape{' . uri_escape($t) . '}';
127     }
128    
129     $m =~ s/($escape_re)/$escape{$1}/gs;
130     $m =~ s#($RE{URI}{HTTP})#e(qq{<a href="$1">$1</a>})#egs ||
131     $m =~ s#\/(\w+)\/#<i>$1</i>#gs;
132 dpavlin 73 $m =~ s#$tag_regex#e(qq{<a href="$url?tag=$1" class="tag">$1</a>})#egs;
133 dpavlin 70 $m =~ s#\*(\w+)\*#<b>$1</b>#gs;
134     $m =~ s#_(\w+)_#<u>$1</u>#gs;
135    
136     $m =~ s#uri_unescape{([^}]+)}#uri_unescape($1)#egs;
137     return $m;
138     },
139     nick => sub {
140     my $n = shift || return;
141     if (! $nick_enumerator{$n}) {
142     my $max = scalar keys %nick_enumerator;
143     $nick_enumerator{$n} = $max + 1;
144     }
145     return '<span class="nick col-' .
146     ( $nick_enumerator{$n} % $max_color ) .
147     '">' . $n . '</span>';
148     },
149     };
150    
151 dpavlin 5 my $dbh = DBI->connect($DSN,"","", { RaiseError => 1, AutoCommit => 1 }) || die $DBI::errstr;
152    
153 dpavlin 50 my $sql_schema = {
154     log => '
155 dpavlin 5 create table log (
156     id serial,
157     time timestamp default now(),
158     channel text not null,
159 dpavlin 19 me boolean default false,
160 dpavlin 5 nick text not null,
161     message text not null,
162     primary key(id)
163     );
164    
165     create index log_time on log(time);
166     create index log_channel on log(channel);
167     create index log_nick on log(nick);
168 dpavlin 50 ',
169     meta => '
170     create table meta (
171     nick text not null,
172     channel text not null,
173     name text not null,
174     value text,
175     changed timestamp default now(),
176     primary key(nick,channel,name)
177     );
178     ',
179     };
180 dpavlin 5
181 dpavlin 50 foreach my $table ( keys %$sql_schema ) {
182    
183     eval {
184     $dbh->do(qq{ select count(*) from $table });
185     };
186    
187     if ($@) {
188     warn "creating database table $table in $DSN\n";
189     $dbh->do( $sql_schema->{ $table } );
190     }
191 dpavlin 19 }
192 dpavlin 5
193 dpavlin 50
194     =head2 meta
195    
196     Set or get some meta data into database
197    
198     meta('nick','channel','var_name', $var_value );
199    
200     $var_value = meta('nick','channel','var_name');
201     ( $var_value, $changed ) = meta('nick','channel','var_name');
202    
203     =cut
204    
205     sub meta {
206     my ($nick,$channel,$name,$value) = @_;
207    
208     # normalize channel name
209     $channel =~ s/^#//;
210    
211     if (defined($value)) {
212    
213     my $sth = $dbh->prepare(qq{ update meta set value = ?, changed = now() where nick = ? and channel = ? and name = ? });
214    
215     eval { $sth->execute( $value, $nick, $channel, $name ) };
216    
217     # error or no result
218     if ( $@ || ! $sth->rows ) {
219     $sth = $dbh->prepare(qq{ insert into meta (value,nick,channel,name,changed) values (?,?,?,?,now()) });
220     $sth->execute( $value, $nick, $channel, $name );
221     _log "created $nick/$channel/$name = $value";
222     } else {
223     _log "updated $nick/$channel/$name = $value ";
224     }
225    
226     return $value;
227    
228     } else {
229    
230     my $sth = $dbh->prepare(qq{ select value,changed from meta where nick = ? and channel = ? and name = ? });
231     $sth->execute( $nick, $channel, $name );
232     my ($v,$c) = $sth->fetchrow_array;
233     _log "fetched $nick/$channel/$name = $v [$c]";
234     return ($v,$c) if wantarray;
235     return $v;
236    
237     }
238     }
239    
240    
241    
242 dpavlin 5 my $sth = $dbh->prepare(qq{
243     insert into log
244 dpavlin 37 (channel, me, nick, message, time)
245     values (?,?,?,?,?)
246 dpavlin 5 });
247    
248 dpavlin 50
249 dpavlin 28 my $tags;
250    
251 dpavlin 11 =head2 get_from_log
252 dpavlin 5
253 dpavlin 11 my @messages = get_from_log(
254     limit => 42,
255     search => '%what to stuff in ilike%',
256 dpavlin 13 fmt => {
257     time => '{%s} ',
258     time_channel => '{%s %s} ',
259     nick => '%s: ',
260 dpavlin 20 me_nick => '***%s ',
261 dpavlin 13 message => '%s',
262     },
263 dpavlin 20 filter => {
264     message => sub {
265     # modify message content
266     return shift;
267     }
268 dpavlin 21 },
269     context => 5,
270 dpavlin 42 full_rows => 1,
271 dpavlin 11 );
272    
273 dpavlin 20 Order is important. Fields are first passed through C<filter> (if available) and
274     then throgh C<< sprintf($fmt->{message}, $message >> if available.
275    
276 dpavlin 21 C<context> defines number of messages around each search hit for display.
277    
278 dpavlin 42 C<full_rows> will return database rows for each result with C<date>, C<time>, C<channel>,
279     C<me>, C<nick> and C<message> keys.
280    
281 dpavlin 11 =cut
282    
283     sub get_from_log {
284     my $args = {@_};
285    
286 dpavlin 68 if ( ! $args->{fmt} ) {
287     $args->{fmt} = {
288     date => '[%s] ',
289     time => '{%s} ',
290     time_channel => '{%s %s} ',
291     nick => '%s: ',
292     me_nick => '***%s ',
293     message => '%s',
294     };
295     }
296 dpavlin 13
297 dpavlin 21 my $sql_message = qq{
298 dpavlin 11 select
299     time::date as date,
300     time::time as time,
301     channel,
302 dpavlin 20 me,
303 dpavlin 11 nick,
304     message
305     from log
306     };
307 dpavlin 21
308     my $sql_context = qq{
309     select
310     id
311     from log
312     };
313    
314     my $context = $1 if ($args->{search} && $args->{search} =~ s/\s*\+(\d+)\s*/ /);
315    
316     my $sql = $context ? $sql_context : $sql_message;
317    
318 dpavlin 67 sub check_date {
319 dpavlin 68 my $date = shift || return;
320     my $new_date = eval { DateTime::Format::ISO8601->parse_datetime( $date )->ymd; };
321 dpavlin 64 if ( $@ ) {
322 dpavlin 68 warn "invalid date $date\n";
323     $new_date = DateTime->now->ymd;
324 dpavlin 64 }
325 dpavlin 68 return $new_date;
326 dpavlin 67 }
327    
328 dpavlin 68 my @where;
329     my @args;
330    
331     if (my $search = $args->{search}) {
332     $search =~ s/^\s+//;
333     $search =~ s/\s+$//;
334     push @where, 'message ilike ? or nick ilike ?';
335     push @args, ( ( '%' . $search . '%' ) x 2 );
336     _log "search for '$search'";
337 dpavlin 63 }
338 dpavlin 68
339     if ($args->{tag} && $tags->{ $args->{tag} }) {
340     push @where, 'id in (' . join(',', @{ $tags->{ $args->{tag} } }) . ')';
341     _log "search for tags $args->{tag}";
342     }
343    
344     if (my $date = $args->{date} ) {
345     $date = check_date( $date );
346     push @where, 'date(time) = ?';
347     push @args, $date;
348     _log "search for date $date";
349     }
350    
351     $sql .= " where " . join(" and ", @where) if @where;
352    
353 dpavlin 11 $sql .= " order by log.time desc";
354 dpavlin 35 $sql .= " limit " . $args->{limit} if ($args->{limit});
355 dpavlin 11
356 dpavlin 68 #warn "### sql: $sql ", dump( @args );
357    
358 dpavlin 11 my $sth = $dbh->prepare( $sql );
359 dpavlin 69 eval { $sth->execute( @args ) };
360     return if $@;
361 dpavlin 68
362 dpavlin 11 my $last_row = {
363     date => '',
364     time => '',
365     channel => '',
366     nick => '',
367     };
368    
369     my @rows;
370    
371     while (my $row = $sth->fetchrow_hashref) {
372     unshift @rows, $row;
373     }
374    
375 dpavlin 42 # normalize nick names
376     map {
377     $_->{nick} =~ s/^_*(.*?)_*$/$1/
378     } @rows;
379    
380     return @rows if ($args->{full_rows});
381    
382 dpavlin 16 my @msgs = (
383     "Showing " . ($#rows + 1) . " messages..."
384     );
385 dpavlin 11
386 dpavlin 21 if ($context) {
387     my @ids = @rows;
388     @rows = ();
389    
390     my $last_to = 0;
391    
392     my $sth = $dbh->prepare( $sql_message . qq{ where id >= ? and id < ? } );
393     foreach my $row_id (sort { $a->{id} <=> $b->{id} } @ids) {
394     my $id = $row_id->{id} || die "can't find id in row";
395    
396     my ($from, $to) = ($id - $context, $id + $context);
397     $from = $last_to if ($from < $last_to);
398     $last_to = $to;
399     $sth->execute( $from, $to );
400    
401     #warn "## id: $id from: $from to: $to returned: ", $sth->rows, "\n";
402    
403     while (my $row = $sth->fetchrow_hashref) {
404     push @rows, $row;
405     }
406    
407     }
408     }
409    
410 dpavlin 35 # sprintf which can take coderef as first parametar
411     sub cr_sprintf {
412     my $fmt = shift || return;
413     if (ref($fmt) eq 'CODE') {
414     $fmt->(@_);
415     } else {
416     sprintf($fmt, @_);
417     }
418     }
419    
420 dpavlin 11 foreach my $row (@rows) {
421    
422     $row->{time} =~ s#\.\d+##;
423    
424     my $msg = '';
425    
426 dpavlin 35 $msg = cr_sprintf($args->{fmt}->{date}, $row->{date}) . ' ' if ($last_row->{date} ne $row->{date});
427 dpavlin 26 my $t = $row->{time};
428    
429 dpavlin 13 if ($last_row->{channel} ne $row->{channel}) {
430 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{time_channel}, $t, $row->{channel});
431 dpavlin 13 } else {
432 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{time}, $t);
433 dpavlin 13 }
434 dpavlin 11
435 dpavlin 12 my $append = 1;
436 dpavlin 11
437 dpavlin 22 my $nick = $row->{nick};
438 dpavlin 42 # if ($nick =~ s/^_*(.*?)_*$/$1/) {
439     # $row->{nick} = $nick;
440     # }
441 dpavlin 24
442 dpavlin 22 if ($last_row->{nick} ne $nick) {
443 dpavlin 20 # obfu way to find format for me_nick if needed or fallback to default
444     my $fmt = $row->{me} ? ( $args->{fmt}->{me_nick} || $args->{fmt}->{nick} ) : $args->{fmt}->{nick};
445     $fmt ||= '%s';
446    
447     $nick = $args->{filter}->{nick}->($nick) if (ref($args->{filter}->{nick}) eq 'CODE');
448    
449 dpavlin 35 $msg .= cr_sprintf( $fmt, $nick );
450 dpavlin 12 $append = 0;
451     }
452    
453 dpavlin 20 $args->{fmt}->{message} ||= '%s';
454     if (ref($args->{filter}->{message}) eq 'CODE') {
455 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{message},
456 dpavlin 20 $args->{filter}->{message}->(
457 dpavlin 15 $row->{message}
458     )
459     );
460     } else {
461 dpavlin 35 $msg .= cr_sprintf($args->{fmt}->{message}, $row->{message});
462 dpavlin 15 }
463 dpavlin 11
464 dpavlin 12 if ($append && @msgs) {
465     $msgs[$#msgs] .= " " . $msg;
466     } else {
467     push @msgs, $msg;
468     }
469 dpavlin 11
470     $last_row = $row;
471     }
472    
473     return @msgs;
474     }
475    
476 dpavlin 37 # tags support
477 dpavlin 11
478 dpavlin 37 my $cloud = HTML::TagCloud->new;
479 dpavlin 4
480 dpavlin 37 =head2 add_tag
481 dpavlin 4
482 dpavlin 70 add_tag( id => 42, message => 'irc message', nick => 'foobar' [, me => 1 ] );
483 dpavlin 37
484     =cut
485    
486 dpavlin 70 my $last_x_tags = 5;
487     my @last_tags;
488    
489 dpavlin 37 sub add_tag {
490     my $arg = {@_};
491    
492     return unless ($arg->{id} && $arg->{message});
493    
494     my $m = $arg->{message};
495     from_to('UTF-8', 'iso-8859-2', $m) if (is_utf8($m));
496    
497 dpavlin 70 my @tags;
498    
499 dpavlin 37 while ($m =~ s#$tag_regex##s) {
500     my $tag = $1;
501     next if (! $tag || $tag =~ m/https?:/i);
502     push @{ $tags->{$tag} }, $arg->{id};
503     #warn "+tag $tag: $arg->{id}\n";
504 dpavlin 73 $cloud->add($tag, "$url?tag=$tag", scalar @{$tags->{$tag}} + 1);
505 dpavlin 70 push @tags, $tag;
506    
507 dpavlin 37 }
508 dpavlin 70
509     if ( @tags ) {
510 dpavlin 74 pop @last_tags if $#last_tags == $last_x_tags;
511     unshift @last_tags, { tags => [ @tags ], %$arg };
512 dpavlin 70 }
513    
514 dpavlin 37 }
515    
516     =head2 seed_tags
517    
518     Read all tags from database and create in-memory cache for tags
519    
520     =cut
521    
522     sub seed_tags {
523 dpavlin 74 my $sth = $dbh->prepare(qq{ select id,message,nick,me,time from log where message like '%//%' order by time asc });
524 dpavlin 37 $sth->execute;
525     while (my $row = $sth->fetchrow_hashref) {
526     add_tag( %$row );
527     }
528    
529     foreach my $tag (keys %$tags) {
530 dpavlin 73 $cloud->add($tag, "$url?tag=$tag", scalar @{$tags->{$tag}} + 1);
531 dpavlin 37 }
532     }
533    
534     seed_tags;
535    
536    
537 dpavlin 36 =head2 save_message
538    
539 dpavlin 37 save_message(
540     channel => '#foobar',
541     me => 0,
542     nick => 'dpavlin',
543 dpavlin 70 message => 'test message',
544 dpavlin 37 time => '2006-06-25 18:57:18',
545     );
546 dpavlin 36
547 dpavlin 37 C<time> is optional, it will use C<< now() >> if it's not available.
548    
549     C<me> if not specified will be C<0> (not C</me> message)
550    
551 dpavlin 36 =cut
552    
553     sub save_message {
554 dpavlin 37 my $a = {@_};
555 dpavlin 70 confess "have msg" if $a->{msg};
556 dpavlin 37 $a->{me} ||= 0;
557 dpavlin 38 $a->{time} ||= strftime($TIMESTAMP,localtime());
558 dpavlin 37
559 dpavlin 45 _log
560 dpavlin 37 $a->{channel}, " ",
561     $a->{me} ? "***" . $a->{nick} : "<" . $a->{nick} . ">",
562 dpavlin 70 " " . $a->{message};
563 dpavlin 37
564 dpavlin 70 from_to($a->{message}, 'UTF-8', $ENCODING);
565 dpavlin 37
566 dpavlin 70 $sth->execute($a->{channel}, $a->{me}, $a->{nick}, $a->{message}, $a->{time});
567     add_tag( id => $dbh->last_insert_id(undef,undef,"log",undef), %$a );
568 dpavlin 36 }
569    
570 dpavlin 50
571 dpavlin 37 if ($import_dircproxy) {
572     open(my $l, $import_dircproxy) || die "can't open $import_dircproxy: $!";
573     warn "importing $import_dircproxy...\n";
574 dpavlin 69 my $tz_offset = 1 * 60 * 60; # TZ GMT+2
575 dpavlin 37 while(<$l>) {
576     chomp;
577     if (/^@(\d+)\s(\S+)\s(.+)$/) {
578     my ($time, $nick, $msg) = ($1,$2,$3);
579    
580     my $dt = DateTime->from_epoch( epoch => $time + $tz_offset );
581    
582     my $me = 0;
583     $me = 1 if ($nick =~ m/^\[\S+]/);
584     $nick =~ s/^[\[<]([^!]+).*$/$1/;
585    
586     $msg =~ s/^ACTION\s+// if ($me);
587    
588     save_message(
589     channel => $CHANNEL,
590     me => $me,
591     nick => $nick,
592 dpavlin 70 message => $msg,
593 dpavlin 37 time => $dt->ymd . " " . $dt->hms,
594     ) if ($nick !~ m/^-/);
595    
596     } else {
597 dpavlin 45 _log "can't parse: $_";
598 dpavlin 37 }
599     }
600     close($l);
601     warn "import over\n";
602     exit;
603     }
604    
605    
606     #
607     # POE handing part
608     #
609    
610     my $SKIPPING = 0; # if skipping, how many we've done
611     my $SEND_QUEUE; # cache
612 dpavlin 43 my $ping; # ping stats
613 dpavlin 37
614     POE::Component::IRC->new($IRC_ALIAS);
615    
616 dpavlin 34 POE::Session->create( inline_states =>
617 dpavlin 4 {_start => sub {
618 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => register => 'all');
619     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
620 dpavlin 4 },
621 dpavlin 9 irc_255 => sub { # server is done blabbing
622 dpavlin 7 $_[KERNEL]->post($IRC_ALIAS => join => $CHANNEL);
623     $_[KERNEL]->post($IRC_ALIAS => join => '#logger');
624     $_[KERNEL]->yield("heartbeat"); # start heartbeat
625     # $_[KERNEL]->yield("my_add", $_) for keys %FOLLOWS;
626 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
627 dpavlin 4 },
628     irc_public => sub {
629 dpavlin 7 my $kernel = $_[KERNEL];
630     my $nick = (split /!/, $_[ARG0])[0];
631     my $channel = $_[ARG1]->[0];
632     my $msg = $_[ARG2];
633 dpavlin 4
634 dpavlin 70 save_message( channel => $channel, me => 0, nick => $nick, message => $msg);
635 dpavlin 50 meta( $nick, $channel, 'last-msg', $msg );
636 dpavlin 4 },
637 dpavlin 19 irc_ctcp_action => sub {
638     my $kernel = $_[KERNEL];
639     my $nick = (split /!/, $_[ARG0])[0];
640     my $channel = $_[ARG1]->[0];
641     my $msg = $_[ARG2];
642    
643 dpavlin 70 save_message( channel => $channel, me => 1, nick => $nick, message => $msg);
644 dpavlin 50
645 dpavlin 54 if ( $use_twitter ) {
646 dpavlin 58 if ( my $twitter = meta( $nick, $NICK, 'twitter' ) ) {
647 dpavlin 54 my ($login,$passwd) = split(/\s+/,$twitter,2);
648     _log("sending twitter for $nick/$login on $channel ");
649     my $bot = Net::Twitter->new( username=>$login, password=>$passwd );
650     $bot->update("<${channel}> $msg");
651     }
652 dpavlin 50 }
653    
654 dpavlin 19 },
655 dpavlin 43 irc_ping => sub {
656     warn "pong ", $_[ARG0], $/;
657 dpavlin 48 $ping->{ $_[ARG0] }++;
658 dpavlin 43 },
659     irc_invite => sub {
660     my $kernel = $_[KERNEL];
661     my $nick = (split /!/, $_[ARG0])[0];
662     my $channel = $_[ARG1];
663    
664     warn "invited to $channel by $nick";
665    
666     $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, "how nice of you to invite me to $channel, I'll be right there..." );
667     $_[KERNEL]->post($IRC_ALIAS => join => $channel);
668    
669     },
670 dpavlin 7 irc_msg => sub {
671     my $kernel = $_[KERNEL];
672     my $nick = (split /!/, $_[ARG0])[0];
673     my $msg = $_[ARG2];
674 dpavlin 50 my $channel = $_[ARG1]->[0];
675 dpavlin 14 from_to($msg, 'UTF-8', $ENCODING);
676 dpavlin 7
677 dpavlin 8 my $res = "unknown command '$msg', try /msg $NICK help!";
678 dpavlin 11 my @out;
679 dpavlin 7
680 dpavlin 45 _log "<< $msg";
681 dpavlin 7
682 dpavlin 8 if ($msg =~ m/^help/i) {
683 dpavlin 7
684 dpavlin 11 $res = "usage: /msg $NICK comand | commands: stat - user/message stat | last - show backtrace | grep foobar - find foobar";
685 dpavlin 8
686 dpavlin 10 } elsif ($msg =~ m/^msg\s+(\S+)\s+(.*)$/i) {
687    
688 dpavlin 45 _log ">> /msg $1 $2";
689 dpavlin 10 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $1, $2 );
690     $res = '';
691    
692 dpavlin 8 } elsif ($msg =~ m/^stat.*?\s*(\d*)/i) {
693    
694 dpavlin 7 my $nr = $1 || 10;
695    
696     my $sth = $dbh->prepare(qq{
697 dpavlin 40 select
698 dpavlin 57 trim(both '_' from nick) as nick,
699 dpavlin 40 count(*) as count,
700     sum(length(message)) as len
701     from log
702 dpavlin 57 group by trim(both '_' from nick)
703 dpavlin 40 order by len desc,count desc
704     limit $nr
705 dpavlin 7 });
706     $sth->execute();
707     $res = "Top $nr users: ";
708 dpavlin 8 my @users;
709 dpavlin 7 while (my $row = $sth->fetchrow_hashref) {
710 dpavlin 40 push @users,$row->{nick} . ': ' . $row->{count} . '/' . $row->{len} . '=' . sprintf("%.2f", $row->{len}/$row->{count});
711 dpavlin 7 }
712 dpavlin 8 $res .= join(" | ", @users);
713     } elsif ($msg =~ m/^last.*?\s*(\d*)/i) {
714    
715 dpavlin 50 my $limit = $1 || meta( $nick, $channel, 'last-size' ) || 10;
716    
717     foreach my $res (get_from_log( limit => $limit )) {
718 dpavlin 45 _log "last: $res";
719 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
720 dpavlin 11 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
721 dpavlin 8 }
722    
723 dpavlin 11 $res = '';
724 dpavlin 8
725 dpavlin 21 } elsif ($msg =~ m/^(search|grep)\s+(.*)\s*$/i) {
726 dpavlin 8
727 dpavlin 11 my $what = $2;
728 dpavlin 8
729 dpavlin 21 foreach my $res (get_from_log(
730     limit => 20,
731     search => $what,
732     )) {
733 dpavlin 45 _log "search [$what]: $res";
734 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
735 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
736     }
737    
738     $res = '';
739 dpavlin 11
740 dpavlin 42 } elsif ($msg =~ m/^(?:count|poll)\s+(.*)(?:\s+(\d+))?\s*$/i) {
741    
742     my ($what,$limit) = ($1,$2);
743     $limit ||= 100;
744    
745     my $stat;
746    
747     foreach my $res (get_from_log(
748     limit => $limit,
749     search => $what,
750     full_rows => 1,
751     )) {
752     while ($res->{message} =~ s/\Q$what\E(\+|\-)//) {
753     $stat->{vote}->{$1}++;
754     $stat->{from}->{ $res->{nick} }++;
755     }
756     }
757    
758     my @nicks;
759 dpavlin 43 foreach my $nick (sort { $stat->{from}->{$a} <=> $stat->{from}->{$b} } keys %{ $stat->{from} }) {
760     push @nicks, $nick . ( $stat->{from}->{$nick} == 1 ? '' :
761     "(" . $stat->{from}->{$nick} . ")"
762     );
763 dpavlin 42 }
764    
765     $res =
766 dpavlin 43 "$what ++ " . ( $stat->{vote}->{'+'} || 0 ) .
767     " : " . ( $stat->{vote}->{'-'} || 0 ) . " --" .
768 dpavlin 42 " from " . ( join(", ", @nicks) || 'nobody' );
769    
770 dpavlin 43 $_[KERNEL]->post( $IRC_ALIAS => notice => $nick, $res );
771    
772     } elsif ($msg =~ m/^ping/) {
773     $res = "ping = " . dump( $ping );
774 dpavlin 51 } elsif ($msg =~ m/^conf(?:ig)*\s*(last-size|twitter)*\s*(.*)/) {
775 dpavlin 50 if ( ! defined( $1 ) ) {
776     my $sth = $dbh->prepare(qq{ select name,value,changed from meta where nick = ? and channel = ? });
777     $sth->execute( $nick, $channel );
778 dpavlin 52 $res = "config for $nick on $channel";
779 dpavlin 50 while ( my ($n,$v) = $sth->fetchrow_array ) {
780 dpavlin 52 $res .= " | $n = $v";
781 dpavlin 50 }
782 dpavlin 51 } elsif ( ! $2 ) {
783 dpavlin 50 my $val = meta( $nick, $channel, $1 );
784     $res = "current $1 = " . ( $val ? $val : 'undefined' );
785 dpavlin 51 } else {
786     my $validate = {
787     'last-size' => qr/^\d+/,
788     'twitter' => qr/^\w+\s+\w+/,
789     };
790    
791     my ( $op, $val ) = ( $1, $2 );
792    
793     if ( my $regex = $validate->{$op} ) {
794     if ( $val =~ $regex ) {
795     meta( $nick, $channel, $op, $val );
796     $res = "saved $op = $val";
797     } else {
798     $res = "config option $op = $val doesn't validate against $regex";
799     }
800     } else {
801     $res = "config option $op doesn't exist";
802     }
803 dpavlin 50 }
804 dpavlin 7 }
805    
806 dpavlin 8 if ($res) {
807 dpavlin 45 _log ">> [$nick] $res";
808 dpavlin 14 from_to($res, $ENCODING, 'UTF-8');
809 dpavlin 8 $_[KERNEL]->post( $IRC_ALIAS => privmsg => $nick, $res );
810     }
811 dpavlin 7
812     },
813 dpavlin 10 irc_477 => sub {
814 dpavlin 45 _log "# irc_477: ",$_[ARG1];
815 dpavlin 10 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
816     },
817 dpavlin 7 irc_505 => sub {
818 dpavlin 45 _log "# irc_505: ",$_[ARG1];
819 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "register $NICK" );
820 dpavlin 10 # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set hide email on" );
821     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "set email dpavlin\@rot13.org" );
822 dpavlin 8 },
823     irc_registered => sub {
824 dpavlin 45 _log "## registrated $NICK";
825 dpavlin 7 $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
826 dpavlin 10 },
827 dpavlin 41 irc_disconnected => sub {
828 dpavlin 45 _log "## disconnected, reconnecting again";
829 dpavlin 41 $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
830     },
831     irc_socketerr => sub {
832 dpavlin 45 _log "## socket error... sleeping for $sleep_on_error seconds and retry";
833 dpavlin 41 sleep($sleep_on_error);
834     $_[KERNEL]->post($IRC_ALIAS => connect => $CONNECT);
835     },
836 dpavlin 11 # irc_433 => sub {
837     # print "# irc_433: ",$_[ARG1], "\n";
838     # warn "## indetify $NICK\n";
839     # $_[KERNEL]->post( $IRC_ALIAS => privmsg => 'nickserv', "IDENTIFY $NICK" );
840     # },
841 dpavlin 4 _child => sub {},
842     _default => sub {
843 dpavlin 45 _log sprintf "sID:%s %s %s",
844     $_[SESSION]->ID, $_[ARG0],
845 dpavlin 34 ref($_[ARG1]) eq "ARRAY" ? join(",", map { ref($_) eq "ARRAY" ? join(";", @{$_}) : $_ } @{ $_[ARG1] }) :
846     $_[ARG1] ? $_[ARG1] :
847     "";
848 dpavlin 4 0; # false for signals
849     },
850     my_add => sub {
851     my $trailing = $_[ARG0];
852     my $session = $_[SESSION];
853     POE::Session->create
854     (inline_states =>
855     {_start => sub {
856     $_[HEAP]->{wheel} =
857     POE::Wheel::FollowTail->new
858     (
859     Filename => $FOLLOWS{$trailing},
860     InputEvent => 'got_line',
861     );
862     },
863     got_line => sub {
864     $_[KERNEL]->post($session => my_tailed =>
865     time, $trailing, $_[ARG0]);
866     },
867     },
868     );
869    
870     },
871     my_tailed => sub {
872     my ($time, $file, $line) = @_[ARG0..ARG2];
873     ## $time will be undef on a probe, or a time value if a real line
874    
875     ## PoCo::IRC has throttling built in, but no external visibility
876     ## so this is reaching "under the hood"
877     $SEND_QUEUE ||=
878     $_[KERNEL]->alias_resolve($IRC_ALIAS)->get_heap->{send_queue};
879    
880     ## handle "no need to keep skipping" transition
881     if ($SKIPPING and @$SEND_QUEUE < 1) {
882     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
883     "[discarded $SKIPPING messages]");
884     $SKIPPING = 0;
885     }
886    
887     ## handle potential message display
888     if ($time) {
889     if ($SKIPPING or @$SEND_QUEUE > 3) { # 3 msgs per 10 seconds
890     $SKIPPING++;
891     } else {
892     my @time = localtime $time;
893     $_[KERNEL]->post($IRC_ALIAS => privmsg => $CHANNEL =>
894     sprintf "%02d:%02d:%02d: %s: %s",
895     ($time[2] + 11) % 12 + 1, $time[1], $time[0],
896     $file, $line);
897     }
898     }
899    
900     ## handle re-probe/flush if skipping
901     if ($SKIPPING) {
902     $_[KERNEL]->delay($_[STATE] => 0.5); # $time will be undef
903     }
904    
905     },
906     my_heartbeat => sub {
907     $_[KERNEL]->yield(my_tailed => time, "heartbeat", "beep");
908     $_[KERNEL]->delay($_[STATE] => 10);
909     }
910     },
911     );
912    
913 dpavlin 13 # http server
914    
915     my $httpd = POE::Component::Server::HTTP->new(
916 dpavlin 70 Port => $http_port,
917 dpavlin 13 ContentHandler => { '/' => \&root_handler },
918     Headers => { Server => 'irc-logger' },
919     );
920    
921     my $style = <<'_END_OF_STYLE_';
922 dpavlin 16 p { margin: 0; padding: 0.1em; }
923 dpavlin 13 .time, .channel { color: #808080; font-size: 60%; }
924 dpavlin 28 .date { float: right; background: #e0e0e0; color: #404040; font-size: 120%; padding: 0.25em; border: 1px dashed #808080; }
925 dpavlin 20 .nick { color: #000000; font-size: 80%; padding: 2px; font-family: courier, courier new, monospace ; }
926 dpavlin 13 .message { color: #000000; font-size: 100%; }
927 dpavlin 16 .search { float: right; }
928 dpavlin 60 a:link.tag, a:visited.tag { border: 1px dashed #ccc; backgound: #ccc; text-decoration: none }
929     a:hover.tag { border: 1px solid #eee }
930     hr { border: 1px dashed #ccc; height: 1px; clear: both; }
931     /*
932 dpavlin 20 .col-0 { background: #ffff66 }
933     .col-1 { background: #a0ffff }
934     .col-2 { background: #99ff99 }
935     .col-3 { background: #ff9999 }
936     .col-4 { background: #ff66ff }
937 dpavlin 60 */
938 dpavlin 65 .calendar { border: 1px solid red; width: 100%; }
939     .month { border: 0px; width: 100%; }
940 dpavlin 13 _END_OF_STYLE_
941    
942 dpavlin 70 $max_color = 0;
943 dpavlin 20
944 dpavlin 60 my @cols = qw(
945     #ffcccc #ccffe6 #ccccff #e6ccff #ffccff #ffcce6 #ff9999 #ffcc99 #ffff99
946     #ccff99 #99ff99 #99ffcc #99ccff #9999ff #cc99ff #ff6666 #ffb366 #ffff66
947     #66ff66 #66ffb3 #66b3ff #6666ff #ff3333 #33ff33 #3399ff #3333ff #ff3399
948     #a0a0a0 #ff0000 #ffff00 #80ff00 #0000ff #8000ff #ff00ff #ff0080 #994d00
949     #999900 #009900 #cc0066 #c0c0c0 #ccff99 #99ff33 #808080 #660033 #ffffff
950     );
951    
952     foreach my $c (@cols) {
953     $style .= ".col-${max_color} { background: $c }\n";
954     $max_color++;
955     }
956     warn "defined $max_color colors for users...\n";
957    
958 dpavlin 13 sub root_handler {
959     my ($request, $response) = @_;
960     $response->code(RC_OK);
961 dpavlin 16
962 dpavlin 73 return RC_OK if $request->uri =~ m/favicon.ico$/;
963    
964 dpavlin 16 my $q;
965    
966     if ( $request->method eq 'POST' ) {
967     $q = new CGI::Simple( $request->content );
968     } elsif ( $request->uri =~ /\?(.+)$/ ) {
969     $q = new CGI::Simple( $1 );
970     } else {
971     $q = new CGI::Simple;
972     }
973    
974     my $search = $q->param('search') || $q->param('grep') || '';
975    
976 dpavlin 71 if ($request->url =~ m#/rss#i) {
977     my $type = 'RSS'; # Atom
978 dpavlin 70
979 dpavlin 72 $response->content_type( 'application/' . lc($type) . '+xml' );
980 dpavlin 70
981     my $html = '<!-- error -->';
982 dpavlin 74 #warn "create $type feed from ",dump( @last_tags );
983 dpavlin 70
984     my $feed = XML::Feed->new( $type );
985    
986     $feed->title( "last $last_x_tags from $CHANNEL" );
987 dpavlin 74 $feed->link( $url );
988 dpavlin 70 $feed->description( "collects messages which have tags// in them" );
989    
990     foreach my $m ( @last_tags ) {
991 dpavlin 73 # warn dump( $m );
992 dpavlin 70 #my $tags = join(' ', @{$m->{tags}} );
993     my $feed_entry = XML::Feed::Entry->new($type);
994     $feed_entry->title( $m->{nick} . '@' . $m->{time} );
995     $feed_entry->author( $m->{nick} );
996 dpavlin 73 $feed_entry->link( '/#' . $m->{id} );
997 dpavlin 70 $feed_entry->issued( DateTime::Format::Flexible->build( $m->{time} ) );
998 dpavlin 75
999     my $message = $filter->{message}->( $m->{message} );
1000     $message .= "<br/>\n" unless $message =~ m!<(/p|br/?)>!;
1001     warn "## message = $message\n";
1002     from_to( $message, $ENCODING, 'UTF-8' );
1003    
1004 dpavlin 73 #$feed_entry->summary(
1005     $feed_entry->content(
1006 dpavlin 75 "<![CDATA[$message]]>"
1007 dpavlin 70 );
1008 dpavlin 71 $feed_entry->category( join(', ', @{$m->{tags}}) );
1009 dpavlin 70 $feed->add_entry( $feed_entry );
1010     }
1011    
1012     $response->content( $feed->as_xml );
1013     return RC_OK;
1014     }
1015    
1016     if ( $@ ) {
1017     warn "$@";
1018     }
1019    
1020     $response->content_type("text/html; charset=$ENCODING");
1021    
1022 dpavlin 35 my $html =
1023 dpavlin 28 qq{<html><head><title>$NICK</title><style type="text/css">$style} .
1024     $cloud->css .
1025     qq{</style></head><body>} .
1026     qq{
1027 dpavlin 32 <form method="post" class="search" action="/">
1028 dpavlin 16 <input type="text" name="search" value="$search" size="10">
1029     <input type="submit" value="search">
1030     </form>
1031     } .
1032 dpavlin 31 $cloud->html(500) .
1033 dpavlin 35 qq{<p>};
1034     if ($request->url =~ m#/history#) {
1035     my $sth = $dbh->prepare(qq{
1036 dpavlin 65 select date(time) as date,count(*) as nr,sum(length(message)) as len
1037 dpavlin 35 from log
1038     group by date(time)
1039     order by date(time) desc
1040     });
1041     $sth->execute();
1042     my ($l_yyyy,$l_mm) = (0,0);
1043 dpavlin 65 $html .= qq{<table class="calendar"><tr>};
1044 dpavlin 35 my $cal;
1045 dpavlin 65 my $ord = 0;
1046 dpavlin 35 while (my $row = $sth->fetchrow_hashref) {
1047     # this is probably PostgreSQL specific, expects ISO date
1048     my ($yyyy,$mm,$dd) = split(/-/, $row->{date});
1049     if ($yyyy != $l_yyyy || $mm != $l_mm) {
1050 dpavlin 65 if ( $cal ) {
1051     $html .= qq{<td valign="top">} . $cal->as_HTML() . qq{</td>};
1052     $ord++;
1053     $html .= qq{</tr><tr>} if ( $ord % 3 == 0 );
1054     }
1055 dpavlin 35 $cal = new HTML::CalendarMonthSimple('month'=>$mm,'year'=>$yyyy);
1056 dpavlin 65 $cal->border(1);
1057     $cal->width('30%');
1058     $cal->cellheight('5em');
1059     $cal->tableclass('month');
1060     #$cal->cellclass('day');
1061     $cal->sunday('SUN');
1062     $cal->saturday('SAT');
1063     $cal->weekdays('MON','TUE','WED','THU','FRI');
1064 dpavlin 35 ($l_yyyy,$l_mm) = ($yyyy,$mm);
1065     }
1066     $cal->setcontent($dd, qq{
1067 dpavlin 73 <a href="$url?date=$row->{date}">$row->{nr}</a><br/>$row->{len}
1068 dpavlin 35 });
1069 dpavlin 65
1070 dpavlin 35 }
1071 dpavlin 65 $html .= qq{<td valign="top">} . $cal->as_HTML() . qq{</td></tr></table>};
1072 dpavlin 35
1073     } else {
1074     $html .= join("</p><p>",
1075 dpavlin 13 get_from_log(
1076 dpavlin 68 limit => ( $q->param('last') || $q->param('date') ) ? undef : 100,
1077 dpavlin 28 search => $search || undef,
1078 dpavlin 29 tag => $q->param('tag') || undef,
1079 dpavlin 68 date => $q->param('date') || undef,
1080 dpavlin 13 fmt => {
1081 dpavlin 35 date => sub {
1082     my $date = shift || return;
1083 dpavlin 73 qq{<hr/><div class="date"><a href="$url?date=$date">$date</a></div>};
1084 dpavlin 35 },
1085 dpavlin 13 time => '<span class="time">%s</span> ',
1086     time_channel => '<span class="channel">%s %s</span> ',
1087 dpavlin 20 nick => '%s:&nbsp;',
1088     me_nick => '***%s&nbsp;',
1089 dpavlin 13 message => '<span class="message">%s</span>',
1090     },
1091 dpavlin 70 filter => $filter,
1092 dpavlin 13 )
1093 dpavlin 35 );
1094     }
1095    
1096     $html .= qq{</p>
1097     <hr/>
1098     <p>See <a href="/history">history</a> of all messages.</p>
1099     </body></html>};
1100    
1101     $response->content( $html );
1102 dpavlin 74 warn "<< ", $request->method, " ", $request->uri, " created ", length($html), " bytes\n";
1103 dpavlin 13 return RC_OK;
1104     }
1105    
1106 dpavlin 4 POE::Kernel->run;

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26