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
|
#include "DownloadManager.h"
#include <QTimer>
void DownloadManager::get(QString& filename)
{
// Forge URL from the given filename and the base URL.
QUrl u = this->baseUrl.resolved(filename);
// If download in progress, enqueue file and return.
if (dip)
{
qDebug() << "Download in progress! Enqueueing:" << u.toString();
dlQ.enqueue(u);
return;
}
// No running downloads.
dlQ.enqueue(u);
qDebug() << "Enqueueing :" << u.toString();
startNextDownload();
}
void DownloadManager::startNextDownload()
{
qDebug() << "Starting next download: " << dlQ.head().toString()
<< "(" << dlQ.size() << "in queue.)";
// Set flag for download in progress.
dip = true;
if (dlQ.isEmpty())
{
qDebug() << "Download queue empty! Exiting...";
return;
}
QUrl url = dlQ.dequeue();
qDebug() << "Dequeueing..." << url.toString();
//** TEST **
QString path = url.path();
QString basename = QFileInfo(path).fileName();
if (basename.isEmpty())
this->filename = "download";
else
this->filename = basename;
//qDebug() << "Path is: " << path << endl;
//qDebug() << "Basename is: " << basename << endl;
//** TEST **
//qDebug() << "Filename is: " << this->filename;
outfile.setFileName(this->filename);
if (!outfile.open(QIODevice::WriteOnly))
{
qDebug() << "Couldn't open file! Exiting...";
// Skip this file
startNextDownload();
return;
}
QNetworkRequest request(url);
currentDownload = (*qnam).get(request);
QObject::connect(currentDownload, SIGNAL(readyRead()), this, SLOT(downloadReady()));
QObject::connect(currentDownload, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(downloadProgress(qint64, qint64)));
QObject::connect(currentDownload, SIGNAL(finished()), this, SLOT(downloadFinished()));
}
void DownloadManager::downloadReady()
{
outfile.write(this->currentDownload->readAll());
}
void DownloadManager::downloadProgress(qint64 bytesIn, qint64 bytesTotal)
{
qDebug() << "Download progress of " << currentDownload->url().toString() << ": " << bytesIn << "/" << bytesTotal;
}
void DownloadManager::downloadFinished()
{
if (currentDownload->isFinished())
qDebug() << "Downloaded " << currentDownload->url().toString() << endl;
outfile.close();
// If queue is empty, we are done.
// TODO: not sure if this is actually needed...
if (dlQ.isEmpty())
return;
// Queue not empty, start next download in queue.
dip = false;
currentDownload->deleteLater();
startNextDownload();
}
void DownloadManager::print()
{
qDebug() << "The download manager is still working";
}
DownloadManager::DownloadManager(const QUrl& baseUrl)
{
this->qnam = new QNetworkAccessManager();
this->baseUrl = baseUrl;
dip = false;
}
DownloadManager::~DownloadManager()
{
}
|