#include "filedownloader.h" #include FileDownloader* FileDownloader::_self=NULL; QNetworkAccessManager* FileDownloader::m_WebCtrl=NULL; QList* FileDownloader::m_pendingTasks=NULL; DownLoadHistory* FileDownloader::m_gui=NULL; bool FileDownloader::m_noGui=false; QString FileDownloader::m_serviceName="FileDownloader"; #define _INIT \ if(Q_UNLIKELY(_self==NULL))\ {\ init();\ }\ int FileDownloader::downloadFile(QUrl fileUrl, const QString &name) { _INIT if(QFile::exists(name)|| QFile::exists(name+".part")) { return -1; } FileDownloaderTask* task=NULL; int ID=_self->getTaskId(); if(ID!=-1) { QNetworkRequest request(fileUrl); QNetworkReply* reply = m_WebCtrl->get(request); if(reply && (reply->error()==QNetworkReply::NoError)) { task=new FileDownloaderTask(reply,ID,name,_self); m_pendingTasks->append(task); if(!m_noGui) { m_gui->addElement(new DownloadHistoryElement(task)); } } else { return -1; } } return ID; } int FileDownloader::downloadFile(QString fileUrl, const QString &name) { return downloadFile(QUrl(fileUrl),name); } QWidget *FileDownloader::getGUI() { return (QWidget*) m_gui; } const QString &FileDownloader::serviceName() { return m_serviceName; } FileDownloaderTask* FileDownloader::getDownloadTask(int ID) { _INIT for(int i=0;icount();i++) { if(m_pendingTasks->at(i)->ID()==ID) return m_pendingTasks->at(i); } return NULL; } bool FileDownloader::taskIsCompleted(int ID) { return getDownloadTask(ID)->downloadComplete(); } FileDownloader *FileDownloader::self() { _INIT return _self; } int FileDownloader::getTaskId() { for(unsigned int i=0;icount();j++) { if(m_pendingTasks->at(j)->ID()==(int)i) idValid=false; } if(idValid) return (int)i; } return -1; } void FileDownloader::init(bool noGUI, QObject *parent) { m_noGui=noGUI; if(Q_UNLIKELY(_self==NULL)) { _self=new FileDownloader(parent); } } FileDownloader::FileDownloader(QObject *parent) : QLopService(parent) { QNetworkProxyQuery q(QUrl("http://www.google.com")); q.setQueryType(QNetworkProxyQuery::UrlRequest); q.setProtocolTag("http"); QList proxies = QNetworkProxyFactory::systemProxyForQuery(q); if( proxies.size() > 0 && proxies[0].type() != QNetworkProxy::NoProxy ) QNetworkProxy::setApplicationProxy(proxies[0]); else qDebug("No proxy server selected"); m_WebCtrl = new QNetworkAccessManager(this); m_pendingTasks = new QList(); if(!m_noGui) m_gui=new DownLoadHistory(); } FileDownloader::~FileDownloader() { if(!m_noGui) delete m_gui; while (m_pendingTasks->count()) { FileDownloaderTask* task=m_pendingTasks->last(); m_pendingTasks->removeLast(); delete task; } delete m_WebCtrl; }