This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Downloadmanager class

By: a guest on Dec 18th, 2010  |  syntax: C++  |  size: 6.18 KB  |  views: 64  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //HEADER FILE
  2. #ifndef DOWNLOADMANAGER_H
  3. #define DOWNLOADMANAGER_H
  4.  
  5. #include <QFile>
  6. #include <QObject>
  7. #include <QQueue>
  8. #include <QTime>
  9. #include <QUrl>
  10. #include <QtNetwork/QNetworkAccessManager>
  11. #include <QtNetwork/QNetworkReply>
  12. #include <QtNetwork/QSslError>
  13. #include <QtNetwork/QAuthenticator>
  14.  
  15. class DownloadManager: public QObject
  16. {
  17.     Q_OBJECT
  18.  
  19. public:
  20.  
  21.     DownloadManager(QObject *parent = 0);
  22.  
  23.     void appendToQueue(const QUrl &url);
  24.     void appendToQueue(const QStringList &urlList,const QString &sTargetFolder);
  25.     QString getTargetFolder();
  26.     void setTargetFolder(const QString &strTargetFolder);
  27.  
  28. Q_SIGNALS:
  29.  
  30.     void finished();
  31.     void downloadComplete(bool,QString);
  32.  
  33. private slots:
  34.  
  35.     void startNextDownload();
  36.     void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
  37.     void downloadFinished();
  38.     void downloadReadyRead();
  39.  
  40.     void errorNetworkReply(QNetworkReply::NetworkError);
  41.  
  42.     void authenticationRequired(QNetworkReply*,QAuthenticator*);
  43.  
  44.     void sslErrors(QNetworkReply*,QList<QSslError>);
  45.  
  46.     bool isDownloadDone();
  47.  
  48.     QString saveFileName(const QUrl &url);
  49.  
  50. private:
  51.  
  52.     QString        m_sTargetFolder;
  53.  
  54.     QNetworkAccessManager manager;
  55.     QQueue<QUrl>          downloadQueue;
  56.     QNetworkReply         *currentDownload;
  57.  
  58.     QFile output;
  59.     QTime downloadTime;
  60.  
  61.     int downloadedCount;
  62.     int totalCount;
  63. };
  64.  
  65. #endif
  66.  
  67.  
  68. //CPP FILE
  69.  
  70. #include "downloadmanager.h"
  71.  
  72. #include <QFileInfo>
  73. #include <QtNetwork/QNetworkRequest>
  74. #include <QtNetwork/QNetworkReply>
  75. #include <QString>
  76. #include <QStringList>
  77. #include <QTimer>
  78. #include <QDebug>
  79. #include <QDir>
  80. DownloadManager::DownloadManager(QObject *parent)
  81.     : QObject(parent), downloadedCount(0), totalCount(0)
  82. {
  83. }
  84.  
  85. void DownloadManager::sslErrors(QNetworkReply*,QList<QSslError>)
  86. {
  87.         //FIXME: implement this
  88. }
  89.  
  90. void DownloadManager::appendToQueue(const QStringList &urlList,const QString &sTargetFolder)
  91. {
  92.     setTargetFolder(sTargetFolder);
  93.  
  94.     foreach (QString url, urlList)
  95.     {
  96.         if(!url.isEmpty())
  97.             appendToQueue(QUrl::fromEncoded(url.toLocal8Bit(),QUrl::StrictMode));
  98.     }
  99.  
  100.     if (downloadQueue.isEmpty())
  101.         QTimer::singleShot(0, this, SIGNAL(finished()));
  102. }
  103.  
  104. void DownloadManager::appendToQueue(const QUrl &url)
  105. {
  106.     if (downloadQueue.isEmpty())
  107.         QTimer::singleShot(0, this, SLOT(startNextDownload()));
  108.  
  109.     downloadQueue.enqueue(url);
  110.     ++totalCount;
  111. }
  112.  
  113.  
  114. QString DownloadManager::saveFileName(const QUrl &url)
  115. {
  116.     QString path = url.path();    
  117.     path.replace('/','_');
  118.     return m_sTargetFolder + "/" + path;
  119. }
  120.  
  121. void DownloadManager::startNextDownload()
  122. {
  123.     if (downloadQueue.isEmpty()) {
  124.  
  125.         qDebug() << QString("%1/%2 files downloaded successfully\n").arg(downloadedCount).arg(totalCount);
  126.         emit finished();
  127.         return;
  128.     }
  129.  
  130.     QUrl url = downloadQueue.dequeue();
  131.  
  132.     QString filename = saveFileName(url);
  133.     output.setFileName(filename);
  134.     if (!output.open(QIODevice::WriteOnly)) {
  135.         fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
  136.                 qPrintable(filename), url.toEncoded().constData(),
  137.                 qPrintable(output.errorString()));
  138.  
  139.         startNextDownload();
  140.         return;                 // skip this download
  141.     }
  142.  
  143.  
  144.     QNetworkRequest request(url);
  145.     currentDownload = manager.get(request);
  146.  
  147.     connect(currentDownload,SIGNAL(error(QNetworkReply::NetworkError)),this,
  148.                             SLOT(errorNetworkReply(QNetworkReply::NetworkError)));
  149.  
  150.     connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
  151.                              SLOT(downloadProgress(qint64,qint64)));
  152.  
  153.     connect(currentDownload, SIGNAL(finished()),
  154.                              SLOT(downloadFinished()));
  155.  
  156.     connect(currentDownload, SIGNAL(readyRead()),
  157.                              SLOT(downloadReadyRead()));
  158.  
  159. //    connect(&manager,SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
  160. //            SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*)));
  161.  
  162.  
  163.     connect(&manager,SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
  164.     // prepare the output
  165.     printf("Downloading %s...\n", url.toEncoded().constData());
  166.     downloadTime.start();
  167. }
  168.  
  169. void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
  170. {
  171.  
  172.     qDebug() << QString("\n%1 data of %2 downloaded").arg(QString::number(bytesReceived)).arg(QString::number(bytesTotal));
  173.  
  174. }
  175.  
  176. void DownloadManager::downloadFinished()
  177. {
  178.     output.close();
  179.  
  180.     if (currentDownload->error()) {
  181.         // download failed
  182.         qDebug() << L"Download Status : Failed. \t Error Msg : " << currentDownload->errorString();
  183.  
  184.  
  185.         emit downloadComplete(false,QFileInfo(output).absoluteFilePath());
  186.  
  187.     } else {
  188.  
  189.         ++downloadedCount;
  190.         qDebug() << L"Download Status : Succeeded." ;
  191.  
  192.         emit downloadComplete(true,QFileInfo(output).absoluteFilePath());
  193.  
  194.     }
  195.  
  196.     currentDownload->deleteLater();
  197.     startNextDownload();
  198. }
  199.  
  200. void DownloadManager::downloadReadyRead()
  201. {
  202.     output.write(currentDownload->readAll());
  203. }
  204.  
  205. //void DownloadManager::networkAccessibleChangedSlot(QNetworkAccessManager::NetworkAccessibility access)
  206. //{
  207. //
  208. //    if(access == QNetworkAccessManager::NotAccessible)
  209. //        qDebug() << "\n Net gone...................:)";
  210. //}
  211.  
  212. void DownloadManager::errorNetworkReply(QNetworkReply::NetworkError code)
  213. {
  214.     qDebug() << "\nNetwork Error : " + QString::number(code);
  215. }
  216.  
  217. void DownloadManager::setTargetFolder(const QString &strTargetFolder)
  218. {
  219.     m_sTargetFolder = strTargetFolder;
  220.  
  221.     QDir dirTarget;
  222.  
  223.         if(!dirTarget.exists())
  224.                 dirTarget.mkpath(sTargetFolder);
  225.  
  226. }
  227.  
  228. QString DownloadManager::getTargetFolder()
  229. {
  230.     return m_sTargetFolder;
  231. }
  232.  
  233. bool DownloadManager::isDownloadDone()
  234. {
  235.     return totalCount == downloadedCount;
  236. }
  237.  
  238. void DownloadManager::authenticationRequired(QNetworkReply *reply,QAuthenticator *auth)
  239. {
  240.     if(reply && reply->isRunning())
  241.     {
  242.         auth->setUser(reply->url().userName());
  243.         auth->setPassword(reply->url().password());
  244.     }
  245. }
clone this paste RAW Paste Data