This file is indexed.

/usr/share/rtpg-www/lib/RTPG.pm is in rtpg-www 0.2.11-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
#!/usr/bin/perl

use utf8;
use strict;
use warnings;
package RTPG;
use Carp;
use POSIX qw(strftime);
use RTPG::Direct;
use RPC::XML::Client;
use RPC::XML;
use MIME::Types;

use Fcntl qw(:flock);

# international symbols in our commands
$RPC::XML::ENCODING = "UTF-8";

my $SIZE_BY_CHUNKS_LIMIT=1024**3;

=head1 NAME

RTPG - is a module for accessing to rtorrent's SCGI functions.

=head1 VERSION

0.92

=cut

our $VERSION=0.93;

=head1 SYNOPSIS

 use RTPG;

 # standard variant
 my $h = new RTPG(url=>'http://localhost/RPC2');

 # direct connection to rtorrent
 my $h = new RTPG(url=>'localhost:5000');
 my $h = new RTPG(url=>'/path/to/socket.rtorrent');

 # arrayref and error (standard version)
 my ($tlist, $error)=$h->torrents_list;

 # arrayref (died version)
 my $tlist=$h->torrents_list;

 for (@$tlist)
 {
     my $file_list=$h->file_list($_->{hash});
     ..
 }


 # direct commands by RPC
 my $list_methods=$h->rpc_command('system.listMethods');
 my ($list_methods, $error)=$h->rpc_command('system.listMethods');

 # system information (library versions, etc)
 my $hashref=$h->system_information;
 my ($hashref, $error)=$h->system_information;

=head1 METHODS


=head2 new

The constructor. It receives the next options:

=over

=item B<url>

is an address of rtorrent's SCGI (direct) or rtorrent's RPC (standard).

=item B<queue>

if TRUE, commands will process in queue mode (use flock).

=back

=cut

