File: DownloadManager.pm

package info (click to toggle)
qt4-perl 4.8.4-1.2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,636 kB
  • ctags: 8,100
  • sloc: perl: 42,963; cpp: 28,039; makefile: 160; xml: 98; sh: 4
file content (187 lines) | stat: -rw-r--r-- 4,288 bytes parent folder | download | duplicates (3)
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
package DownloadManager;

use strict;
use warnings;
use QtCore4;
use QtNetwork4;
use QtCore4::isa qw( Qt::Object );
use TextProgressBar;
use QtCore4::signals
    finished => [];

use QtCore4::slots
    startNextDownload => [],
    downloadProgress => ['qint64', 'qint64'],
    downloadFinished => [],
    downloadReadyRead => [];

use Scalar::Util qw( reftype );

sub manager() {
    return this->{manager};
}

sub downloadQueue() {
    return this->{downloadQueue};
}

sub currentDownload() {
    return this->{currentDownload};
}

sub output() {
    return this->{output};
}

sub downloadTime() {
    return this->{downloadTime};
}

sub progressBar() {
    return this->{progressBar};
}

sub downloadedCount() {
    return this->{downloadedCount};
}

sub totalCount() {
    return this->{totalCount};
}

sub NEW
{
    my ($class, $parent) = @_;
    $class->SUPER::NEW($parent);
    this->{downloadedCount} = 0;
    this->{totalCount} = 0;
    this->{manager} = Qt::NetworkAccessManager();
    this->{output} = Qt::File();
    this->{downloadTime} = Qt::Time();
    this->{progressBar} = TextProgressBar->new();
    this->{downloadQueue} = [];
}

sub append
{
    my ($url) = @_;
    if ( reftype( $url ) eq 'ARRAY' ) {
        foreach my $url2 ( @{$url} ) {
            append(Qt::Url::fromEncoded(Qt::ByteArray($url2)));
        }
        if (scalar @{downloadQueue()} == 0) {
            Qt::Timer::singleShot(0, this, SIGNAL 'finished()');
        }
        return;
    }

    if (scalar @{downloadQueue()} == 0) {
        Qt::Timer::singleShot(0, this, SLOT 'startNextDownload()');
    }
    push @{downloadQueue()}, $url;
    ++(this->{totalCount});
}

sub saveFileName
{
    my ($url) = @_;
    my $path = $url->path();
    my $basename = Qt::FileInfo($path)->fileName();

    if (!defined $basename) {
        $basename = 'download';
    }

    if (Qt::File::exists($basename)) {
        # already exists, don't overwrite
        my $i = 0;
        $basename .= '.';
        while (Qt::File::exists($basename . $i)) {
            ++$i;
        }

        $basename .= $i;
    }

    return $basename;
}

sub startNextDownload
{
    if (scalar @{downloadQueue()} == 0) {
        printf "%d/%d files downloaded successfully\n", downloadedCount(), totalCount();
        emit finished();
        return;
    }

    my $url = shift @{downloadQueue()};

    my $filename = saveFileName($url);
    output()->setFileName($filename);
    if (!output()->open(Qt::IODevice::WriteOnly())) {
        printf STDERR "Problem opening save file '%s' for download '%s': %s\n",
               $filename, $url->toEncoded()->constData(),
               output()->errorString();

        startNextDownload();
        return;                 # skip this download
    }

    my $request = Qt::NetworkRequest($url);
    this->{currentDownload} = manager()->get($request);
    this->connect(currentDownload, SIGNAL 'downloadProgress(qint64,qint64)',
            SLOT 'downloadProgress(qint64,qint64)');
    this->connect(currentDownload, SIGNAL 'finished()',
            SLOT 'downloadFinished()');
    this->connect(currentDownload, SIGNAL 'readyRead()',
            SLOT 'downloadReadyRead()');

    # prepare the output
    printf "Downloading %s...\n", $url->toEncoded()->constData();
    downloadTime()->start();
}

sub downloadProgress
{
    my ($bytesReceived, $bytesTotal) = @_;
    progressBar()->setStatus($bytesReceived, $bytesTotal);

    # calculate the download speed
    my $speed = $bytesReceived * 1000.0 / downloadTime()->elapsed();
    my $unit;
    if ($speed < 1024) {
        $unit = 'bytes/sec';
    } elsif ($speed < 1024*1024) {
        $speed /= 1024;
        $unit = 'kB/s';
    } else {
        $speed /= 1024*1024;
        $unit = 'MB/s';
    }

    progressBar()->setMessage(sprintf '%03f %s', $speed, $unit);
    progressBar()->update();
}

sub downloadFinished
{
    progressBar()->clear();
    output()->close();

    if (currentDownload->error() != Qt::NetworkReply::NoError()) {
        # download failed
        printf STDERR "Failed: %s\n", currentDownload->errorString();
    } else {
        printf "Succeeded.\n";
        ++(this->{downloadedCount});
    }

    startNextDownload();
}

sub downloadReadyRead
{
    output()->write(currentDownload->readAll());
}

1;