123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- #include "downloadmanager.h"
- #include "filesystem.h"
- #include "aconfig.h"
- #include <QFileInfo>
- #include <QApplication>
- #include <QNetworkRequest>
- #include <QNetworkReply>
- #include <QString>
- #include <QStringList>
- #include <QTimer>
- #include <stdio.h>
- DownloadManager::DownloadManager(QObject *parent)
- : QObject(parent), downloadedCount(0), totalCount(0) {}
- void DownloadManager::append(const QStringList &urlList){
- foreach (QString url, urlList)
- append(QUrl::fromEncoded(url.toLocal8Bit()));
- if (downloadQueue.isEmpty())
- QTimer::singleShot(0, this, SIGNAL(finished()));
- }
- void DownloadManager::append(const QUrl &url){
- qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Добавлен: ", url.fileName().toStdString().c_str());
- if (downloadQueue.isEmpty())
- QTimer::singleShot(0, this, SLOT(startNextDownload()));
- downloadQueue.enqueue(url);
- ++totalCount;
- qDebug("%s:%i: %s%i", __FILE__, __LINE__, "Загрузок в списке: ", totalCount);
- }
- void DownloadManager::startNextDownload() {
- if (downloadQueue.isEmpty()) {
- qDebug("%s:%i: %s%d/%d", __FILE__, __LINE__, "Загрузка завершена. Загружено файлов: ", downloadedCount, totalCount);
- emit finishedAllDownloads();
- return;
- }
- QUrl url = downloadQueue.dequeue();
- QString filename = QFileInfo(url.path()).fileName();
- output.setFileName(QApplication::applicationDirPath() + "/data/" + filename);
- qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Начата загрузка файла: ", filename.toStdString().c_str());
- // Проверяем целостность файла и игнорируем в случае если он цел
- QString hash = FileSystem::fileHash(QApplication::applicationDirPath() + "/data/" + filename, QCryptographicHash::Md5);
- QStringList pname = output.fileName().split("/");
- QStringList ptype = pname.last().split("_");
- qDebug() << ptype.first();
- QString keyname = ptype.first();
- if(keyname == "loadscreens") keyname = "screens";
- if(hash == AConfig::getInstance()->getValue("Hashes", ptype.first()) && AConfig::getInstance()->getValue("Editor", keyname) == "true"){
- qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Проверка хэша успешно завершена: ", filename.toStdString().c_str());
- startNextDownload();
- return;
- }
- qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Хэш файла не совпал: ", filename.toStdString().c_str());
- QStringList parsename = filename.split("_");
- QString name = parsename[0] + "Status";
- download_name = parsename[0];
- if (!output.open(QIODevice::WriteOnly)) {
- qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Произошла остановка скачивания ", filename.toStdString().c_str());
- /*fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
- qPrintable(filename), url.toEncoded().constData(),
- qPrintable(output.errorString()));*/
- emit fileDownloadFinished(filename, "Не удалась");
- startNextDownload();
- return;
- }
- qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем скачивание ", url.fileName().toStdString().c_str());
- QNetworkRequest request(url);
- currentDownload = manager.get(request);
- connect(this, SIGNAL(cancelDownload()), currentDownload, SLOT(abort()));
- connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)), SLOT(downloadProgress(qint64,qint64)));
- connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished()));
- connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead()));
- // prepare the output
- downloadTime.start();
- }
- void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
- {
- double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
- double percent = double(std::ceil(((double)bytesReceived/ bytesTotal) * 100 * 10)) / 10.0;
- QString unit;
- if (speed < 1024) {
- unit = "bytes/sec";
- } else if (speed < 1024*1024) {
- speed /= 1024;
- unit = "kB/s";
- } else {
- speed /= 1024*1024;
- unit = "MB/s";
- }
- QString speedtext = QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit);
- QString percenttext = QString::fromLatin1("%1").arg(percent, 3);
- emit updateDownloadProgress("Загрузка ... <br/>" + percenttext+ "% (" + speedtext + ")");
- }
- void DownloadManager::downloadFinished()
- {
- QString filename = output.fileName();
- output.close();
- if (currentDownload->error()) {
- qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Загрузка не удалась: ", currentDownload->errorString().toStdString().c_str());
- //fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
- emit fileDownloadFinished(filename, "Не удалась.");
- } else {
- emit fileDownloadFinished(filename, "Готово.");
- qInfo("%s:%i: %s", __FILE__, __LINE__, "Все загрузки завершены. Загрузчик завершил свою работу.");
- ++downloadedCount;
- }
- currentDownload->deleteLater();
- startNextDownload();
- }
- void DownloadManager::downloadReadyRead(){
- output.write(currentDownload->readAll());
- }
- void DownloadManager::abortDownload(QString name){
- if(download_name == name && currentDownload != nullptr && currentDownload->isOpen()) {
- currentDownload->abort();
- }
- }
|