00001 #include "updaterdownload.h"
00002 #include <QApplication>
00003 #include <QDebug>
00004 #include <QMessageBox>
00005
00006 UpdaterDownload::UpdaterDownload()
00007 {
00008 connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
00009 }
00010
00011 void UpdaterDownload::setDownloads(QStringList downs)
00012 {
00013 downloads = downs;
00014 }
00015
00016 void UpdaterDownload::doDownload(const QUrl &url)
00017 {
00018 qDebug()<<"doDownload: " << url;
00019 QNetworkRequest request(url);
00020 QNetworkReply *reply = manager.get(request);
00021
00022 currentDownloads.append(reply);
00023 }
00024
00025 QString UpdaterDownload::saveFileName(const QUrl &url)
00026 {
00027 QString path = url.path();
00028 QString basename = QFileInfo(path).fileName();
00029
00030 if (basename.isEmpty())
00031 {
00032 basename = "download";
00033 }
00034
00035 if (QFile::exists(basename))
00036 {
00037
00038 int i = 0;
00039 basename += '.';
00040 while (QFile::exists(basename + QString::number(i)))
00041 {
00042 ++i;
00043 }
00044
00045 basename += QString::number(i);
00046 }
00047
00048 return basename;
00049 }
00050
00051 bool UpdaterDownload::saveToDisk(const QString &filename, QIODevice *data)
00052 {
00053 QFile file(filename);
00054 if (!file.open(QIODevice::WriteOnly))
00055 {
00056 qDebug()<< "Could not open " << QString(qPrintable(filename)) << " for writing: " << QString(qPrintable(file.errorString()));
00057 return false;
00058 }
00059
00060 file.write(data->readAll());
00061 file.close();
00062
00063 return true;
00064 }
00065
00066 void UpdaterDownload::execute()
00067 {
00068 foreach (QString arg, downloads)
00069 {
00070 QUrl url = QUrl::fromEncoded(arg.toLocal8Bit());
00071 doDownload(url);
00072 }
00073 }
00074
00075 void UpdaterDownload::downloadFinished(QNetworkReply *reply)
00076 {
00077 QUrl url = reply->url();
00078 if(reply->error() != QNetworkReply::NoError)
00079 {
00080 qDebug()<< "reply error: " << reply->error();
00081 qDebug() << "Download of " << QString(url.toEncoded().constData()) << " failed: " << QString(qPrintable(reply->errorString()));
00082 }
00083 else
00084 {
00085 QString filename = saveFileName(url);
00086 if(saveToDisk(filename, reply))
00087 {
00088 qDebug() << "Download of " << QString(url.toEncoded().constData()) << " succeded (saved to " << QString(qPrintable(filename));
00089 }
00090 }
00091
00092 currentDownloads.removeAll(reply);
00093 reply->deleteLater();
00094
00095 if(currentDownloads.isEmpty())
00096 {
00097 emit downloadFinished();
00098 }
00099 }