fix torrent link detection
[xmlrtorrent.git] / xmlrtorrent.pl
1 # control an rTorrent client via XMLRPC,
2 # and collect rtorrent files from IRC for later download
3 #
4 # (c) 2007-2008 by Ralf Ertzinger <ralf@camperquake.de>
5 # licensed under GNU GPL v2
6
7 use strict;
8 use Irssi 20020324 qw (command_bind command_runsub signal_add_first signal_add_last);
9 use vars qw($VERSION %IRSSI);
10 use XML::Simple;
11 use Data::Dumper;
12 use File::Spec;
13 use List::Util qw(max);
14 use xmlrtorrent;
15
16 my @talkers;
17 my $talker;
18 my $conf;
19 my $conffile = File::Spec->catfile(Irssi::get_irssi_dir(), 'xmlrtorrent.xml');
20 my $scriptdir = File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts');
21 my $plugindir = File::Spec->catfile($scriptdir, 'xmlrtorrent');
22 my %torrentlist = ();
23 my $torrentindex = 1;
24 my $rtorrent;
25
26 my @outputstack = (undef);
27
28 my $PARAMS = {
29     '_QUEUE' => {},
30 };
31
32 # activate debug here
33 my $debug = 1;
34
35 # "message public", SERVER_REC, char *msg, char *nick, char *address, char *target
36 signal_add_last("message public" => sub {check_for_link(\@_,1,4,2,0);});
37 # "message own_public", SERVER_REC, char *msg, char *target
38 signal_add_last("message own_public" => sub {check_for_link(\@_,1,2,-1,0);});
39
40 # "message private", SERVER_REC, char *msg, char *nick, char *address
41 signal_add_last("message private" => sub {check_for_link(\@_,1,-1,2,0);});
42 # "message own_private", SERVER_REC, char *msg, char *target, char *orig_target
43 signal_add_last("message own_private" => sub {check_for_link(\@_,1,2,-1,0);});
44
45 # "message irc action", SERVER_REC, char *msg, char *nick, char *address, char *target
46 signal_add_last("message irc action" => sub {check_for_link(\@_,1,4,2,0);});
47 # "message irc own_action", SERVER_REC, char *msg, char *target
48 signal_add_last("message irc own_action" => sub {check_for_link(\@_,1,2,-1,0);});
49
50 # For tab completion
51 signal_add_first('complete word', \&sig_complete);
52
53 my $xmlrtorrent_commands = {
54     'save' => sub {
55         cmd_save();
56     },
57
58     'set' => sub {
59         cmd_set(@_);
60     },
61     
62     'show' => sub {
63         cmd_show(@_);
64     },
65
66     'help' => sub {
67         cmd_help(@_);
68     },
69
70     'queue' => sub {
71         cmd_queue(@_);
72     },
73
74     'remote' => sub {
75         cmd_remote(@_);
76     },
77
78     'talker' => sub {
79         cmd_talker(@_);
80     },
81
82     'debug' => sub {
83         $debug = 1;
84         write_irssi('Enabled debugging');
85     },
86
87     'nodebug' => sub {
88         $debug = 0;
89         write_irssi('Disabled debugging');
90     },
91 };
92
93 sub write_irssi {
94     my @text = @_;
95     my $output = $outputstack[0];
96
97     $text[0] = '%%mxmlrtorrent: %%n' . $text[0];
98
99     if (defined($output) and ref($output)) {
100         $output->print(sprintf(shift(@text), @text), MSGLEVEL_CLIENTCRAP);
101     } else {
102         Irssi::print(sprintf(shift(@text), @text));
103     }
104
105 }
106
107 sub push_output {
108     unshift(@outputstack, shift);
109 }
110
111 sub pop_output {
112     shift(@outputstack);
113 }
114
115 sub write_debug {
116     if ($debug) {
117         write_irssi(@_);
118     }
119 }
120
121 sub check_for_link {
122     my ($signal,$parammessage,$paramchannel,$paramnick,$paramserver) = @_;
123     my $server = $signal->[$paramserver];
124     my $target = $signal->[$paramchannel];
125     my $message = ($parammessage == -1) ? '' : $signal->[$parammessage];
126     my $nick = ($paramnick == -1)?defined($server)?$server->{'nick'}:'':$signal->[$paramnick];
127     my $g;
128     my $p;
129
130     my $witem;
131     if (defined $server) {
132         $witem = $server->window_item_find($target);
133     } else {
134         $witem = Irssi::window_item_find($target);
135     }
136     
137     # Look if we should ignore this line
138     if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
139         return;
140     }
141         
142     push_output($witem);
143
144     # Look if there is a torrent link in there
145         
146     while ($message =~ m,(http://\S*\.(?:torrent|penis)),g) {
147         write_debug('Torrent-URL: %s', $1);
148         $torrentlist{$torrentindex++} = {'CHANNEL' => $target, 'NICK' => $nick, 'URL' => $1};
149     }
150
151     pop_output();
152 }
153
154 # Handle the queue of unhandled torrents
155 sub cmd_queue {
156     my ($subcmd, $id, @params) = @_;
157
158     if ('remove' eq $subcmd) {
159         if (defined($id)) {
160             delete($torrentlist{$id});
161         }
162     } elsif ('clear' eq $subcmd) {
163         %torrentlist = ();
164     } elsif ('confirm' eq $subcmd) {
165         my $u;
166         return unless(defined($id) and exists($torrentlist{$id}));
167
168         $u = $torrentlist{$id}->{'URL'};
169
170         write_debug('Sending %s to rtorrent', $u);
171         unless(defined($rtorrent->load_start($talker, $u))) {
172             write_irssi('%%RError sending URL %s: %s', $u, $rtorrent->errstr());
173         } else {
174             write_irssi('%s enqueued', $u);
175             delete($torrentlist{$id});
176         }
177     } elsif ('add' eq $subcmd) {
178         unless(defined($id)) {
179             return;
180         }
181         $torrentlist{$torrentindex++} = {'CHANNEL' => '', 'NICK' => '', 'URL' => $id};
182     } elsif (('list' eq $subcmd) or !defined($subcmd))  {
183         my $l;
184         write_irssi('List of queued torrents');
185         if (0 == scalar(keys(%torrentlist))) {
186             write_irssi('  (no torrents in local queue)');
187         } else {
188             foreach (sort(keys(%torrentlist))) {
189                 write_irssi('  %3d: %s@%s: %s', $_,
190                         $torrentlist{$_}->{'NICK'},
191                         $torrentlist{$_}->{'CHANNEL'},
192                         $torrentlist{$_}->{'URL'});
193             }
194         }
195     } else {
196         write_irssi('Unknown subcommand: %s', $subcmd);
197     }
198 }
199
200 # Handle the remote rtorrent queue
201 sub cmd_remote {
202     my ($subcmd, $id, @params) = @_;
203     my $rqueue;
204
205     if (('list' eq $subcmd) or !defined($subcmd)) {
206         unless(defined($rqueue = $rtorrent->download_list($talker))) {
207             write_irssi('Error getting list of downloads: %s', $rtorrent->errstr());
208             return;
209         }
210
211         write_irssi('List of remote torrents');
212         if (0 == scalar(@{$rqueue})) {
213             write_irssi('  (no torrents in remote queue)');
214         } else {
215             foreach (@{$rqueue}) {
216                 write_irssi('  %s%s: %sB/%sB done (%d%%), %sB/s up, %sB/s down',
217                             $_->{'ACTIVE'}?'*':' ',
218                             $_->{'NAME'},
219                             $_->{'BYTES_DONE'},
220                             $_->{'SIZE_BYTES'},
221                             $_->{'UP_RATE'},
222                             $_->{'DOWN_RATE'});
223             }
224         }
225     }
226 }
227
228
229 sub cmd_save {
230     
231     my %mappedqueue;
232
233     # XML::Simple has some problems with numbers as nodenames,
234     # so we have to modify our queue a bit.
235     %mappedqueue = map {("_$_" => $torrentlist{$_})} keys(%torrentlist);
236
237     eval {
238         open(CONF, '>'.$conffile) or die 'Could not open config file';
239         $conf->{'xmlrtorrent'}->{'_QUEUE'} = \%mappedqueue;
240         print CONF XML::Simple::XMLout($conf, KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'});
241         close(CONF);
242     };
243     if ($@) {
244         write_irssi('Could not save config to %s: %s', ($conffile, $@));
245     } else {
246         write_irssi('configuration saved to %s', $conffile);
247     }
248 }
249
250 sub cmd_set {
251     my $target = shift;
252     my $key = shift;
253     my $val = shift;
254     my $p;
255
256     foreach $p (@talkers) {
257         if ($p->{'NAME'} eq $target) {
258             $p->setval($key, $val);
259             return;
260         }
261     }
262     write_irssi(undef, 'No such module');
263 }
264
265 sub cmd_show {
266     my $target = shift;
267     my $p;
268     my $e;
269
270     if (defined($target)) {
271         foreach $p (@talkers) {
272             if ($p->{'NAME'} eq $target) {
273                 write_irssi($p->getconfstr());
274                 return;
275             }
276         }
277         write_irssi('No such module');
278     } else {
279         write_irssi('Loaded talkers:');
280         foreach $p (@talkers) {
281             write_irssi(' %s', $p->{'NAME'});
282         };
283     }
284 }
285
286 sub cmd_help {
287     my $target = shift;
288     my $p;
289
290     if (defined($target)) {
291         foreach $p (@talkers) {
292             if ($p->{'NAME'} eq $target) {
293                 write_irssi($p->gethelpstr());
294                 return;
295             }
296         }
297         write_irssi('No such module');
298     } else {
299         write_irssi(<<'EOT');
300 Supported commands:
301  save: save the current configuration
302  help [modulename]: display this help or module specific help
303  show [modulename]: show loaded modules or the current parameters of a module
304  talker [modulename]: display or set the talker to use
305  debug: enable debugging messages
306  nodebug: disable debugging messages
307 EOT
308 ;
309     }
310 }
311
312 sub cmd_talker {
313     my $target = shift;
314     my $p;
315
316     if (defined($target)) {
317         foreach $p (@talkers) {
318             if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'talker')) {
319                 $talker = $p;
320                 $conf->{'videosite'}->{'talker'} = $target;
321                 return;
322             }
323         }
324         write_irssi('No such talker');
325     } else {
326         write_irssi('Current talker: %s', $conf->{'videosite'}->{'talker'});
327     }
328 }
329
330
331
332 # save on unload
333 sub sig_command_script_unload {
334     my $script = shift;
335     if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
336         cmd_save();
337     }
338 }
339
340 sub ploader {
341
342     my $dir = shift;
343     my $pattern = shift;
344     my $type = shift;
345     my @list;
346     my $p;
347     my $g;
348     my @g = ();
349
350     opendir(D, $dir) || return ();
351     @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
352     closedir(D);
353
354     foreach $p (@list) {
355         write_debug('Trying to load %s:', $p);
356         $p =~ s/\.pm$//;
357         eval qq{ require xmlrtorrent::$p; };
358         if ($@) {
359             write_irssi('Failed to load plugin: %s', "$@");
360             next;
361         }
362
363         $g = eval qq{ xmlrtorrent::$p->new(); };
364         if ($@) {
365             write_irssi('Failed to instanciate: %s', "$@");
366             delete($INC{$p});
367             next;
368         }
369
370         write_debug('found %s %s', $g->{'TYPE'}, $g->{'NAME'});
371         if ($type eq $g->{'TYPE'}) {
372             push(@g, $g);
373             $g->setio(sub {Irssi::print(shift)});
374         } else {
375             write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
376             delete($INC{$p});
377         }
378     }
379
380     write_debug('Loaded %d plugins', $#g+1);
381     
382     return @g;
383 }
384
385 sub _load_modules($) {
386
387     my $path = shift;
388
389     foreach (keys(%INC)) {
390         if ($INC{$_} =~ m|^$path|) {
391             write_debug('Removing %s from $INC', $_);
392             delete($INC{$_});
393         }
394     }
395     @talkers = ploader($path, '.*Talker\.pm$', 'talker');
396 }
397
398 sub init_xmlrtorrent {
399
400     my $bindings = shift;
401     my $p;
402
403     unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
404         # No config, start with an empty one
405         write_debug('No config found, using defaults');
406         $conf = { 'xmlrtorrent' => { }};
407     }
408     foreach (keys(%{$PARAMS})) {
409         unless (exists($conf->{'xmlrtorrent'}->{$_})) {
410             $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
411         }
412     }
413
414     _load_modules($plugindir);
415
416     unless (defined(@talkers)) {
417         write_irssi('No talkers found, can not proceed.');
418         return;
419     }
420
421     $talker = $talkers[0];
422     foreach $p (@talkers) {
423         if ($conf->{'xmlrtorrent'}->{'talker'} eq $p->{'NAME'}) {
424             $talker = $p;
425         }
426     }
427     write_debug(undef, 'Selected %s as talker', $talker->{'NAME'});
428     $conf->{'videosite'}->{'talker'} = $talker->{'NAME'};
429
430
431     # Restore the queue
432     %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
433     %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
434     $torrentindex = max(keys(%torrentlist)) + 1;
435
436     unless(defined($rtorrent = xmlrtorrent->new())) {
437         write_irssi('Could not initialize XMLRPC instance');
438         return;
439     }
440
441     if ($bindings) {
442
443         Irssi::signal_add_first('command script load', 'sig_command_script_unload');
444         Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
445         Irssi::signal_add('setup saved', 'cmd_save');
446
447
448         Irssi::command_bind('torrent' => \&cmdhandler);
449     }
450
451     write_irssi('xmlrtorrent initialized');
452 }
453
454 sub sig_complete {
455     my ($complist, $window, $word, $linestart, $want_space) = @_;
456     my @matches;
457
458     if ($linestart !~ m|^/torrent\b|) {
459         return;
460     }
461
462     ${$want_space} = 0;
463
464     Irssi::signal_stop();
465 }
466
467 sub cmdhandler {
468     my ($data, $server, $witem) = @_;
469     my ($cmd, @params) = split(/\s+/, $data);
470
471     push_output($witem);
472
473     if (exists($xmlrtorrent_commands->{$cmd})) {
474         $xmlrtorrent_commands->{$cmd}->(@params);
475     } else {
476         write_irssi('Unknown command: %s', $cmd);
477     }
478
479     pop_output();
480 }
481
482 unshift(@INC, $scriptdir);
483 init_xmlrtorrent(1);