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);
18 my $conffile = File::Spec->catfile(Irssi::get_irssi_dir(), 'xmlrtorrent.xml');
19 my $scriptdir = File::Spec->catfile(Irssi::get_irssi_dir(), 'scripts');
20 my $plugindir = File::Spec->catfile($scriptdir, 'xmlrtorrent');
24 my @outputstack = (undef);
33 # "message public", SERVER_REC, char *msg, char *nick, char *address, char *target
34 signal_add_last("message public" => sub {check_for_link(\@_,1,4,2,0);});
35 # "message own_public", SERVER_REC, char *msg, char *target
36 signal_add_last("message own_public" => sub {check_for_link(\@_,1,2,-1,0);});
38 # "message private", SERVER_REC, char *msg, char *nick, char *address
39 signal_add_last("message private" => sub {check_for_link(\@_,1,-1,2,0);});
40 # "message own_private", SERVER_REC, char *msg, char *target, char *orig_target
41 signal_add_last("message own_private" => sub {check_for_link(\@_,1,2,-1,0);});
43 # "message irc action", SERVER_REC, char *msg, char *nick, char *address, char *target
44 signal_add_last("message irc action" => sub {check_for_link(\@_,1,4,2,0);});
45 # "message irc own_action", SERVER_REC, char *msg, char *target
46 signal_add_last("message irc own_action" => sub {check_for_link(\@_,1,2,-1,0);});
49 signal_add_first('complete word', \&sig_complete);
51 my $xmlrtorrent_commands = {
82 write_irssi('Enabled debugging');
87 write_irssi('Disabled debugging');
91 # This is shamelessly stolen from pythons urlgrabber
95 my @symbols = ('', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y');
96 my $step = $SI?1000:1024;
99 my $max_depth = $#symbols;
102 while (($number > $thresh) and ($depth < $max_depth)) {
107 if ($number =~ /^[+-]?\d+$/) {
110 } elsif ($number < 9.95) {
115 return sprintf($format, $number, $symbols[$depth]);
120 my $output = $outputstack[0];
122 my $format = '%%mxmlrtorrent: %%n' . shift(@text);
124 # escape % in parameters from irssi
125 s/%/%%/g foreach @text;
127 if (defined($output) and ref($output)) {
128 $output->print(sprintf($format, @text), MSGLEVEL_CLIENTCRAP);
130 Irssi::print(sprintf($format, @text));
136 unshift(@outputstack, shift);
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];
159 if (defined $server) {
160 $witem = $server->window_item_find($target);
162 $witem = Irssi::window_item_find($target);
165 # Look if we should ignore this line
166 if ($message =~ m,(?:\s|^)/nosave(?:\s|$),) {
172 # Look if there is a torrent link in there
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};
182 # Handle the queue of unhandled torrents
184 my ($subcmd, $id, @params) = @_;
186 if ('remove' eq $subcmd) {
188 delete($torrentlist{$id});
190 } elsif ('clear' eq $subcmd) {
192 } elsif ('confirm' eq $subcmd) {
194 return unless(defined($id) and exists($torrentlist{$id}));
196 $u = $torrentlist{$id}->{'URL'};
198 write_debug('Sending %s to rtorrent', $u);
199 unless(defined($talker->load_start($u))) {
200 write_irssi('%%RError sending URL %s: %s', $u, $talker->errstr());
202 write_irssi('%s enqueued', $u);
203 delete($torrentlist{$id});
205 } elsif ('add' eq $subcmd) {
206 unless(defined($id)) {
209 $torrentlist{$torrentindex++} = {'CHANNEL' => '', 'NICK' => '', 'URL' => $id};
210 } elsif (('list' eq $subcmd) or !defined($subcmd)) {
212 write_irssi('List of queued torrents');
213 if (0 == scalar(keys(%torrentlist))) {
214 write_irssi(' (no torrents in local queue)');
216 foreach (sort(keys(%torrentlist))) {
217 write_irssi(' %3d: %s@%s: %s', $_,
218 $torrentlist{$_}->{'NICK'},
219 $torrentlist{$_}->{'CHANNEL'},
220 $torrentlist{$_}->{'URL'});
224 write_irssi('Unknown subcommand: %s', $subcmd);
228 # Handle the remote rtorrent queue
230 my ($subcmd, $id, @params) = @_;
233 if (('list' eq $subcmd) or !defined($subcmd)) {
234 unless(defined($rqueue = $talker->download_list())) {
235 write_irssi('Error getting list of downloads: %s', $talker->errstr());
239 write_irssi('List of remote torrents');
240 if (0 == scalar(@{$rqueue})) {
241 write_irssi(' (no torrents in remote queue)');
243 foreach (@{$rqueue}) {
244 write_irssi(' %s%s: %sB/%sB done (%d%%), %sB/s up, %sB/s down',
245 $_->{'ACTIVE'}?'*':' ',
247 format_number($_->{'BYTES_DONE'}),
248 format_number($_->{'SIZE_BYTES'}),
249 $_->{'BYTES_DONE'}*100/$_->{'SIZE_BYTES'},
250 format_number($_->{'UP_RATE'}),
251 format_number($_->{'DOWN_RATE'}));
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);
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'});
273 write_irssi('Could not save config to %s: %s', ($conffile, $@));
275 write_irssi('configuration saved to %s', $conffile);
285 foreach $p (@talkers) {
286 if ($p->{'NAME'} eq $target) {
287 $p->setval($key, $val);
291 write_irssi('No such module');
299 if (defined($target)) {
300 foreach $p (@talkers) {
301 if ($p->{'NAME'} eq $target) {
302 write_irssi($p->getconfstr());
306 write_irssi('No such module');
308 write_irssi('Loaded talkers:');
309 foreach $p (@talkers) {
310 write_irssi(' %s', $p->{'NAME'});
319 if (defined($target)) {
320 foreach $p (@talkers) {
321 if ($p->{'NAME'} eq $target) {
322 write_irssi($p->gethelpstr());
326 write_irssi('No such module');
328 write_irssi(<<'EOT');
330 save: save the current configuration
331 help [modulename]: display this help or module specific help
332 show [modulename]: show loaded modules or the current parameters of a module
333 talker [modulename]: display or set the talker to use
334 debug: enable debugging messages
335 nodebug: disable debugging messages
345 if (defined($target)) {
346 foreach $p (@talkers) {
347 if (($p->{'NAME'} eq $target) && ($p->{'TYPE'} eq 'talker')) {
349 $conf->{'xmlrtorrent'}->{'talker'} = $target;
353 write_irssi('No such talker');
355 write_irssi('Current talker: %s', $conf->{'xmlrtorrent'}->{'talker'});
362 sub sig_command_script_unload {
364 if ($script =~ /(.*\/)?xmlrtorrent(\.pl)?$/) {
379 opendir(D, $dir) || return ();
380 @list = grep {/$pattern/ && -f File::Spec->catfile($dir, $_) } readdir(D);
384 write_debug('Trying to load %s:', $p);
386 eval qq{ require xmlrtorrent::$p; };
388 write_irssi('Failed to load plugin: %s', "$@");
392 $g = eval qq{ xmlrtorrent::$p->new(); };
394 write_irssi('Failed to instanciate: %s', "$@");
399 write_debug('found %s %s', $g->{'TYPE'}, $g->{'NAME'});
400 if ($type eq $g->{'TYPE'}) {
402 $g->setio(sub {Irssi::print(shift)});
404 write_irssi('%s has wrong type (got %s, expected %s)', $p, $g->{'TYPE'}, $type);
409 write_debug('Loaded %d plugins', $#g+1);
414 sub _load_modules($) {
418 foreach (keys(%INC)) {
419 if ($INC{$_} =~ m|^$path|) {
420 write_debug('Removing %s from $INC', $_);
424 @talkers = ploader($path, '.*Talker\.pm$', 'talker');
427 sub init_xmlrtorrent {
429 my $bindings = shift;
432 unless(-r $conffile && defined($conf = XML::Simple::XMLin($conffile, ForceArray => ['config', 'option'], KeepRoot => 1, KeyAttr => {'config' => 'module', 'option' => 'key'}))) {
433 # No config, start with an empty one
434 write_debug('No config found, using defaults');
435 $conf = { 'xmlrtorrent' => { }};
437 foreach (keys(%{$PARAMS})) {
438 unless (exists($conf->{'xmlrtorrent'}->{$_})) {
439 $conf->{'xmlrtorrent'}->{$_} = $PARAMS->{$_};
443 _load_modules($plugindir);
445 unless (defined(@talkers)) {
446 write_irssi('No talkers found, can not proceed.');
450 $talker = $talkers[0];
451 foreach $p (@talkers) {
452 if ($conf->{'xmlrtorrent'}->{'talker'} eq $p->{'NAME'}) {
456 write_debug('Selected %s as talker', $talker->{'NAME'});
457 $conf->{'xmlrtorrent'}->{'talker'} = $talker->{'NAME'};
459 # Loop through all plugins and load the config
460 foreach $p (@talkers) {
461 $conf->{'xmlrtorrent'}->{'config'}->{$p->{'NAME'}} = $p->mergeconfig($conf->{'xmlrtorrent'}->{'config'}->{$p->{'NAME'}});
465 %torrentlist = %{$conf->{'xmlrtorrent'}->{'_QUEUE'}};
466 %torrentlist = map { my $a = substr($_, 1); ("$a" => $torrentlist{$_}) } keys(%torrentlist);
467 $torrentindex = max(keys(%torrentlist)) + 1;
471 Irssi::signal_add_first('command script load', 'sig_command_script_unload');
472 Irssi::signal_add_first('command script unload', 'sig_command_script_unload');
473 Irssi::signal_add('setup saved', 'cmd_save');
476 Irssi::command_bind('torrent' => \&cmdhandler);
479 write_irssi('xmlrtorrent initialized');
483 my ($complist, $window, $word, $linestart, $want_space) = @_;
486 if ($linestart !~ m|^/torrent\b|) {
492 Irssi::signal_stop();
496 my ($data, $server, $witem) = @_;
497 my ($cmd, @params) = split(/\s+/, $data);
501 if (exists($xmlrtorrent_commands->{$cmd})) {
502 $xmlrtorrent_commands->{$cmd}->(@params);
504 write_irssi('Unknown command: %s', $cmd);
510 unshift(@INC, $scriptdir);