Guest User

Untitled

a guest
Jul 16th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. #!perl -I../lib
  2. use strict;
  3. use warnings;
  4. use Getopt::Long;
  5. use Net::BitTorrent;
  6. $|++;
  7. my ($port, $int) = (0, 0);
  8. GetOptions q[port:i] => \$port;
  9. my @t = grep {-e} @ARGV;
  10. @t || exit printf q[%s [-port \d] some.torrent [another.torrent ...]], $0;
  11. my $bt = new Net::BitTorrent({LocalPort => $port})
  12. || die sprintf q[Failed to create N::B object (%s)], $^E;
  13. $SIG{q[INT]} = sub {
  14. $int = $int + 3 > time ? exit : time;
  15. for ($bt, values %{$bt->torrents}) { printf qq[%s\n], $_->as_string(1) }
  16. };
  17. $bt->on_event(
  18. q[piece_hash_pass],
  19. sub {
  20. my ($s, $a) = @_;
  21. my $t = $a->{q[Torrent]};
  22. my $h = grep {$_} split //, unpack q[b*], $t->bitfield;
  23. my $w = grep {$_} split //, unpack q[b*], $t->_wanted;
  24. printf qq[+%d: %04d|%s|%4d/%4d|% 3.2f%%\r],
  25. $t->save_resume_data, $a->{q[Index]}, $t->as_string(), $h,
  26. $t->piece_count, 100 - ($w / $t->piece_count * 100);
  27.  
  28. # Report on per-file completion
  29. for my $file (piece_to_file($t, $a->{q[Index]})) {
  30. printf " %s is %03.3f%% complete\n",
  31. $file->path,
  32. $file->_percent_complete;
  33. }
  34. }
  35. );
  36. $bt->on_event(q[file_write],
  37. sub { pop->{q[File]}->torrent->save_resume_data });
  38. for my $_t (@t) {
  39. printf qq[Loading '%s'...\n], $_t;
  40. my $t = $bt->add_torrent({Path => $_t, Resume => $_t . q[.resume]})
  41. || warn sprintf q[Cannot load %s: %s], $_t, $^E && next;
  42. $t->hashcheck;
  43. $t->start;
  44. }
  45. $bt->do_one_loop(0.5) && sleep 1 while 1;
  46.  
  47. sub piece_to_file {
  48. my ($t, $i) = @_; # torrent, piece_index
  49. my @files;
  50. my $file_index = 0;
  51. my $total_offset = $i * $t->raw_data(1)->{q[info]}{q[piece length]};
  52. my $length = ($i == ($t->piece_count - 1)
  53. ? ($t->size % $t->raw_data(1)->{q[info]}{q[piece length]})
  54. : $t->raw_data(1)->{q[info]}{q[piece length]}
  55. );
  56. SEARCH:
  57. while ($total_offset > $t->files->[$file_index]->size) {
  58. $total_offset -= $t->files->[$file_index]->size;
  59. $file_index++;
  60. last SEARCH
  61. if not defined $t->files->[$file_index]->size;
  62. }
  63. FILE: while ((defined $length) && ($length > 0)) {
  64. my $this_read =
  65. (($total_offset + $length) >= $t->files->[$file_index]->size)
  66. ? ($t->files->[$file_index]->size - $total_offset)
  67. : $length;
  68. push @files, $t->files->[$file_index];
  69. $file_index++;
  70. $length -= $this_read;
  71. last FILE if not defined $t->files->[$file_index];
  72. $total_offset = 0;
  73. }
  74. return @files;
  75. }
Add Comment
Please, Sign In to add comment