Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!perl -I../lib
- use strict;
- use warnings;
- use Getopt::Long;
- use Net::BitTorrent;
- $|++;
- my ($port, $int) = (0, 0);
- GetOptions q[port:i] => \$port;
- my @t = grep {-e} @ARGV;
- @t || exit printf q[%s [-port \d] some.torrent [another.torrent ...]], $0;
- my $bt = new Net::BitTorrent({LocalPort => $port})
- || die sprintf q[Failed to create N::B object (%s)], $^E;
- $SIG{q[INT]} = sub {
- $int = $int + 3 > time ? exit : time;
- for ($bt, values %{$bt->torrents}) { printf qq[%s\n], $_->as_string(1) }
- };
- $bt->on_event(
- q[piece_hash_pass],
- sub {
- my ($s, $a) = @_;
- my $t = $a->{q[Torrent]};
- my $h = grep {$_} split //, unpack q[b*], $t->bitfield;
- my $w = grep {$_} split //, unpack q[b*], $t->_wanted;
- printf qq[+%d: %04d|%s|%4d/%4d|% 3.2f%%\r],
- $t->save_resume_data, $a->{q[Index]}, $t->as_string(), $h,
- $t->piece_count, 100 - ($w / $t->piece_count * 100);
- # Report on per-file completion
- for my $file (piece_to_file($t, $a->{q[Index]})) {
- printf " %s is %03.3f%% complete\n",
- $file->path,
- $file->_percent_complete;
- }
- }
- );
- $bt->on_event(q[file_write],
- sub { pop->{q[File]}->torrent->save_resume_data });
- for my $_t (@t) {
- printf qq[Loading '%s'...\n], $_t;
- my $t = $bt->add_torrent({Path => $_t, Resume => $_t . q[.resume]})
- || warn sprintf q[Cannot load %s: %s], $_t, $^E && next;
- $t->hashcheck;
- $t->start;
- }
- $bt->do_one_loop(0.5) && sleep 1 while 1;
- sub piece_to_file {
- my ($t, $i) = @_; # torrent, piece_index
- my @files;
- my $file_index = 0;
- my $total_offset = $i * $t->raw_data(1)->{q[info]}{q[piece length]};
- my $length = ($i == ($t->piece_count - 1)
- ? ($t->size % $t->raw_data(1)->{q[info]}{q[piece length]})
- : $t->raw_data(1)->{q[info]}{q[piece length]}
- );
- SEARCH:
- while ($total_offset > $t->files->[$file_index]->size) {
- $total_offset -= $t->files->[$file_index]->size;
- $file_index++;
- last SEARCH
- if not defined $t->files->[$file_index]->size;
- }
- FILE: while ((defined $length) && ($length > 0)) {
- my $this_read =
- (($total_offset + $length) >= $t->files->[$file_index]->size)
- ? ($t->files->[$file_index]->size - $total_offset)
- : $length;
- push @files, $t->files->[$file_index];
- $file_index++;
- $length -= $this_read;
- last FILE if not defined $t->files->[$file_index];
- $total_offset = 0;
- }
- return @files;
- }
Add Comment
Please, Sign In to add comment