blib/lib/Horris/Connection/Plugin/Poller.pm untested

filter: Statementstmt 0.0% 0 / 64 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 91 CC 7 SCAR 27.1
CC
7
Cov
0%
on_connect
30.0
irc_privmsg
12.0
on_disconnect
2.0
CRAP 15.1
1 package Horris::Connection::Plugin::Poller;
2 # ABSTRACT: Poller Plugin on Horris
3  
4 use Moose;
5 use DBI;
6 use Data::Dumper;
7 extends 'Horris::Connection::Plugin';
8 with 'MooseX::Role::Pluggable::Plugin';
9  
10 use constant {
11 ROWID => 0,
12 MSG_ID => 1,
13 TIME => 2,
14 SEND => 3,
15 MSG => 4,
16 };
17  
18 has channel => (
19 is => 'ro',
20 isa => 'HashRef',
21 );
22  
23 has dbfile => (
24 is => 'ro',
25 isa => 'Str',
26 required => 1,
27 );
28  
29 has '+is_enable' => (
30 default => 0
31 );
32  
33 my $w;
34 my $dbh;
35 my $sth_select;
36 my $sth_update;
37 my $interval = 3;
38  
39 sub on_connect {
40  
41 warn __PACKAGE__ . " on_connect\n";
42  
43 my ($self) = @_;
44  
45 # create table messages (msg_id text, time int, send int, msg text);
46  
47 my $current_time = scalar time;
48  
49 my $dbfile = $self->dbfile;
50 $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile", "", "");
51 $sth_select = $dbh->prepare("SELECT rowid, msg_id, time, send, msg FROM messages WHERE send=0 and time > $current_time");
52 $sth_update = $dbh->prepare("UPDATE messages SET send=1 WHERE rowid=?");
53  
54 # Polling $self->dbfile every $interval secs.
55 $w = AnyEvent->timer(
56 after => 10,
57 interval => $interval,
58 cb => sub {
59  
60 my %anti_excess;
61  
62 # select messages to say
63 $sth_select->execute;
64 foreach my $row (@{ $sth_select->fetchall_arrayref }) {
65  
66 warn sprintf '[%s] Poller : %s', $self->is_enable ? 'on' : 'off', join(", ", @$row);
67  
68 if($self->is_enable) {
69 foreach my $channel (keys %{ $self->channel }) {
70 for my $feed (@{ $self->channel->{$channel}->{feed} }) {
71  
72 if($row->[MSG_ID] eq $feed) {
73  
74 # drop '\' from channel name
75 my $cname = substr $channel, 1;
76  
77 $self->connection->irc_privmsg({
78 channel => $cname,
79 message => $row->[MSG],
80 });
81  
82 if($anti_excess{ scalar time }++ > 3) {
83 print Dumper(\%anti_excess);
84 sleep 5;
85 }
86 }
87  
88 }
89 }
90 }
91  
92 $sth_update->execute($row->[ROWID]);
93 }
94 },
95 );
96  
97 $self->pass;
98 }
99  
100 sub on_disconnect {
101 undef $w;
102 undef $sth_select;
103 undef $sth_update;
104 undef $dbh;
105 }
106  
107 sub irc_privmsg {
108 my ($self, $message) = @_;
109 my $msg = $message->message;
110 my $botname = $self->connection->nickname;
111 my ($cmd) = $msg =~ m/^$botname\S*\s+(\w+)/;
112
113 if (defined $cmd and lc $cmd eq 'feed') {
114 $self->_switch;
115 $self->connection->irc_notice({
116 channel => $message->channel,
117 message => $self->is_enable ? '[feed] on' : '[feed] off'
118 });
119 }
120  
121 return $self->pass;
122 }
123  
124 __PACKAGE__->meta->make_immutable;
125  
126 1;
127  
128 __END__