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