downloadmanager.cpp 5.4 KB

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