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($talker, $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($talker))) {
248 write_irssi('Error getting list of downloads: %s', $rtorrent->errstr());
252 write_irssi('List of remote 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);
298 foreach $p (@talkers) {
299 if ($p->{'NAME'} eq $target) {
300 $p->setval($key, $val);
304 write_irssi(undef, 'No such module');
312 if (defined($target)) {
313 foreach $p (@talkers) {
314 if ($p->{'NAME'} eq $target) {
315 write_irssi($p->getconfstr());
319 write_irssi('No such module');
321 write_irssi('Loaded talkers:');
322 foreach $p (@talkers) {
323 write_irssi(' %s', $p->{'NAME'});
332 if (defined($target)) {
333 foreach $p (@talkers) {
334 if ($p->{'NAME'} eq $target) {
335 write_irssi($p->gethelpstr());
339 write_irssi('No such module');
341 write_irssi(<<'EOT');
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
358 if (defined($target)) {
359 foreach $p (@talkers) {
360 if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'talker')) {
362 $conf->{'videosite'}->{'talker'} = $target;
366 write_irssi('No such talker');
368 write_irssi('Current talker: %s', $conf->{'videosite'}->{'talker'});
375 sub sig_command_script_unload {
377 if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
392 opendir(D, $dir) || return ();
393 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
397 write_debug('Trying to load %s:', $p);
399 eval qq{ require xmlrtorrent::$p; };
401 write_irssi('Failed to load plugin: %s', "$@");
405 $g = eval qq{ xmlrtorrent::$p->new(); };
407 write_irssi('Failed to instanciate: %s', "$@");
412 write_debug('found %s %s', $g->{'TYPE'}, $g->{'NAME'});
413 if ($type eq $g->{'TYPE'}) {
415 $g->setio(sub {Irssi::print(shift)});
417 write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
422 write_debug('Loaded %d plugins', $#g+1);
427 sub _load_modules($) {
431 foreach (keys(%INC)) {
432 if ($INC{$_} =~ m|^$path|) {
433 write_debug('Removing %s from $INC', $_);
437 @talkers = ploader($path, '.*Talker\.pm$', 'talker');
440 sub init_xmlrtorrent {
442 my $bindings = shift;
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' => { }};
450 foreach (keys(%{$PARAMS})) {
451 unless (exists($conf->{'xmlrtorrent'}->{$_})) {
452 $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
456 _load_modules($plugindir);
458 unless (defined(@talkers)) {
459 write_irssi('No talkers found, can not proceed.');
463 $talker = $talkers[0];
464 foreach $p (@talkers) {
465 if ($conf->{'xmlrtorrent'}->{'talker'} eq $p->{'NAME'}) {
469 write_debug(undef, 'Selected %s as talker', $talker->{'NAME'});
470 $conf->{'videosite'}->{'talker'} = $talker->{'NAME'};
474 %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
475 %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
476 $torrentindex = max(keys(%torrentlist)) + 1;
478 unless(defined($rtorrent = xmlrtorrent->new())) {
479 write_irssi('Could not initialize XMLRPC instance');
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');
490 Irssi::command_bind('torrent' => \&cmdhandler);
493 write_irssi('xmlrtorrent initialized');
497 my ($complist, $window, $word, $linestart, $want_space) = @_;
500 if ($linestart !~ m|^/torrent\b|) {
506 Irssi::signal_stop();
510 my ($data, $server, $witem) = @_;
511 my ($cmd, @params) = split(/\s+/, $data);
515 if (exists($xmlrtorrent_commands->{$cmd})) {
516 $xmlrtorrent_commands->{$cmd}->(@params);
518 write_irssi('Unknown command: %s', $cmd);
524 unshift(@INC, $scriptdir);