blib/lib/Net/BitTorrent/Protocol/BEP53.pm untested

filter: Statementstmt 0.0% 0 / 63 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 103 SCAR 42.8
CC
8
Cov
0%
parse
42.0
_decode_base32
12.0
BEGIN
2.0
CRAP 72.0
1 use v5.40;
2 use feature 'class';
3 no warnings 'experimental::class';
4 use Net::BitTorrent::Emitter;
5 #
6 class Net::BitTorrent::Protocol::BEP53 v2.1.0 : isa(Net::BitTorrent::Emitter) {
7 use URI::Escape qw[uri_unescape uri_escape];
8 #
9 field $infohash_v1 : reader : param = undef;
10 field $infohash_v2 : reader : param = undef;
11 field $trackers : reader : param = [];
12 field $name : reader : param = undef;
13 field $nodes : reader : param = []; # DHT bootstrap nodes (x.pe)
14  
15 #
16 sub parse ( $class, $uri ) {
17 die 'Not a magnet URI' unless $uri =~ /^magnet:\?/;
18 my %params;
19 my $query = substr( $uri, 8 );
20 for my $pair ( split( /[&;]/, $query ) ) {
21 my ( $key, $val ) = split( /=/, $pair, 2 );
22 next unless defined $key && defined $val;
23 $val = uri_unescape($val);
24 push @{ $params{$key} }, $val;
25 }
26 my ( $v1, $v2 );
27 for my $xt ( @{ $params{xt} // [] } ) {
28 if ( $xt =~ /^urn:btih:([a-fA-F0-9]{40})$/ ) {
29 $v1 = pack( 'H*', $1 );
30 }
31 elsif ( $xt =~ /^urn:btih:([a-zA-Z2-7]{32})$/ ) {
32  
33 # Base32 encoded (v1)
34 $v1 = _decode_base32($1);
35 }
36 elsif ( $xt =~ /^urn:btmh:1220([a-fA-F0-9]{64})$/ ) {
37  
38 # BEP 53 v2 (multihash SHA-256)
39 $v2 = pack( 'H*', $1 );
40 }
41 }
42 return $class->new(
43 infohash_v1 => $v1,
44 infohash_v2 => $v2,
45 trackers => ( $params{tr} // [] ),
46 name => ( $params{dn}[0] // undef ),
47 nodes => ( $params{'x.pe'} // [] ),
48 );
49 }
50  
51 sub _decode_base32 ($str) {
52 $str = uc($str);
53 my $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
54 my %map;
55 @map{ split //, $alphabet } = 0 .. 31;
56 my $buffer = 0;
57 my $bits = 0;
58 my $res = '';
59 for my $char ( split //, $str ) {
60 next unless exists $map{$char};
61 $buffer = ( $buffer << 5 ) | $map{$char};
62 $bits += 5;
63 if ( $bits >= 8 ) {
64 $bits -= 8;
65 $res .= chr( ( $buffer >> $bits ) & 0xFF );
66 $buffer &= ( 1 << $bits ) - 1;
67 }
68 }
69 return $res;
70 }
71  
72 method to_string () {
73 my @pairs;
74 push @pairs, 'xt=urn:btih:' . unpack( 'H*', $infohash_v1 ) if $infohash_v1;
75 push @pairs, 'xt=urn:btmh:1220' . unpack( 'H*', $infohash_v2 ) if $infohash_v2;
76 push @pairs, 'dn=' . uri_escape($name) if defined $name;
77 push @pairs, 'tr=' . uri_escape($_) for @$trackers;
78 push @pairs, 'x.pe=' . uri_escape($_) for @$nodes;
79 'magnet:?' . join( '&', @pairs );
80 }
81 };
82 #
83 1;