summaryrefslogtreecommitdiff
path: root/lib/Multi/IRC.pm
blob: 9ac169a41bfeea4e2bbcb6fdeb0c50ff13468182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

#
#  Multi::IRC  -  HMX-12 Multi, the IRC bot
#

package Multi::IRC;

use strict;
use warnings;
use POE qw|
  Component::IRC::State
  Component::IRC::Plugin::Connector
  Component::IRC::Plugin::CTCP
  Component::IRC::Plugin::Logger
  Component::IRC::Plugin::NickServID
|;
use POE::Component::IRC::Common ':ALL';
use URI::Escape 'uri_escape_utf8';
use Net::HTTP;

use constant {
  ARG  => ARG0,
  DEST => ARG1,
  NICK => ARG2
};


sub spawn {
  return if $Multi::DAEMONIZE != 0; # we don't provide any commands, after all

  my $p = shift;
  my $irc = POE::Component::IRC::State->spawn(
    alias => 'circ',
    NoDNS => 1,
  );
  POE::Session->create(
    package_states => [
      $p => [qw|
        _start irc_001 irc_public irc_ctcp_action irc_msg irccmd vndbid shutdown
        cmd_info cmd_vndb cmd_list cmd_vn cmd_uptime cmd_me cmd_say cmd_cmd cmd_eval
      |],
    ],
    heap => { irc => $irc,
      o => {
        user => 'Multi_test'.$$,
        server => 'irc.synirc.net',
        ircname => 'VNDB.org Multi',
        channel => [ '#vndb' ],
        @_
      },
      log => {},
      privpers => {},
    }
  );
}


sub _start {
  $_[KERNEL]->alias_set('irc');

  $_[HEAP]{irc}->plugin_add(
    Logger => POE::Component::IRC::Plugin::Logger->new(
      Path => $Multi::LOGDIR,
      Private => 0,
      Public => 1,
  ));
  $_[HEAP]{irc}->plugin_add(
    Connector => POE::Component::IRC::Plugin::Connector->new()
  );
  $_[HEAP]{irc}->plugin_add(
    CTCP => POE::Component::IRC::Plugin::CTCP->new(
      version => $_[HEAP]{o}{ircname}.' v'.$VNDB::VERSION,
      userinfo => $_[HEAP]{o}{ircname},
  ));
  $_[HEAP]{irc}->plugin_add(
    NickServID => POE::Component::IRC::Plugin::NickServID->new(
      Password => $_[HEAP]{o}{pass}
  )) if $_[HEAP]{o}{pass};

  $_[KERNEL]->post(circ => register => 'all');
  $_[KERNEL]->post(circ => connect => {
    Nick  => $_[HEAP]{o}{user},
    Username => 'u1',
    Ircname => $_[HEAP]{o}{ircname},
    Server => $_[HEAP]{o}{server},
  });

  $_[KERNEL]->sig('shutdown' => 'shutdown');
}


sub irc_001 { 
  $_[KERNEL]->post(circ => join => $_) for (@{$_[HEAP]{o}{channel}});
  $_[KERNEL]->call(core => log => 2, 'Connected to IRC!');
}


sub irc_public {
  if($_[ARG2] =~ /^!/) {
    (my $cmd = $_[ARG2]) =~ s/^!//;
    my $nick = (split /!/, $_[ARG0])[0];
    $_[KERNEL]->call(irc => irccmd => $_[ARG1][0], $cmd, $nick);
  } else {
    $_[KERNEL]->call(irc => vndbid => $_[ARG1][0], $_[ARG2]);
  }
}


sub irc_ctcp_action {
  $_[KERNEL]->call(irc => vndbid => $_[ARG1][0], $_[ARG2]);
}


sub irc_msg {
  my $nick = ( split /!/, $_[ARG0] )[0];
  $_[ARG2] =~ s/^!//;
  if(!$_[KERNEL]->call(irc => irccmd => $nick => $_[ARG2])) {
    $_[HEAP]{privpers}{$_} < time-3600 and delete $_[HEAP]{privpers}{$_}
      for (keys %{$_[HEAP]{privpers}});
    $_[KERNEL]->post(circ => privmsg => $nick => 'I am not human, join #vndb or PM Yorhel if you need something.')
      if !$_[HEAP]{privpers}{$nick};
    $_[HEAP]{privpers}{$nick} ||= time;
  }
}


