escape % in irssi messages
[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     my $format = '%%mxmlrtorrent: %%n' . shift(@text);
98
99     # escape % in parameters from irssi
100     @text = grep { s/%/%%/g } @text;
101
102     if (defined($output) and ref($output)) {
103         $output->print(sprintf($format, @text), MSGLEVEL_CLIENTCRAP);
104     } else {
105         Irssi::print(sprintf($format, @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 sub check_for_link {
125     my ($signal,$parammessage,$paramchannel,$paramnick,$paramserver) = @_;
126     my $server = $signal->[$paramserver];
127     my $target = $signal->[$paramchannel];
128     my $message = ($parammessage == -1) ? '' : $signal->[$parammessage];
129     my $nick = ($paramnick == -1)?defined($server)?$server->{'nick'}:'':$signal->[$paramnick];
130     my $g;
131     my $p;
132
133     my $witem;
134     if (defined $server) {
135         $witem = $server->window_item_find($target);
136     } else {
137         $witem = Irssi::window_item_find($target);
138     }
139     
140     # Look if we should ignore this line
141     if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
142         return;
143     }
144         
145     push_output($witem);
146
147     # Look if there is a torrent link in there
148         
149     while ($message =~ m,(http://\S*\.(?:torrent|penis)),g) {
150         write_debug('Torrent-URL: %s', $1);
151         $torrentlist{$torrentindex++} = {'CHANNEL' => $target, 'NICK' => $nick, 'URL' => $1};
152     }
153
154     pop_output();
155 }
156
157 # Handle the queue of unhandled torrents
158 sub cmd_queue {
159     my ($subcmd, $id, @params) = @_;
160
161     if ('remove' eq $subcmd) {
162         if (defined($id)) {
163             delete($torrentlist{$id});
164         }
165     } elsif ('clear' eq $subcmd) {
166         %torrentlist = ();
167     } elsif ('confirm' eq $subcmd) {
168         my $u;
169         return unless(defined($id) and exists($torrentlist{$id}));
170
171         $u = $torrentlist{$id}->{'URL'};
172
173         write_debug('Sending %s to rtorrent', $u);
174         unless(defined($rtorrent->load_start($talker, $u))) {
175             write_irssi('%%RError sending URL %s: %s', $u, $rtorrent->errstr());
176         } else {
177             write_irssi('%s enqueued', $u);
178             delete($torrentlist{$id});
179         }
180     } elsif ('add' eq $subcmd) {
181         unless(defined($id)) {
182             return;
183         }
184         $torrentlist{$torrentindex++} = {'CHANNEL' => '', 'NICK' => '', 'URL' => $id};
185     } elsif (('list' eq $subcmd) or !defined($subcmd))  {
186         my $l;
187         write_irssi('List of queued torrents');
188         if (0 == scalar(keys(%torrentlist))) {
189             write_irssi('  (no torrents in local queue)');
190         } else {
191             foreach (sort(keys(%torrentlist))) {
192                 write_irssi('  %3d: %s@%s: %s', $_,
193                         $torrentlist{$_}->{'NICK'},
194                         $torrentlist{$_}->{'CHANNEL'},
195                         $torrentlist{$_}->{'URL'});
196             }
197         }
198     } else {
199         write_irssi('Unknown subcommand: %s', $subcmd);
200     }
201 }
202
203 # Handle the remote rtorrent queue
204 sub cmd_remote {
205     my ($subcmd, $id, @params) = @_;
206     my $rqueue;
207
208     if (('list' eq $subcmd) or !defined($subcmd)) {
209         unless(defined($rqueue = $rtorrent->download_list($talker))) {
210             write_irssi('Error getting list of downloads: %s', $rtorrent->errstr());
211             return;
212         }
213
214         write_irssi('List of remote torrents');
215         if (0 == scalar(@{$rqueue})) {
216             write_irssi('  (no torrents in remote queue)');
217         } else {
218             foreach (@{$rqueue}) {
219                 write_irssi('  %s%s: %sB/%sB done (%d%%), %sB/s up, %sB/s down',
220                             $_->{'ACTIVE'}?'*':' ',
221                             $_->{'NAME'},
222                             $_->{'BYTES_DONE'},
223                             $_->{'SIZE_BYTES'},
224                             $_->{'UP_RATE'},
225                             $_->{'DOWN_RATE'});
226             }
227         }
228     }
229 }
230
231
232 sub cmd_save {
233     
234     my %mappedqueue;
235
236     # XML::Simple has some problems with numbers as nodenames,
237     # so we have to modify our queue a bit.
238     %mappedqueue = map {("_$_" => $torrentlist{$_})} keys(%torrentlist);
239
240     eval {
241         open(CONF, '>'.$conffile) or die 'Could not open config file';
242         $conf->{'xmlrtorrent'}->{'_QUEUE'} = \%mappedqueue;
243         print CONF XML::Simple::XMLout($conf, KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'});
244         close(CONF);
245     };
246     if ($@) {
247         write_irssi('Could not save config to %s: %s', ($conffile, $@));
248     } else {
249         write_irssi('configuration saved to %s', $conffile);
250     }
251 }
252
253 sub cmd_set {
254     my $target = shift;
255     my $key = shift;
256     my $val = shift;
257     my $p;
258
259     foreach $p (@talkers) {
260         if ($p->{'NAME'} eq $target) {
261             $p->setval($key, $val);
262             return;
263         }
264     }
265     write_irssi(undef, 'No such module');
266 }
267
268 sub cmd_show {
269     my $target = shift;
270     my $p;
271     my $e;
272
273     if (defined($target)) {
274         foreach $p (@talkers) {
275             if ($p->{'NAME'} eq $target) {
276                 write_irssi($p->getconfstr());
277                 return;
278             }
279         }
280         write_irssi('No such module');
281     } else {
282         write_irssi('Loaded talkers:');
283         foreach $p (@talkers) {
284             write_irssi(' %s', $p->{'NAME'});
285         };
286     }
287 }
288
289 sub cmd_help {
290     my $target = shift;
291     my $p;
292
293     if (defined($target)) {
294         foreach $p (@talkers) {
295             if ($p->{'NAME'} eq $target) {
296                 write_irssi($p->gethelpstr());
297                 return;
298             }
299         }
300         write_irssi('No such module');
301     } else {
302         write_irssi(<<'EOT');
303 Supported commands:
304  save: save the current configuration
305  help [modulename]: display this help or module specific help
306  show [modulename]: show loaded modules or the current parameters of a module
307  talker [modulename]: display or set the talker to use
308  debug: enable debugging messages
309  nodebug: disable debugging messages
310 EOT
311 ;
312     }
313 }
314
315 sub cmd_talker {
316     my $target = shift;
317     my $p;
318
319     if (defined($target)) {
320         foreach $p (@talkers) {
321             if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'talker')) {
322                 $talker = $p;
323                 $conf->{'videosite'}->{'talker'} = $target;
324                 return;
325             }
326         }
327         write_irssi('No such talker');
328     } else {
329         write_irssi('Current talker: %s', $conf->{'videosite'}->{'talker'});
330     }
331 }
332
333
334
335 # save on unload
336 sub sig_command_script_unload {
337     my $script = shift;
338     if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
339         cmd_save();
340     }
341 }
342
343 sub ploader {
344
345     my $dir = shift;
346     my $pattern = shift;
347     my $type = shift;
348     my @list;
349     my $p;
350     my $g;
351     my @g = ();
352
353     opendir(D, $dir) || return ();
354     @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
355     closedir(D);
356
357     foreach $p (@list) {
358         write_debug('Trying to load %s:', $p);
359         $p =~ s/\.pm$//;
360         eval qq{ require xmlrtorrent::$p; };
361         if ($@) {
362             write_irssi('Failed to load plugin: %s', "$@");
363             next;
364         }
365
366         $g = eval qq{ xmlrtorrent::$p->new(); };
367         if ($@) {
368             write_irssi('Failed to instanciate: %s', "$@");
369             delete($INC{$p});
370             next;
371         }
372
373         write_debug('found %s %s', $g->{'TYPE'}, $g->{'NAME'});
374         if ($type eq $g->{'TYPE'}) {
375             push(@g, $g);
376             $g->setio(sub {Irssi::print(shift)});
377         } else {
378             write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
379             delete($INC{$p});
380         }
381     }
382
383     write_debug('Loaded %d plugins', $#g+1);
384     
385     return @g;
386 }
387
388 sub _load_modules($) {
389
390     my $path = shift;
391
392     foreach (keys(%INC)) {
393         if ($INC{$_} =~ m|^$path|) {
394             write_debug('Removing %s from $INC', $_);
395             delete($INC{$_});
396         }
397     }
398     @talkers = ploader($path, '.*Talker\.pm$', 'talker');
399 }
400
401 sub init_xmlrtorrent {
402
403     my $bindings = shift;
404     my $p;
405
406     unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
407         # No config, start with an empty one
408         write_debug('No config found, using defaults');
409         $conf = { 'xmlrtorrent' => { }};
410     }
411     foreach (keys(%{$PARAMS})) {
412         unless (exists($conf->{'xmlrtorrent'}->{$_})) {
413             $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
414         }
415     }
416
417     _load_modules($plugindir);
418
419     unless (defined(@talkers)) {
420         write_irssi('No talkers found, can not proceed.');
421         return;
422     }
423
424     $talker = $talkers[0];
425     foreach $p (@talkers) {
426         if ($conf->{'xmlrtorrent'}->{'talker'} eq $p->{'NAME'}) {
427             $talker = $p;
428         }
429     }
430     write_debug(undef, 'Selected %s as talker', $talker->{'NAME'});
431     $conf->{'videosite'}->{'talker'} = $talker->{'NAME'};
432
433
434     # Restore the queue
435     %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
436     %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
437     $torrentindex = max(keys(%torrentlist)) + 1;
438
439     unless(defined($rtorrent = xmlrtorrent->new())) {
440         write_irssi('Could not initialize XMLRPC instance');
441         return;
442     }
443
444     if ($bindings) {
445
446         Irssi::signal_add_first('command script load', 'sig_command_script_unload');
447         Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
448         Irssi::signal_add('setup saved', 'cmd_save');
449
450
451         Irssi::command_bind('torrent' => \&cmdhandler);
452     }
453
454     write_irssi('xmlrtorrent initialized');
455 }
456
457 sub sig_complete {
458     my ($complist, $window, $word, $linestart, $want_space) = @_;
459     my @matches;
460
461     if ($linestart !~ m|^/torrent\b|) {
462         return;
463     }
464
465     ${$want_space} = 0;
466
467     Irssi::signal_stop();
468 }
469
470 sub cmdhandler {
471     my ($data, $server, $witem) = @_;
472     my ($cmd, @params) = split(/\s+/, $data);
473
474     push_output($witem);
475
476     if (exists($xmlrtorrent_commands->{$cmd})) {
477         $xmlrtorrent_commands->{$cmd}->(@params);
478     } else {
479         write_irssi('Unknown command: %s', $cmd);
480     }
481
482     pop_output();
483 }
484
485 unshift(@INC, $scriptdir);
486 init_xmlrtorrent(1);