1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "downloadmanager.h"
52
53#include <QTextStream>
54
55#include <cstdio>
56
57using namespace std;
58
59DownloadManager::DownloadManager(QObject *parent)
60 : QObject(parent)
61{
62}
63
64void DownloadManager::append(const QStringList &urls)
65{
66 for (const QString &urlAsString : urls)
67 append(url: QUrl::fromEncoded(url: urlAsString.toLocal8Bit()));
68
69 if (downloadQueue.isEmpty())
70 QTimer::singleShot(interval: 0, receiver: this, slot: &DownloadManager::finished);
71}
72
73void DownloadManager::append(const QUrl &url)
74{
75 if (downloadQueue.isEmpty())
76 QTimer::singleShot(interval: 0, receiver: this, slot: &DownloadManager::startNextDownload);
77
78 downloadQueue.enqueue(t: url);
79 ++totalCount;
80}
81
82QString DownloadManager::saveFileName(const QUrl &url)
83{
84 QString path = url.path();
85 QString basename = QFileInfo(path).fileName();
86
87 if (basename.isEmpty())
88 basename = "download";
89
90 if (QFile::exists(fileName: basename)) {
91 // already exists, don't overwrite
92 int i = 0;
93 basename += '.';
94 while (QFile::exists(fileName: basename + QString::number(i)))
95 ++i;
96
97 basename += QString::number(i);
98 }
99
100 return basename;
101}
102
103void DownloadManager::startNextDownload()
104{
105 if (downloadQueue.isEmpty()) {
106 printf(format: "%d/%d files downloaded successfully\n", downloadedCount, totalCount);
107 emit finished();
108 return;
109 }
110
111 QUrl url = downloadQueue.dequeue();
112
113 QString filename = saveFileName(url);
114 output.setFileName(filename);
115 if (!output.open(flags: QIODevice::WriteOnly)) {
116 fprintf(stderr, format: "Problem opening save file '%s' for download '%s': %s\n",
117 qPrintable(filename), url.toEncoded().constData(),
118 qPrintable(output.errorString()));
119
120 startNextDownload();
121 return; // skip this download
122 }
123
124 QNetworkRequest request(url);
125 currentDownload = manager.get(request);
126 connect(sender: currentDownload, signal: &QNetworkReply::downloadProgress,
127 receiver: this, slot: &DownloadManager::downloadProgress);
128 connect(sender: currentDownload, signal: &QNetworkReply::finished,
129 receiver: this, slot: &DownloadManager::downloadFinished);
130 connect(sender: currentDownload, signal: &QNetworkReply::readyRead,
131 receiver: this, slot: &DownloadManager::downloadReadyRead);
132
133 // prepare the output
134 printf(format: "Downloading %s...\n", url.toEncoded().constData());
135 downloadTimer.start();
136}
137
138void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
139{
140 progressBar.setStatus(value: bytesReceived, maximum: bytesTotal);
141
142 // calculate the download speed
143 double speed = bytesReceived * 1000.0 / downloadTimer.elapsed();
144 QString unit;
145 if (speed < 1024) {
146 unit = "bytes/sec";
147 } else if (speed < 1024*1024) {
148 speed /= 1024;
149 unit = "kB/s";
150 } else {
151 speed /= 1024*1024;
152 unit = "MB/s";
153 }
154
155 progressBar.setMessage(QString::fromLatin1(str: "%1 %2")
156 .arg(a: speed, fieldWidth: 3, fmt: 'f', prec: 1).arg(a: unit));
157 progressBar.update();
158}
159
160void DownloadManager::downloadFinished()
161{
162 progressBar.clear();
163 output.close();
164
165 if (currentDownload->error()) {
166 // download failed
167 fprintf(stderr, format: "Failed: %s\n", qPrintable(currentDownload->errorString()));
168 output.remove();
169 } else {
170 // let's check if it was actually a redirect
171 if (isHttpRedirect()) {
172 reportRedirect();
173 output.remove();
174 } else {
175 printf(format: "Succeeded.\n");
176 ++downloadedCount;
177 }
178 }
179
180 currentDownload->deleteLater();
181 startNextDownload();
182}
183
184void DownloadManager::downloadReadyRead()
185{
186 output.write(data: currentDownload->readAll());
187}
188
189bool DownloadManager::isHttpRedirect() const
190{
191 int statusCode = currentDownload->attribute(code: QNetworkRequest::HttpStatusCodeAttribute).toInt();
192 return statusCode == 301 || statusCode == 302 || statusCode == 303
193 || statusCode == 305 || statusCode == 307 || statusCode == 308;
194}
195
196void DownloadManager::reportRedirect()
197{
198 int statusCode = currentDownload->attribute(code: QNetworkRequest::HttpStatusCodeAttribute).toInt();
199 QUrl requestUrl = currentDownload->request().url();
200 QTextStream(stderr) << "Request: " << requestUrl.toDisplayString()
201 << " was redirected with code: " << statusCode
202 << '\n';
203
204 QVariant target = currentDownload->attribute(code: QNetworkRequest::RedirectionTargetAttribute);
205 if (!target.isValid())
206 return;
207 QUrl redirectUrl = target.toUrl();
208 if (redirectUrl.isRelative())
209 redirectUrl = requestUrl.resolved(relative: redirectUrl);
210 QTextStream(stderr) << "Redirected to: " << redirectUrl.toDisplayString()
211 << '\n';
212}
213

source code of qtbase/examples/network/downloadmanager/downloadmanager.cpp