source: trunk/examples/network/downloadmanager/downloadmanager.cpp@ 168

Last change on this file since 168 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 5.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "downloadmanager.h"
43
44#include <QFileInfo>
45#include <QNetworkRequest>
46#include <QNetworkReply>
47#include <QString>
48#include <QStringList>
49#include <QTimer>
50#include <stdio.h>
51
52DownloadManager::DownloadManager(QObject *parent)
53 : QObject(parent), downloadedCount(0), totalCount(0)
54{
55}
56
57void DownloadManager::append(const QStringList &urlList)
58{
59 foreach (QString url, urlList)
60 append(QUrl::fromEncoded(url.toLocal8Bit()));
61
62 if (downloadQueue.isEmpty())
63 QTimer::singleShot(0, this, SIGNAL(finished()));
64}
65
66void DownloadManager::append(const QUrl &url)
67{
68 if (downloadQueue.isEmpty())
69 QTimer::singleShot(0, this, SLOT(startNextDownload()));
70
71 downloadQueue.enqueue(url);
72 ++totalCount;
73}
74
75QString DownloadManager::saveFileName(const QUrl &url)
76{
77 QString path = url.path();
78 QString basename = QFileInfo(path).fileName();
79
80 if (basename.isEmpty())
81 basename = "download";
82
83 if (QFile::exists(basename)) {
84 // already exists, don't overwrite
85 int i = 0;
86 basename += '.';
87 while (QFile::exists(basename + QString::number(i)))
88 ++i;
89
90 basename += QString::number(i);
91 }
92
93 return basename;
94}
95
96void DownloadManager::startNextDownload()
97{
98 if (downloadQueue.isEmpty()) {
99 printf("%d/%d files downloaded successfully\n", downloadedCount, totalCount);
100 emit finished();
101 return;
102 }
103
104 QUrl url = downloadQueue.dequeue();
105
106 QString filename = saveFileName(url);
107 output.setFileName(filename);
108 if (!output.open(QIODevice::WriteOnly)) {
109 fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
110 qPrintable(filename), url.toEncoded().constData(),
111 qPrintable(output.errorString()));
112
113 startNextDownload();
114 return; // skip this download
115 }
116
117 QNetworkRequest request(url);
118 currentDownload = manager.get(request);
119 connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
120 SLOT(downloadProgress(qint64,qint64)));
121 connect(currentDownload, SIGNAL(finished()),
122 SLOT(downloadFinished()));
123 connect(currentDownload, SIGNAL(readyRead()),
124 SLOT(downloadReadyRead()));
125
126 // prepare the output
127 printf("Downloading %s...\n", url.toEncoded().constData());
128 downloadTime.start();
129}
130
131void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
132{
133 progressBar.setStatus(bytesReceived, bytesTotal);
134
135 // calculate the download speed
136 double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
137 QString unit;
138 if (speed < 1024) {
139 unit = "bytes/sec";
140 } else if (speed < 1024*1024) {
141 speed /= 1024;
142 unit = "kB/s";
143 } else {
144 speed /= 1024*1024;
145 unit = "MB/s";
146 }
147
148 progressBar.setMessage(QString::fromLatin1("%1 %2")
149 .arg(speed, 3, 'f', 1).arg(unit));
150 progressBar.update();
151}
152
153void DownloadManager::downloadFinished()
154{
155 progressBar.clear();
156 output.close();
157
158 if (currentDownload->error()) {
159 // download failed
160 fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
161 } else {
162 printf("Succeeded.\n");
163 ++downloadedCount;
164 }
165
166 currentDownload->deleteLater();
167 startNextDownload();
168}
169
170void DownloadManager::downloadReadyRead()
171{
172 output.write(currentDownload->readAll());
173}
Note: See TracBrowser for help on using the repository browser.