downloadmanager.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #include "app.h"
  2. #include "filesystem.h"
  3. #include <QFileInfo>
  4. #include <QApplication>
  5. #include <QNetworkRequest>
  6. #include <QNetworkReply>
  7. #include <QString>
  8. #include <QStringList>
  9. #include <QTimer>
  10. #include <stdio.h>
  11. DownloadManager::DownloadManager(QObject *parent)
  12. : QObject(parent), downloadedCount(0), totalCount(0)
  13. {
  14. }
  15. void DownloadManager::append(const QStringList &urlList){
  16. foreach (QString url, urlList)
  17. append(QUrl::fromEncoded(url.toLocal8Bit()));
  18. if (downloadQueue.isEmpty())
  19. QTimer::singleShot(0, this, SIGNAL(finished()));
  20. }
  21. void DownloadManager::append(const QUrl &url){
  22. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Добавлен: ", url.fileName().toLocal8Bit().data());
  23. if (downloadQueue.isEmpty())
  24. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  25. downloadQueue.enqueue(url);
  26. ++totalCount;
  27. qDebug("%s:%i: %s%i", __FILE__, __LINE__, "Загрузок в списке: ", totalCount);
  28. }
  29. void DownloadManager::startNextDownload()
  30. {
  31. App *app = &App::getInstance();
  32. if (downloadQueue.isEmpty()) {
  33. app->helper->setState("free");// говорим что приложение освободилось
  34. qDebug("%s:%i: %s%d/%d", __FILE__, __LINE__, "Загрузка завершена. Загружено файлов: ", downloadedCount, totalCount);
  35. emit finished();
  36. return;
  37. }
  38. QUrl url = downloadQueue.dequeue();
  39. QString filename = QFileInfo(url.path()).fileName();
  40. output.setFileName(QApplication::applicationDirPath() + "/data/" + filename);
  41. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Начата загрузка файла: ", filename.toLocal8Bit().data());
  42. // Проверяем целостность файла и игнорируем в случае если он цел
  43. QString hash = FileSystem::fileHash(QApplication::applicationDirPath() + "/data/" + filename, QCryptographicHash::Md5);
  44. QStringList pname = output.fileName().split("/");
  45. QStringList ptype = pname.last().split("_");
  46. qDebug() << ptype.first();
  47. QString keyname = ptype.first();
  48. if(keyname == "loadscreens") keyname = "screens";
  49. if(hash == app->config->getValue("Hashes", ptype.first()) && app->config->getValue("Editor", keyname) == "true"){
  50. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Проверка хэша успешно завершена: ", filename.toLocal8Bit().data());
  51. startNextDownload();
  52. return;
  53. }
  54. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Хэш файла не совпал: ", filename.toLocal8Bit().data());
  55. QStringList parsename = filename.split("_");
  56. QString name = parsename[0] + "Status";
  57. download_name = parsename[0];
  58. app->writtenLabel = app->window->ui->mainbox->findChild<QLabel *>(name);
  59. if (!output.open(QIODevice::WriteOnly)) {
  60. qCritical("%s:%i: %s%s", __FILE__, __LINE__, "Произошла остановка скачивания ", filename.toLocal8Bit().data());
  61. /*fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",
  62. qPrintable(filename), url.toEncoded().constData(),
  63. qPrintable(output.errorString()));*/
  64. if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не удалась");
  65. startNextDownload();
  66. return;
  67. }
  68. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем скачивание ", url.fileName().toLocal8Bit().data());
  69. app->helper->setState("busy");// говорим что приложение занято
  70. QNetworkRequest request(url);
  71. currentDownload = manager.get(request);
  72. connect(this, SIGNAL(cancelDownload()), currentDownload, SLOT(abort()));
  73. connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
  74. SLOT(downloadProgress(qint64,qint64)));
  75. connect(currentDownload, SIGNAL(finished()),
  76. SLOT(downloadFinished()));
  77. connect(currentDownload, SIGNAL(readyRead()),
  78. SLOT(downloadReadyRead()));
  79. // prepare the output
  80. downloadTime.start();
  81. }
  82. void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
  83. {
  84. double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
  85. double percent = double(std::ceil(((double)bytesReceived/ bytesTotal) * 100 * 10)) / 10.0;
  86. QString unit;
  87. if (speed < 1024) {
  88. unit = "bytes/sec";
  89. } else if (speed < 1024*1024) {
  90. speed /= 1024;
  91. unit = "kB/s";
  92. } else {
  93. speed /= 1024*1024;
  94. unit = "MB/s";
  95. }
  96. QString speedtext = QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit);
  97. QString percenttext = QString::fromLatin1("%1").arg(percent, 3);
  98. App *app = &App::getInstance();
  99. if(app->writtenLabel != nullptr) app->writtenLabel->setText("Загрузка ... <br/>" + percenttext+ "% (" + speedtext + ")");
  100. }
  101. void DownloadManager::downloadFinished()
  102. {
  103. output.close();
  104. App *app = &App::getInstance();
  105. app->helper->setState("free");// говорим что приложение освободилось
  106. if (currentDownload->error()) {
  107. qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Загрузка не удалась: ", currentDownload->errorString().toLocal8Bit().data());
  108. //fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
  109. if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не удалась.");
  110. } else {
  111. if(app->writtenLabel != nullptr) app->writtenLabel->setText("Готово");
  112. qInfo("%s:%i: %s", __FILE__, __LINE__, "Все загрузки завершены. Загрузчик завершил свою работу.");
  113. ++downloadedCount;
  114. app->network->getPaths();
  115. }
  116. currentDownload->deleteLater();
  117. startNextDownload();
  118. }
  119. void DownloadManager::downloadReadyRead(){
  120. output.write(currentDownload->readAll());
  121. }
  122. void DownloadManager::abortDownload(QString name){
  123. App *app = &App::getInstance();
  124. if(download_name == name){
  125. if(app->state != "free" && currentDownload != NULL && currentDownload->isOpen()) {
  126. qDebug() << "Прерываем закачку " + download_name;
  127. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Пользователь прервал закачку файла ", download_name.toLocal8Bit().data());
  128. if(app->writtenLabel != nullptr) app->writtenLabel->setText("Не выбран");
  129. currentDownload->abort();
  130. }
  131. }
  132. }