fix % escaping
[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 $conf;
17 my $conffile = File::Spec->catfile(Irssi::get_irssi_dir(), 'xmlrtorrent.xml');
18 my $scriptdir = File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts');
19 my %torrentlist = ();
20 my $torrentindex = 1;
21 my $rtorrent;
22
23 my @outputstack = (undef);
24
25 my $PARAMS = {
26     'XMLURL' => 'http://localhost/RPC2',
27     'USERNAME' => '',
28     'PASSWORD' => '',
29     '_QUEUE' => {},
30 };
31
32 # activate debug here
33 my $debug = 0;
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     'debug' => sub {
79         $debug = 1;
80         write_irssi('Enabled debugging');
81     },
82
83     'nodebug' => sub {
84         $debug = 0;
85         write_irssi('Disabled debugging');
86     },
87 };
88
89 sub write_irssi {
90     my @text = @_;
91     my $output = $outputstack[0];
92
93     my $format = '%%mxmlrtorrent: %%n' . shift(@text);
94
95     # escape % in parameters from irssi
96     s/%/%%/g foreach @text;
97
98     if (defined($output) and ref($output)) {
99         $output->print(sprintf($format, @text), MSGLEVEL_CLIENTCRAP);
100     } else {
101         Irssi::print(sprintf($format, @text));
102     }
103
104 }
105
106 sub push_output {
107     unshift(@outputstack, shift);
108 }
109
110 sub pop_output {
111     shift(@outputstack);
112 }
113
114 sub write_debug {
115     if ($debug) {
116         write_irssi(@_);
117     }
118 }
119
120 # This is shamelessly stolen from pythons urlgrabber
121 sub format_number {
122     my $number = shift;
123     my $SI = shift || 0;
124     my @symbols = ('', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y');
125     my $step = $SI?1000:1024;
126     my $thresh = 999;
127     my $depth = 0;
128     my $max_depth = $#symbols;
129     my $format;
130
131     while (($number > $thresh) and ($depth < $max_depth)) {
132         $depth += 1;
133         $number /= $step;
134     }
135
136     if ($number =~ /^[+-]?\d+$/) {
137         # Integer.
138         $format = '%i%s';
139     } elsif ($number < 9.95) {
140         $format = '%.1f%s';
141     } else {
142         $format = '%.0f%s';
143     }
144     return sprintf($format, $number, $symbols[$depth]);
145 }
146
147
148
149 sub check_for_link {
150     my ($signal,$parammessage,$paramchannel,$paramnick,$paramserver) = @_;
151     my $server = $signal->[$paramserver];
152     my $target = $signal->[$paramchannel];
153     my $message = ($parammessage == -1) ? '' : $signal->[$parammessage];
154     my $nick = ($paramnick == -1)?defined($server)?$server->{'nick'}:'':$signal->[$paramnick];
155     my $g;
156     my $p;
157
158     my $witem;
159     if (defined $server) {
160         $witem = $server->window_item_find($target);
161     } else {
162         $witem = Irssi::window_item_find($target);
163     }
164     
165     # Look if we should ignore this line
166     if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
167         return;
168     }
169         
170     push_output($witem);
171
172     # Look if there is a torrent link in there
173         
174     while ($message =~ m,(http://\S*\.(?:torrent|penis)),g) {
175         write_debug('Torrent-URL: %s', $1);
176         $torrentlist{$torrentindex++} = {'CHANNEL' => $target, 'NICK' => $nick, 'URL' => $1};
177     }
178
179     pop_output();
180 }
181
182 # Handle the queue of unhandled torrents
183 sub cmd_queue {
184     my ($subcmd, $id, @params) = @_;
185
186     if ('remove' eq $subcmd) {
187         if (defined($id)) {
188             delete($torrentlist{$id});
189         }
190     } elsif ('clear' eq $subcmd) {
191         %torrentlist = ();
192     } elsif ('confirm' eq $subcmd) {
193         my $u;
194         return unless(defined($id) and exists($torrentlist{$id}));
195
196         $u = $torrentlist{$id}->{'URL'};
197
198         write_debug('Sending %s to rtorrent', $u);
199         unless(defined($rtorrent->load_start($u))) {
200             write_irssi('%%RError sending URL %s: %s', $u, $rtorrent->errstr());
201         } else {
202             write_irssi('%s enqueued', $u);
203             delete($torrentlist{$id});
204         }
205     } elsif ('add' eq $subcmd) {
206         unless(defined($id)) {
207             return;
208         }
209         $torrentlist{$torrentindex++} = {'CHANNEL' => '', 'NICK' => '', 'URL' => $id};
210     } elsif (('list' eq $subcmd) or !defined($subcmd))  {
211         my $l;
212         write_irssi('List of queued torrents');
213         if (0 == scalar(keys(%torrentlist))) {
214             write_irssi('  (no torrents in local queue)');
215         } else {
216             foreach (sort(keys(%torrentlist))) {
217                 write_irssi('  %3d: %s@%s: %s', $_,
218                         $torrentlist{$_}->{'NICK'},
219                         $torrentlist{$_}->{'CHANNEL'},
220                         $torrentlist{$_}->{'URL'});
221             }
222         }
223     } else {
224         write_irssi('Unknown subcommand: %s', $subcmd);
225     }
226 }
227
228 # Handle the remote rtorrent queue
229 sub cmd_remote {
230     my ($subcmd, $id, @params) = @_;
231     my $rqueue;
232
233     if (('list' eq $subcmd) or !defined($subcmd)) {
234         unless(defined($rqueue = $rtorrent->download_list())) {
235             write_irssi('Error getting list of downloads: %s', $rtorrent->errstr());
236             return;
237         }
238
239         write_irssi('List of rempote torrents');
240         if (0 == scalar(@{$rqueue})) {
241             write_irssi('  (no torrents in remote queue)');
242         } else {
243             foreach (@{$rqueue}) {
244                 write_irssi('  %s%s: %sB/%sB done (%d%%), %sB/s up, %sB/s down',
245                         $_->[6]?'*':' ',
246                         $_->[0],
247                         format_number($_->[2]),
248                         format_number($_->[1]),
249                         ($_->[2]*100)/$_->[1],
250                         format_number($_->[3]),
251                         format_number($_->[4]));
252             }
253         }
254     }
255 }
256
257
258 sub cmd_save {
259     
260     my %mappedqueue;
261
262     # XML::Simple has some problems with numbers as nodenames,
263     # so we have to modify our queue a bit.
264     %mappedqueue = map {("_$_" => $torrentlist{$_})} keys(%torrentlist);
265
266     eval {
267         open(CONF, '>'.$conffile) or die 'Could not open config file';
268         $conf->{'xmlrtorrent'}->{'_QUEUE'} = \%mappedqueue;
269         print CONF XML::Simple::XMLout($conf, KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'});
270         close(CONF);
271     };
272     if ($@) {
273         write_irssi('Could not save config to %s: %s', ($conffile, $@));
274     } else {
275         write_irssi('configuration saved to %s', $conffile);
276     }
277 }
278
279 sub cmd_set {
280     my $target = shift;
281     my $key = shift;
282     my $val = shift;
283
284     if ('global' eq $target) {
285         if(exists($PARAMS->{$key})) {
286             $conf->{'xmlrtorrent'}->{$key} = $val;
287             if ('XMLURL' eq $key) {
288                 unless(defined($rtorrent = xmlrtorrent->new(
289                         'XMLURL' => $conf->{'xmlrtorrent'}->{'XMLURL'},
290                         'USERNAME' => $conf->{'xmlrtorrent'}->{'USERNAME'},
291                         'USERNAME' => $conf->{'xmlrtorrent'}->{'PASSWORD'}))) {
292                     write_irssi('Could not initialize XMLRPC instance');
293                     return;
294                 }
295             }
296         } else {
297             write_irssi('Key %s does not exist', $key);
298         }
299     }
300 }
301
302
303 sub cmd_show {
304     my $target = shift;
305     my $p;
306     my $e;
307 }
308
309 sub cmd_help {
310     my $target = shift;
311     my $p;
312
313     write_irssi(<<'EOT');
314 Supported commands:
315  save: Save the current configuration
316  help: Display this help
317  debug: enable debugging messages
318  nodebug: disable debugging messages
319 EOT
320 }
321
322
323 # save on unload
324 sub sig_command_script_unload {
325     my $script = shift;
326     if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
327         cmd_save();
328     }
329 }
330
331 sub init_xmlrtorrent {
332
333     my $bindings = shift;
334     my $p;
335
336     unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
337         # No config, start with an empty one
338         write_debug('No config found, using defaults');
339         $conf = { 'xmlrtorrent' => { }};
340     }
341     foreach (keys(%{$PARAMS})) {
342         unless (exists($conf->{'xmlrtorrent'}->{$_})) {
343             $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
344         }
345     }
346
347     # Restore the queue
348     %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
349     %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
350     $torrentindex = max(keys(%torrentlist)) + 1;
351
352     unless(defined($rtorrent = xmlrtorrent->new(
353             'XMLURL' => $conf->{'xmlrtorrent'}->{'XMLURL'},
354             'USERNAME' => $conf->{'xmlrtorrent'}->{'USERNAME'},
355             'USERNAME' => $conf->{'xmlrtorrent'}->{'PASSWORD'}))) {
356         write_irssi('Could not initialize XMLRPC instance');
357         return;
358     }
359
360     if ($bindings) {
361
362         Irssi::signal_add_first('command script load', 'sig_command_script_unload');
363         Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
364         Irssi::signal_add('setup saved', 'cmd_save');
365
366
367         Irssi::command_bind('torrent' => \&cmdhandler);
368     }
369
370     write_irssi('xmlrtorrent initialized');
371 }
372
373 sub sig_complete {
374     my ($complist, $window, $word, $linestart, $want_space) = @_;
375     my @matches;
376
377     if ($linestart !~ m|^/torrent\b|) {
378         return;
379     }
380
381     ${$want_space} = 0;
382
383     Irssi::signal_stop();
384 }
385
386 sub cmdhandler {
387     my ($data, $server, $witem) = @_;
388     my ($cmd, @params) = split(/\s+/, $data);
389
390     push_output($witem);
391
392     if (exists($xmlrtorrent_commands->{$cmd})) {
393         $xmlrtorrent_commands->{$cmd}->(@params);
394     } else {
395         write_irssi('Unknown command: %s', $cmd);
396     }
397
398     pop_output();
399 }
400
401 unshift(@INC, $scriptdir);
402 init_xmlrtorrent(1);