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