sub irccmd { # dest, cmd, [nick]
  my($dest, $cmd, $nick) = @_[ARG0..$#_];
  $nick ||= $_[ARG0];

  return 0 if $cmd !~ /^([a-z0-9A-Z_]+)(?: (.+))?$/;
  my($f, $a) = (lc $1, $2||'');

  # check for a cmd_* function and call it (some scary magic, see perlmod)
  my $sub;
  {
    no strict;
    $sub = ${__PACKAGE__.'::'}{'cmd_'.$f};
  }
  return 0 if !defined $sub;
  local *SUB = $sub;
  return 0 if !defined *SUB{CODE};
  $_[KERNEL]->yield('cmd_'.$f, $a, $dest, $nick);
  return 1;
}


sub vndbid { # dest, msg, force
  my $m = $_[ARG1];

  $_[HEAP]{log}{$_} < time-60 and delete $_[HEAP]{log}{$_}
    for (keys %{$_[HEAP]{log}});

  # Four possible options:
  #  1.  [tvpru]+  -> item page
  #  2.  [vpr]+.+  -> item revision
  #  3.  d+        -> documentation page
  #  4.  d+.+      -> documentation page # section
  #  5.  t+.+      -> reply to a thread

  my @formats = (
    BOLD.RED.'['.NORMAL.BOLD.'_%s%d'   .RED.']'                       .NORMAL.' %s '                       .RED.'@'.NORMAL.LIGHT_GREY.' %s/%1$s%2$d'.NORMAL,
    BOLD.RED.'['.NORMAL.BOLD.'%s%d.%d'.RED.']'.NORMAL.RED.' Edit of' .NORMAL.' %s '.RED.'by'.NORMAL.' %s '.RED.'@'.NORMAL.LIGHT_GREY.' %s/%1$s%2$d.%3$d'.NORMAL,
    BOLD.RED.'['.NORMAL.BOLD.'d%d'    .RED.']'                       .NORMAL.' %s '                       .RED.'@'.NORMAL.LIGHT_GREY.' %s/d%1$d'.NORMAL,
    BOLD.RED.'['.NORMAL.BOLD.'d%d.%d' .RED.']'                       .NORMAL.' %s '.RED.'->'.NORMAL.' %s '.RED.'@'.NORMAL.LIGHT_GREY.' %s/d%1$d#%2$d'.NORMAL,
    BOLD.RED.'['.NORMAL.BOLD.'t%d.%d' .RED.']'.NORMAL.RED.' Reply to'.NORMAL.' %s '.RED.'by'.NORMAL.' %s '.RED.'@'.NORMAL.LIGHT_GREY.' %s/t%1$d.%2$d'.NORMAL,
  );

  # get a list of possible IDs (a la sub summary in defs.pl)
  my @id; # [ type, id, ref ]
  for (split /[, ]/, $m) {
    next if length > 15 or m{[a-z]{3,6}://}i; # weed out URLs and too long things
    push @id, /^(?:.*[^\w]|)([dvprt])([1-9][0-9]*)\.([1-9][0-9]*)(?:[^\w].*|)$/ ? [ $1, $2, $3 ]   # matches 2, 4 and 5
           :  /^(?:.*[^\w]|)([dvprtu])([1-9][0-9]*)(?:[^\w].*|)$/ ? [ $1, $2, 0 ] : ();       # matches 1 and 3
  }

  # loop through the matched IDs and search the database
  for (@id) {
    my($t, $id, $rev) = (@$_);

    next if $_[HEAP]{log}{$t.$id.'.'.$rev} && !$_[ARG2];
    $_[HEAP]{log}{$t.$id.'.'.$rev} = time;

   # option 1: item page
    if($t =~ /[vprtu]/ && !$rev) {
      my $s = $Multi::SQL->prepare(
        $t eq 'v' ? 'SELECT vr.title FROM vn_rev vr JOIN vn v ON v.latest = vr.id WHERE v.id = ?' :
        $t eq 'u' ? 'SELECT u.username AS title FROM users u WHERE u.id = ?' :
        $t eq 'p' ? 'SELECT pr.name AS title FROM producers_rev pr JOIN producers p ON p.latest = pr.id WHERE p.id = ?' :
        $t eq 't' ? 'SELECT title FROM threads WHERE id = ?' :
                    'SELECT rr.title FROM releases_rev rr JOIN releases r ON r.latest = rr.id WHERE r.id = ?'
      );
      $s->execute($id);
      my $r = $s->fetchrow_hashref;
      $s->finish;
      next if !$r || ref($r) ne 'HASH';
      $_[KERNEL]->post(circ => privmsg => $_[ARG0], sprintf $formats[0],
        $t, $id, $r->{title}, $VNDB::VNDBopts{root_url});

   # option 2: item revision
    } elsif($t =~ /[vpr]/) {
      my $s = $Multi::SQL->prepare(sprintf q|
        SELECT %s AS title, u.username
        FROM changes c
        JOIN %s_rev i ON c.id = i.id
        JOIN users u ON u.id = c.requester
        WHERE i.%sid = %d 
          AND c.rev = %d|,
        $t ne 'p' ? 'i.title' : 'i.name',
        {qw|v vn r releases p producers|}->{$t},
        $t, $id, $rev);
      $s->execute;
      my $r = $s->fetchrow_hashref;
      next if !$r || ref($r) ne 'HASH';
      $_[KERNEL]->post(circ => privmsg => $_[ARG0], sprintf $formats[1],
        $t, $id, $rev, $r->{title}, $r->{username}, $VNDB::VNDBopts{root_url});

   # option 3: documentation page
    } elsif($t eq 'd') {
      my $f = sprintf '/www/vndb/data/docs/%d', $id;
      open my $F, '<', $f or next;
      (my $title = <$F>) =~ s/^:TITLE://;
      chomp($title);

      if(!$rev) {
        $_[KERNEL]->post(circ => privmsg => $_[ARG0], sprintf $formats[2],
          $id, $title, $VNDB::VNDBopts{root_url});
        next;
      }

   # option 4: documentation page # section
      my($sec, $sub);
      while(<$F>) {
        if(/^:SUB:/ && ++$sec == $rev) {
          chomp;
          ($sub = $_) =~ s/^:SUB://;
          last;
        }
      }
      next if !$sub;
      $_[KERNEL]->post(circ => privmsg => $_[ARG0], sprintf $formats[3],
        $id, $rev, $title, $sub, $VNDB::VNDBopts{root_url});

   # option 5: reply to a thread
    } elsif($t eq 't' && $rev) {
      my $s = $Multi::SQL->prepare(q|
        SELECT t.title, u.username
          FROM threads t
          JOIN threads_posts tp ON tp.tid = t.id
          JOIN users u ON u.id = tp.uid
          WHERE t.id = ?
            AND tp.num = ?|);
      $s->execute($id, $rev);
      my $r = $s->fetchrow_hashref;
      $s->finish;
      next if !$r || ref($r) ne 'HASH';
      $_[KERNEL]->post(circ => privmsg => $_[ARG0], sprintf $formats[4],
        $id, $rev, $r->{title}, $r->{username}, $VNDB::VNDBopts{root_url});
    }
  }
}

sub shutdown {
  $_[KERNEL]->post(circ => shutdown => 'Byebye!');
}



# cmd_* commands: $arg, $dest, $nick

sub cmd_info {
  $_[KERNEL]->post(circ => privmsg => $_[DEST],
    'Hello, I am HMX-12 Multi v'.$VNDB::VERSION.' made by the great Yorhel!');
}


sub cmd_vndb {
  $_[KERNEL]->post(circ => privmsg => $_[DEST],
    'VNDB ~ The Visual Novel Database ~ http://vndb.org/');
}


sub cmd_list {
  return if $_[DEST] ne $_[HEAP]{o}{channel}[0];
  $_[KERNEL]->post(circ => privmsg => $_[DEST],
    $_[NICK].', this is not a warez channel!');
}


sub cmd_vn { # $arg = search string
  $_[ARG] =~ s/%//g;
  return $_[KERNEL]->post(circ => privmsg => $_[DEST], 'You forgot the search query, idiot~~!.') if !$_[ARG];
  
  my $q = $Multi::SQL->prepare(q|
    SELECT v.id
    FROM vn v
    JOIN vn_rev vr ON vr.id = v.latest
    WHERE vr.title ILIKE $1
       OR vr.alias ILIKE $1
       OR v.id IN(
         SELECT rv.vid
         FROM releases r
         JOIN releases_rev rr ON rr.id = r.latest
         JOIN releases_vn rv ON rv.rid = rr.id
         WHERE rr.title ILIKE $1
            OR rr.original ILIKE $1
       )
    ORDER BY vr.id
    LIMIT 6|);
  $q->execute('%'.$_[ARG].'%');

  my $res = $q->fetchall_arrayref([]);
  return $_[KERNEL]->post(circ => privmsg => $_[DEST],
    sprintf 'No results found for %s', $_[ARG]) if !@$res;
  return $_[KERNEL]->post(circ => privmsg => $_[DEST],
    sprintf 'Too many results found, see %s/v/search?q=%s',
      $VNDB::VNDBopts{root_url}, uri_escape_utf8($_[ARG])) if @$res > 5;
  $_[KERNEL]->call(irc => vndbid => $_[DEST], join(' ', map 'v'.$_->[0], @$res), 1);
}


sub cmd_uptime {
  my $age = sub {
    return '..down!?' if !$_[0];
    my $d = int $_[0] / 86400;
    $_[0] %= 86400;
    my $h = int $_[0] / 3600;
    $_[0] %= 3600;
    my $m = int $_[0] / 60;
    $_[0] %= 60;
    return sprintf '%s%02d:%02d:%02d', $d ? $d.' days, ' : '', $h, $m, int $_[0];
  };

  open my $R, '<', '/proc/uptime';
  my $server = <$R> =~ /^\s*([0-9]+)/ ? $1 : 0;
  close $R;

  my $multi = time - $^T;

  my $http=0;
 # this should actually be done asynchronously... but I don't expect it to timeout
  if(my $req = Net::HTTP->new(Host => 'localhost', Timeout => 1)) {
    $req->write_request(GET => '/server-status?auto');
    my $d;
    $req->read_entity_body($d, 1024) if $req->read_response_headers;
    $http = $1 if $d =~ /Uptime:\s*([0-9]+)/i;
  }
  
  $_[KERNEL]->post(circ => privmsg => $_[DEST], $_) for (split /\n/, sprintf
    "Uptimes:\n  Server: %s\n  Multi:  %s\n  HTTP:  Uptimes:  %s", map $age->($_), $server, $multi, $http);
}


sub cmd_say { # $arg = '[#chan ]text', no #chan = $dest
  return unless &mymaster;
  my $chan = $_[ARG] =~ s/^(#[a-zA-Z0-9-_.]+) // ? $1 : $_[DEST];
  $_[KERNEL]->post(circ => privmsg => $chan, $_[ARG]);
}


sub cmd_me { # same as cmd_say, but CTCP ACTION
  return unless &mymaster;
  my $chan = $_[ARG] =~ s/^(#[a-zA-Z0-9-_.]+) // ? $1 : $_[DEST];
  $_[KERNEL]->post(circ => ctcp => $chan, 'ACTION '.$_[ARG]);
}


sub cmd_cmd { # TODO: feedback?
  return unless &mymaster;
  $_[KERNEL]->post(core => queue => $_[ARG]);
  $_[KERNEL]->post(circ => privmsg => $_[DEST] => sprintf "Executing %s", $_[ARG]);
}


sub cmd_eval { # the evil cmd
  return unless &mymaster;
  $_[KERNEL]->post(circ => privmsg => $_[DEST], 'eval: '.$_)
    for (split /\r?\n/, eval($_[ARG])||$@);
}




# non-POE function, checks whether we should trust $nick
sub mymaster { # same @_ as the cmd_ functions
  if(!$_[HEAP]{irc}->is_channel_operator($_[HEAP]{o}{channel}[0], $_[ARG2])
    && !$_[HEAP]{irc}->is_channel_owner($_[HEAP]{o}{channel}[0], $_[ARG2])
    && !$_[HEAP]{irc}->is_channel_admin($_[HEAP]{o}{channel}[0], $_[ARG2])
  ) {
    $_[KERNEL]->post(circ => privmsg => $_[ARG1],
      ($_[ARG1]=~/^#/?$_[ARG2].', ':'').'You are not my master!');
    return 0;
  }
  return 1;
}

1;