1 # control an rTorrent client via XMLRPC,
2 # and collect rtorrent files from IRC for later download
4 # (c) 2007-2008 by Ralf Ertzinger <ralf@camperquake.de>
5 # licensed under GNU GPL v2
8 use Irssi 20020324 qw (command_bind command_runsub signal_add_first signal_add_last);
9 use vars qw($VERSION %IRSSI);
13 use List::Util qw(max);
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');
26 my @outputstack = (undef);
29 'XMLURL' => 'http://localhost/RPC2',
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);});
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);});
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);});
54 signal_add_first('complete word', \&sig_complete);
56 my $xmlrtorrent_commands = {
87 write_irssi('Enabled debugging');
92 write_irssi('Disabled debugging');
98 my $output = $outputstack[0];
100 $text[0] = '%%mxmlrtorrent: %%n' . $text[0];
102 if (defined($output) and ref($output)) {
103 $output->print(sprintf(shift(@text), @text), MSGLEVEL_CLIENTCRAP);
105 Irssi::print(sprintf(shift(@text), @text));
111 unshift(@outputstack, shift);
124 # This is shamelessly stolen from pythons urlgrabber
128 my @symbols = ('', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y');
129 my $step = $SI?1000:1024;
132 my $max_depth = $#symbols;
135 while (($number > $thresh) and ($depth < $max_depth)) {
140 if ($number =~ /^[+-]?\d+$/) {
143 } elsif ($number < 9.95) {
148 return sprintf($format, $number, $symbols[$depth]);
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];
164 if (defined $server) {
165 $witem = $server->window_item_find($target);
167 $witem = Irssi::window_item_find($target);
170 # Look if we should ignore this line
171 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
177 # Look if there is a torrent link in there
178 $message =~ m,(http://\S*\.(?:torrent|penis)),;
180 while (defined($m)) {
181 write_debug('Torrent-URL: %s', $m);
182 $torrentlist{$torrentindex++} = {'CHANNEL' => $target, 'NICK' => $nick, 'URL' => $m};
184 # Remove the matched part from the message and try again (there may be
188 $message =~ m|(http://.*\.torrent)|;
195 # Handle the queue of unhandled torrents
197 my ($subcmd, $id, @params) = @_;
199 if ('remove' eq $subcmd) {
201 delete($torrentlist{$id});
203 } elsif ('clear' eq $subcmd) {
205 } elsif ('confirm' eq $subcmd) {
207 return unless(defined($id) and exists($torrentlist{$id}));
209 $u = $torrentlist{$id}->{'URL'};
211 write_debug('Sending %s to rtorrent', $u);
212 unless(defined($rtorrent->load_start($u))) {
213 write_irssi('%%RError sending URL %s: %s', $u, $rtorrent->errstr());
215 write_irssi('%s enqueued', $u);
216 delete($torrentlist{$id});
218 } elsif ('add' eq $subcmd) {
219 unless(defined($id)) {
222 $torrentlist{$torrentindex++} = {'CHANNEL' => '', 'NICK' => '', 'URL' => $id};
223 } elsif (('list' eq $subcmd) or !defined($subcmd)) {
225 write_irssi('List of queued torrents');
226 if (0 == scalar(keys(%torrentlist))) {
227 write_irssi(' (no torrents in local queue)');
229 foreach (sort(keys(%torrentlist))) {
230 write_irssi(' %3d: %s@%s: %s', $_,
231 $torrentlist{$_}->{'NICK'},
232 $torrentlist{$_}->{'CHANNEL'},
233 $torrentlist{$_}->{'URL'});
237 write_irssi('Unknown subcommand: %s', $subcmd);
241 # Handle the remote rtorrent queue
243 my ($subcmd, $id, @params) = @_;
246 if (('list' eq $subcmd) or !defined($subcmd)) {
247 unless(defined($rqueue = $rtorrent->download_list())) {
248 write_irssi('Error getting list of downloads: %s', $rtorrent->errstr());
252 write_irssi('List of rempote torrents');
253 if (0 == scalar(@{$rqueue})) {
254 write_irssi(' (no torrents in remote queue)');
256 foreach (@{$rqueue}) {
257 write_irssi(' %s%s: %sB/%sB done (%d%%), %sB/s up, %sB/s down',
260 format_number($_->[2]),
261 format_number($_->[1]),
262 ($_->[2]*100)/$_->[1],
263 format_number($_->[3]),
264 format_number($_->[4]));
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);
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'});
286 write_irssi('Could not save config to %s: %s', ($conffile, $@));
288 write_irssi('configuration saved to %s', $conffile);
297 if ('global' eq $target) {
298 if(exists($PARAMS->{$key})) {
299 $conf->{'xmlrtorrent'}->{$key} = $val;
300 if ('XMLURL' eq $key) {
301 unless(defined($rtorrent = xmlrtorrent->new(
302 'XMLURL' => $conf->{'xmlrtorrent'}->{'XMLURL'},
303 'USERNAME' => $conf->{'xmlrtorrent'}->{'USERNAME'},
304 'USERNAME' => $conf->{'xmlrtorrent'}->{'PASSWORD'}))) {
305 write_irssi('Could not initialize XMLRPC instance');
310 write_irssi('Key %s does not exist', $key);
326 write_irssi(<<'EOT');
328 save: save the current configuration
329 help: display this help or module specific help
330 talker [modulename]: display or set the talker to use
331 debug: enable debugging messages
332 nodebug: disable debugging messages
340 if (defined($target)) {
341 foreach $p (@talkers) {
342 if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'talker')) {
344 $conf->{'videosite'}->{'talker'} = $target;
348 write_irssi('No such talker');
350 write_irssi('Current talker: %s', $conf->{'videosite'}->{'talker'});
357 sub sig_command_script_unload {
359 if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
374 opendir(D, $dir) || return ();
375 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
379 write_debug('Trying to load %s:', $p);
381 eval qq{ require xmlrtorrent::$p; };
383 write_irssi('Failed to load plugin: %s', "$@");
387 $g = eval qq{ xmlrtorrent::$p->new(); };
389 write_irssi('Failed to instanciate: %s', "$@");
394 write_debug('found %s %s', $g->{'TYPE'}, $g->{'NAME'});
395 if ($type eq $g->{'TYPE'}) {
397 $g->setio(sub {Irssi::print(shift)});
399 write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
404 write_debug('Loaded %d plugins', $#g+1);
409 sub _load_modules($) {
413 foreach (keys(%INC)) {
414 if ($INC{$_} =~ m|^$path|) {
415 write_debug('Removing %s from $INC', $_);
419 @talkers = ploader($path, '.*Talker\.pm$', 'talker');
422 sub init_xmlrtorrent {
424 my $bindings = shift;
427 unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
428 # No config, start with an empty one
429 write_debug('No config found, using defaults');
430 $conf = { 'xmlrtorrent' => { }};
432 foreach (keys(%{$PARAMS})) {
433 unless (exists($conf->{'xmlrtorrent'}->{$_})) {
434 $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
438 _load_modules($plugindir);
440 unless (defined(@talkers)) {
441 write_irssi('No talkers found, can not proceed.');
445 $talker = $talkers[0];
446 foreach $p (@talkers) {
447 if ($conf->{'xmlrtorrent'}->{'talker'} eq $p->{'NAME'}) {
451 write_debug(undef, 'Selected %s as talker', $talker->{'NAME'});
452 $conf->{'videosite'}->{'talker'} = $talker->{'NAME'};
456 %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
457 %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
458 $torrentindex = max(keys(%torrentlist)) + 1;
460 unless(defined($rtorrent = xmlrtorrent->new(
461 'XMLURL' => $conf->{'xmlrtorrent'}->{'XMLURL'},
462 'USERNAME' => $conf->{'xmlrtorrent'}->{'USERNAME'},
463 'USERNAME' => $conf->{'xmlrtorrent'}->{'PASSWORD'}))) {
464 write_irssi('Could not initialize XMLRPC instance');
470 Irssi::signal_add_first('command script load', 'sig_command_script_unload');
471 Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
472 Irssi::signal_add('setup saved', 'cmd_save');
475 Irssi::command_bind('torrent' => \&cmdhandler);
478 write_irssi('xmlrtorrent initialized');
482 my ($complist, $window, $word, $linestart, $want_space) = @_;
485 if ($linestart !~ m|^/torrent\b|) {
491 Irssi::signal_stop();
495 my ($data, $server, $witem) = @_;
496 my ($cmd, @params) = split(/\s+/, $data);
500 if (exists($xmlrtorrent_commands->{$cmd})) {
501 $xmlrtorrent_commands->{$cmd}->(@params);
503 write_irssi('Unknown command: %s', $cmd);
509 unshift(@INC, $scriptdir);