sub new
{
    my ($class, %opts)=@_;
    croak 'XMLRPC url must be defined' unless exists $opts{url};

    # XML::RPC::Client (standard variant)
    if ($opts{url} =~ m{^\w+://})
    {
        my $connect=RPC::XML::Client->new($opts{url});
        unless (ref $connect)
        {
            $!="Error connect to XMLRPC-server: $connect\n";
            return undef;
        }

        return bless {
            standard            =>  1,
            rtorrent_ctl_url    =>  $opts{url},
            connection          =>  $connect,
            queue_mode          =>  $opts{queue} || 0,
        }, $class;
    }

    my $connect=RTPG::Direct->new(url => $opts{url});
    return bless {
        standard            => 0,
        rtorrent_ctl_url    => $opts{url},
        connection          => $connect,
        queue_mode          => $opts{queue} || 0,
    };
}

=head2 rpc_command(CMD[,ARGS])

You can use this method for send commands to rtorrent.

=head3 EXAMPLE

 # standard version
 my ($result, $error)=$h->rpc_command('system.listMethods');

 # died version
 my $result=$h->rpc_command('system.listMethods');

=cut

sub rpc_command
{
    my $self=shift;
    my ($cmd, @args)=@_;
    my $resp;

    flock DATA, LOCK_EX if $self->{queue_mode};
    $resp=$self->{connection}->send_request($cmd, @args);
    flock DATA, LOCK_UN if $self->{queue_mode};

    if (ref $resp)
    {
        if ('RPC::XML::fault' eq ref $resp)
        {
            my $err_str=sprintf
                "Fault when execute command: %s\n" .
                "Fault code: %s\n" .
                "Fault text: %s\n",
                join(' ', $cmd, @args),
                $resp->value->{faultString},
                $resp->value->{faultCode};
            die $err_str unless wantarray;
            return (undef, $err_str);
        }
        return $resp->value unless wantarray;
        return $resp->value, '';
    }
    my $err_str=sprintf
        "Fault when execute command: %s\n" .
        "Fault text: %s\n",
        join(' ', $cmd, @args),
        $resp||'';
    die $err_str unless wantarray;
    return undef, $err_str;
}

=head2 torrents_list([VIEW])

This method returns list of torrents. It is a link to array of hashes.

=head3 EXAMPLE

 # standard version
 my ($tlist, $err)=$h->torrents_list;
 my ($tlist, $err)=$h->torrents_list('started');

 # died version
 my $tlist=$h->torrents_list;
 my $tlist=$h->torrents_list('started');

=head3 views variants

=over

=item default

=item name

=item stopped

=item started

=item complete

=item incomplete

=back

=cut

our $exclude_d_mask = qr{^d\.(?:get_mode|get_custom\D*|get_bitfield)$};

sub torrents_list
{
    my ($self, $view)=@_;
    $view||='default';


    my @iary=eval {
        grep !/$exclude_d_mask/,
        grep /^d\.(?:get_|is_|views\.has$)/, $self->_get_list_methods;
    };

    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }
    my ($list, $error) =
        $self->rpc_command('d.multicall', $view, map { "$_=" } @iary);

    unless (defined $list)
    {
        die $error unless wantarray;
        return undef, $error;
    }

    for (@$list)
    {
        my %info;
        for my $i (0 .. $#iary)
        {
            my $name=$iary[$i];
            $name =~ s/^..(?:get_)?//;
            $info{$name}=$_->[$i];
        }

        # Set download status
        if( $info{hashing} )
        {
            $info{status} = 'hashing';
        }
        elsif( $info{complete} )
        {
            if($info{is_active})
            {
                $info{status} = 'seeding';
            }
            else
            {
                $info{status} = 'finished';
            }
        }
        else
        {
            if($info{is_active})
            {
                $info{status} = 'downloading';
            }
            else
            {
                $info{status} = 'paused';
            }
        }

        $_ = _normalize_one_torrent_info(\%info);
    }

    # Set custom params count
    if( @$list )
    {
        my $count = 0;
        for my $name ( keys %{$list->[0]} )
        {
            next unless $name =~ '^custom(\d+)$';
            $count = $1 if $1 > $count;
        }
        $_->{custom_count} = $count for @$list;
    }

    return $list unless wantarray;
    return $list, '';
}

=head2 torrent_info(tid)

The method returns the link to hash which contains the information about
the torrent (tid);

=head3 EXAMPLE

 my $tlist = $h->torrents_list;
 my $tinfo_first = $tlist->[0];
 my $tinfo_first_second_time
    = $h->torrent_info($tlist->[0]{hash});

=head4 NOTE

Hashes B<$tinfo_first> and B<$tinfo_first_second_time> are equal.
This method can use if You know torrent-id and do not know
an other information about the torrent.

 # standard version
 my ($tinfo, $error)=$h->torrent_info($tid);

 # died version
 my $tinfo=$h->torrent_info($tid);

=cut

sub torrent_info
{
    my ($self, $id)=@_;
    my @iary=eval {
        grep !/$exclude_d_mask/,
        grep /^d\.(get_|is_)/, $self->_get_list_methods;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    my $info={};

    eval
    {
        for my $cmd (@iary)
        {
            my $name=$cmd;
            $name=~s/^..(?:get_)?//;
            $info->{$name}=$self->rpc_command($cmd, $id);
        }
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }
    return _normalize_one_torrent_info($info), '' if wantarray;
    return _normalize_one_torrent_info($info);

}

=head2 file_list(tid)

The method returns the link to array which contains information
about each file that belong to the torrent (tid).

=head3 EXAMPLE

 # standard version
 my ($files, $error)=$h->file_list($tid);

 # died version
 my $files=$h->file_list($tid);

=cut

sub file_list
{
    my ($self, $id)=@_;
    croak "TorrentID must be defined!\n" unless $id;
    my @iary=eval {
        grep /^f\.(get|is)/, $self->_get_list_methods;
    };

    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    my ($chunk_size, $error)=$self->rpc_command('d.get_chunk_size', $id);
    unless (defined $chunk_size)
    {
        die $error unless wantarray;
        return undef, $error;
    }

    my $list;

    ($list, $error) =
        $self->rpc_command('f.multicall', $id, '', map { "$_=" } @iary);
    unless (defined $list)
    {
        die $error unless wantarray;
        return undef, $error;
    }

    my $mimetypes = MIME::Types->new;
    my $unknown   = MIME::Type->new(
        encoding    => 'base64',
        simplified  => 'unknown/unknown',
        type        => 'x-unknown/x-unknown');

    for (@$list)
    {
        my %info;
        for my $i (0 .. $#iary)
        {
            my $name=$iary[$i];
            $name =~ s/^..(?:get_)?//;
            $info{$name}=$_->[$i];
        }
        $_ =  \%info;
        my $size_bytes=1.0*$chunk_size*$_->{size_chunks};
        $_->{size_bytes}=$size_bytes if $size_bytes > $SIZE_BY_CHUNKS_LIMIT;
        $_->{priority_str} =
            ($_->{priority} == 0) ?'off'    :
            ($_->{priority} == 1) ?'normal' :
            ($_->{priority} == 2) ?'high'   :'unknown';
        $_->{percent}=_get_percent_string(
            $_->{completed_chunks},
            $_->{size_chunks}
        );
        $_->{mime} = $mimetypes->mimeTypeOf( $_->{path} ) || $unknown;
    }
    return $list, '' if wantarray;
    return $list;
}

=head2 tracker_list

The method returns information about trackers.

=cut

sub tracker_list
{
    my ($self, $tid) = @_;
    my @cmd = eval {
        grep /^t\.(?:get_|is_)/,
            $self->_get_list_methods
    };

    if ($@) {
        return undef, $@ if wantarray;
        die;
    }

    my ($r, $e) =
        $self->rpc_command('t.multicall', $tid, undef, map { "$_="  } @cmd);

    if ($e) {
        return undef, $e if wantarray;
        die $e;
    }

    @cmd = map { s/^t\.(?:get_)?//; $_ } @cmd;

    for my $t (@$r) {
        $t = { map { ($cmd[$_] => $t->[$_]) } 0 .. $#cmd };
    }

    return ($r, $e) if wantarray;
    return $r;
}

=head2 peer_list(tid)

The method returns information about peers we are connected (by torrent id).

=cut

sub peer_list
{
    my ($self, $tid) = @_;
    my @cmd = eval { grep /^p\.(?:get_|is_)/, $self->_get_list_methods };
    if ($@) {
        return undef, $@ if wantarray;
        die;
    }

    my ($list, $error) = eval {
        $self->rpc_command('p.multicall', $tid, undef, map { "$_=" } @cmd)
    };


    if ($@) {
        return undef, $@ if wantarray;
        die;
    }

    unless($error) {
        for my $item (0 .. $#{$list}) {
            my %h;
            for (0 .. $#cmd) {
                (my $name = $cmd[$_]) =~ s/^p\.(?:get_)?//;
                $h{$name} = $list->[$item][$_];
            }
            $list->[$item] = { %h };
        }
    }

    return ($list, $error) if wantarray;
    return $list unless $error;
    die $error;
}

=head2 set_files_priorities(tid, pri)

This method updates priorities of all files in one torrent

=head3 EXAMPLE

 # standard version
 my $error=$h->set_files_priorities($tid, $pri);
 my ($error)=$h->set_files_priorities($tid, $pri);

 # died version
 $h->set_files_priorities($tid, $pri);

=cut

sub set_files_priorities
{
    my ($self, $id, $pri)=@_;
    my ($list, $error) =
        $self->rpc_command('f.multicall', $id, '', "f.set_priority=$pri");
    return $error if defined wantarray;
    die $error if $error;
    return undef;
}

=head2 set_file_priority

Set file priority

=cut

sub set_file_priority
{
    my ($self, $id, $file_index, $priority) = @_;

    my ($res, $error)=
        $self->rpc_command('f.set_priority', $id, $file_index, $priority);
    unless (defined $res)
    {
        return undef, "$error" if wantarray;
        die $error;
    }

    return $res;
}

=head2 update_priorities

Update priorities before set_file_priority and etc.

=cut

sub update_priorities
{
    my ($self, $id) = @_;

    my ($res, $error)= $self->rpc_command('d.update_priorities', $id);
    unless (defined $res)
    {
        return undef, "$error" if wantarray;
        die $error;
    }

    return $res;
}

=head2 system_information

The method returns the link to hash about system information. The hash
has the fields:

=over

=item B<client_version>

the version of rtorrent.

=item B<library_version>

the version of librtorrent.

=back

=cut

sub system_information
{
    my $self = shift;

    my @info_params = qw(client_version library_version);

    my ($res, $err) = $self->rpc_command(
        'system.multicall', [
            map { { methodName => "system.$_", params => [] } } @info_params
        ]
    );

    if ($err) {
        die $err unless wantarray;
        return (undef, $err);
    }


    my %res;

    for (0 .. $#info_params) {
        $res{ $info_params[$_] } = $res->[$_][0];
    }

    return \%res, '' if wantarray;
    return \%res;
}

=head2 view_list([ARGS])

The method returns information about views in rtorrent.
There are a few additional named arguments:

=over

=item full

if TRUE, method will return additional information about view.

=back

=cut

sub view_list
{
    my ($self, %opts) = @_;

    my $info;

    eval
    {
        $info = $self->rpc_command('view_list');
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }


    if ($opts{full}) {
        for (@$info) {
            my ($tl, $err) = $self->rpc_command(
                'd.multicall', $_, 'd.get_state='
            );

            if ($err) {
                return undef, $err if wantarray;
                die $err;
            }

            $_ = {
                name    => $_,
                count   => scalar(@$tl)
            }
        }
    }

    return $info;
}

=head2 start

Start torrent (tid) download

=cut

sub start
{
    my ($self, $id) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.start',  $id);
        die $err if $err;
        ($res, $err) = $self->rpc_command('d.resume', $id);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die "$@";
    }

    return $res;
}

=head2 stop

Stop torrent (tid) download

=cut

sub stop
{
    my ($self, $id) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.stop', $id);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    return $res;
}

=head2 delete

Delete torrent (tid)

=cut

sub delete
{
    my ($self, $id) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.erase', $id);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    return $res;
}

=head2 pause

Pause torrent (tid)

=cut

sub pause
{
    my ($self, $id) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.pause', $id);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    return $res;
}

=head2 check

Check torrent hash (tid)

=cut

sub check
{
    my ($self, $id) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.check_hash', $id);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    return $res;
}

=head2 priority

Set torrent priority (tid, priority)

=cut

sub priority
{
    my ($self, $id, $priority) = @_;

    my ($res, $err);

    eval
    {
        ($res, $err) = $self->rpc_command('d.set_priority', $id, $priority);
        die $err if $err;
    };
    if ($@)
    {
        return undef, "$@" if wantarray;
        die $@;
    }

    return $res;
}

=head2 set_download_rate

Set maximum download rate for all torrents

=cut

sub set_download_rate
{
    my ($self, $rate) = @_;

    my ($res, $error)=$self->rpc_command('set_download_rate', $rate);
    unless (defined $res)
    {
        return undef, $error if wantarray;
        die $error;
    }

    return $res;
}

=head2 set_upload_rate

Set maximum upload rate for all torrents

=cut

sub set_upload_rate
{
    my ($self, $rate) = @_;

    my ($res, $error)=$self->rpc_command('set_upload_rate', $rate);
    unless (defined $res)
    {
        return undef, $error if wantarray;
        die $error;
    }

    return $res;
}

=head2 rates

Return varios current speed rates and etc.

=cut
sub rates
{
    my ($self, $param)=@_;

    my (%info, $error);

    ($info{download_rate}, $error) = $self->rpc_command('get_download_rate')
        unless $error;
    ($info{upload_rate},   $error) = $self->rpc_command('get_upload_rate')
        unless $error;

    if ($error)
    {
        return undef, $error if wantarray;
        die $error;
    }
    return \%info;
}

=head2 add

Add new torrent for download from url list or filehandle. If $start is TRUE then
torrent immediately start after load.

=cut

sub add
{
    my ($self, $param, $start) = @_;

    $param = [ $param ] unless 'ARRAY' eq ref $param;

    my ($res, $error);

    for (@$param)
    {
        if(ref $_)
        {
            local $/;
            binmode $_;
            my $torrent = RPC::XML::base64->new(<$_>);
            my $sub = 'load_raw';
            $sub = 'load_raw_start' if $start;
            ($res, $error) = $self->rpc_command($sub => $torrent);
        }
        else
        {
            my $url = RPC::XML::base64->new($_);
            my $sub = 'load';
            $sub = 'load_start' if $start;
            ($res, $error) = $self->rpc_command($sub => $url);
        }
    }

    if ($error)
    {
        return undef, $error if wantarray;
        die $error;
    }

    return $res;
}

=head1 PRIVATE METHODS

=head2 _get_list_methods

returns list of rtorrent commands

=cut

sub _get_list_methods
{
    my $self=shift;
    return @{ $self->{listMethods} } if $self->{listMethods};
    my $list = $self->rpc_command('system.listMethods');
    return @$list;
}

=head2 _get_percent_string(PART_OF_VALUE,VALUE)

counts percent by pair values

=cut

sub _get_percent_string($$)
{
    my ($part, $full)=@_;
    return undef unless $full;
    return undef unless defined $part;
    return undef if $part<0;
    return undef if $full<0;
    return undef if $part>$full;
    my $percent=$part*100/$full;
    if ($percent<10)
    {
        $percent=sprintf '%1.2f', $percent;
    }
    else
    {
        $percent=sprintf '%1.1f', $percent;
    }
    s/(?<=\.\d)0$//, s/\.00?$// for $percent;
    return "$percent%";
}

=head2 _normalize_one_torrent_info(HASHREF)

=over

=item calculates:

percents, ratio, human_size, human_done,
human_up_total, human_up_rate, human_down_rate

=item fixes:

32bit overflow in libxmlrpc-c3 version < 1.07

=back

=cut

sub _normalize_one_torrent_info($)
{
    my ($info)=@_;

    for ($info)
    {
        $_->{percent} = _get_percent_string(
            $_->{completed_chunks},
            $_->{size_chunks}
        );

        my ($bytes_done, $size_bytes)=
        (
            1.0*$_->{completed_chunks}*$_->{chunk_size},
            1.0*$_->{size_chunks}*$_->{chunk_size}
        );
        $_->{size_bytes}=$size_bytes if $size_bytes>$SIZE_BY_CHUNKS_LIMIT;
        $_->{bytes_done}=$bytes_done if $bytes_done>$SIZE_BY_CHUNKS_LIMIT;
        $_->{up_total}=1.0*$_->{bytes_done}*($_->{ratio}/1000);


        $_->{ratio}=sprintf '%1.2f', $_->{ratio}/1000;
        $_->{ratio}=~s/((\.00)|0)$//;

#        $_->{human_size}        = as_human_size(  $_->{size_bytes} );
#        $_->{human_done}        = as_human_size(  $_->{bytes_done} );
#        $_->{human_up_total}    = as_human_size(  $_->{up_total}   );
#        $_->{human_up_rate}     = as_human_speed( $_->{up_rate}    );
#        $_->{human_down_rate}   = as_human_speed( $_->{down_rate}  );
    }
    return $info;
}

=head2 as_human_size(NUM)

converts big numbers to small 1024 = 1K, 1024**2 == 1M, etc

=cut

sub as_human_size($)
{
    my ($size, $sign) = (shift, 1);

    my %result = (
        original    => $size,
        digit       => 0,
        letter      => '',
        human       => 'N/A',
        byte        => '',
    );

    {{
        last unless $size;
        last unless $size >= 0;

        my @suffixes = ('', 'K', 'M', 'G', 'T', 'P', 'E');
        my ($limit, $div) = (1024, 1);
        for (@suffixes)
        {
            if ($size < $limit || $_ eq $suffixes[-1])
            {
                $size = $sign * $size / $div;
                if ($size < 10)
                {
                    $size = sprintf "%1.2f", $size;
                }
                elsif ($size < 50)
                {
                    $size = sprintf "%1.1f", $size;
                }
                else
                {
                    $size = int($size);
                }
                s/(?<=\.\d)0$//, s/\.00?$// for $size;
                $result{digit}  = $size;
                $result{letter} = $_;
                $result{byte}   = 'B';
                last;
            }
            $div = $limit;
            $limit *= 1024;
        }
    }}

    $result{human} = $result{digit} . $result{letter} . $result{byte};

    return ($result{digit}, $result{letter}, $result{byte}, $result{human})
        if wantarray;
    return $result{human};
}

=head2 as_human_speed

As as_human_size, but convert into speed

=cut
sub as_human_speed
{
    my @result = as_human_size(shift);
    my $human = pop @result;
    my $byte = pop @result;
    push @result, 'b',  '/', 's';
    $human = join '', @result;
    push @result, $human;
    return @result if wantarray;
    return $human;
}

=head2 as_human_datetime

Return datetime string from timestemp

=cut

sub as_human_datetime
{
#    return decode utf8 => strftime '%c', localtime shift;
    return strftime '%F %R', localtime shift;
}

=head2 torrent_priority_num

Convert torrent priority name to int

=cut
sub torrent_priority_num
{
    my ($name) = @_;

    # Default normal
    my $num =   ($name eq 'off')    ?0    :
                ($name eq 'low')    ?1    :
                ($name eq 'normal') ?2    :
                ($name eq 'high')   ?3    :2;

    return $num;
}

=head2 file_priority_num

Convert file priority name to int

=cut
sub file_priority_num
{
    my ($name) = @_;

    # Default normal
    my $num =   ($name eq 'off')    ?0    :
                ($name eq 'normal') ?1    :
                ($name eq 'high')   ?2    :1;

    return $num;
}

1;

=head1 AUTHORS

Copyright (C) 2008 Dmitry E. Oboukhov <unera@debian.org>,

Copyright (C) 2008 Roman V. Nikolaev <rshadow@rambler.ru>

=head1 LICENSE

This program is free software: you can redistribute  it  and/or  modify  it
under the terms of the GNU General Public License as published by the  Free
Software Foundation, either version 3 of the License, or (at  your  option)
any later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even  the  implied  warranty  of  MERCHANTABILITY  or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public  License  for
more details.

You should have received a copy of the GNU  General  Public  License  along
with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut

__DATA__
this is lock for this module