| 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 | |
| 57 | using namespace std; |
| 58 | |
| 59 | DownloadManager::DownloadManager(QObject *parent) |
| 60 | : QObject(parent) |
| 61 | { |
| 62 | } |
| 63 | |
| 64 | void DownloadManager::append(const QStringList &urls) |
| 65 | { |
| 66 | for (const QString &urlAsString : urls) |
| 67 | append(QUrl::fromEncoded(urlAsString.toLocal8Bit())); |
| 68 | |
| 69 | if (downloadQueue.isEmpty()) |
| 70 | QTimer::singleShot(0, this, &DownloadManager::finished); |
| 71 | } |
| 72 | |
| 73 | void DownloadManager::append(const QUrl &url) |
| 74 | { |
| 75 | if (downloadQueue.isEmpty()) |
| 76 | QTimer::singleShot(0, this, &DownloadManager::startNextDownload); |
| 77 | |
| 78 | downloadQueue.enqueue(url); |
| 79 | ++totalCount; |
| 80 | } |
| 81 | |
| 82 | QString 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(basename)) { |
| 91 | // already exists, don't overwrite |
| 92 | int i = 0; |
| 93 | basename += '.'; |
| 94 | while (QFile::exists(basename + QString::number(i))) |
| 95 | ++i; |
| 96 | |
| 97 | basename += QString::number(i); |
| 98 | } |
| 99 | |
| 100 | return basename; |
| 101 | } |
| 102 | |
| 103 | void DownloadManager::startNextDownload() |
| 104 | { |
| 105 | if (downloadQueue.isEmpty()) { |
| 106 | printf("%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(QIODevice::WriteOnly)) { |
| 116 | fprintf(stderr, "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(currentDownload, &QNetworkReply::downloadProgress, |
| 127 | this, &DownloadManager::downloadProgress); |
| 128 | connect(currentDownload, &QNetworkReply::finished, |
| 129 | this, &DownloadManager::downloadFinished); |
| 130 | connect(currentDownload, &QNetworkReply::readyRead, |
| 131 | this, &DownloadManager::downloadReadyRead); |
| 132 | |
| 133 | // prepare the output |
| 134 | printf("Downloading %s...\n" , url.toEncoded().constData()); |
| 135 | downloadTimer.start(); |
| 136 | } |
| 137 | |
| 138 | void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) |
| 139 | { |
| 140 | progressBar.setStatus(bytesReceived, 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("%1 %2" ) |
| 156 | .arg(speed, 3, 'f', 1).arg(unit)); |
| 157 | progressBar.update(); |
| 158 | } |
| 159 | |
| 160 | void DownloadManager::downloadFinished() |
| 161 | { |
| 162 | progressBar.clear(); |
| 163 | output.close(); |
| 164 | |
| 165 | if (currentDownload->error()) { |
| 166 | // download failed |
| 167 | fprintf(stderr, "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("Succeeded.\n" ); |
| 176 | ++downloadedCount; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | currentDownload->deleteLater(); |
| 181 | startNextDownload(); |
| 182 | } |
| 183 | |
| 184 | void DownloadManager::downloadReadyRead() |
| 185 | { |
| 186 | output.write(currentDownload->readAll()); |
| 187 | } |
| 188 | |
| 189 | bool DownloadManager::isHttpRedirect() const |
| 190 | { |
| 191 | int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); |
| 192 | return statusCode == 301 || statusCode == 302 || statusCode == 303 |
| 193 | || statusCode == 305 || statusCode == 307 || statusCode == 308; |
| 194 | } |
| 195 | |
| 196 | void DownloadManager::reportRedirect() |
| 197 | { |
| 198 | int statusCode = currentDownload->attribute(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(QNetworkRequest::RedirectionTargetAttribute); |
| 205 | if (!target.isValid()) |
| 206 | return; |
| 207 | QUrl redirectUrl = target.toUrl(); |
| 208 | if (redirectUrl.isRelative()) |
| 209 | redirectUrl = requestUrl.resolved(redirectUrl); |
| 210 | QTextStream(stderr) << "Redirected to: " << redirectUrl.toDisplayString() |
| 211 | << '\n'; |
| 212 | } |
| 213 | |