downloadmanager.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #include "app.h"
  2. #include "filesystem.h"
  3. #include "lotromanager.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. {
  15. busy = false;
  16. }
  17. void DownloadManager::append(const QStringList &urlList){
  18. foreach (QString url, urlList)
  19. append(QUrl::fromEncoded(url.toLocal8Bit()));
  20. if (downloadQueue.isEmpty())
  21. QTimer::singleShot(0, this, SIGNAL(finished()));
  22. }
  23. void DownloadManager::append(const QUrl &url){
  24. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Добавлен файл для скачивания: ", url.fileName().toLocal8Bit().data());
  25. if (downloadQueue.count(url) == 0) {
  26. downloadQueue.enqueue(url);
  27. ++totalCount;
  28. } else {
  29. qDebug("%s:%i: %s %s%s", __FILE__, __LINE__, "Не добавляю закачку "
  30. , url.fileName().toLocal8Bit().data()
  31. , ", так как она уже находится в очереди закачек");
  32. }
  33. qDebug("%s:%i: %s%i", __FILE__, __LINE__, "Загрузок в списке: ", totalCount);
  34. //if (!busy)
  35. // QTimer::singleShot(0, this, SLOT(startNextDownload()));
  36. }
  37. void DownloadManager::startDownloads() {
  38. if (!busy)
  39. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  40. }
  41. void DownloadManager::startNextDownload() {
  42. current_speed = "";
  43. bytesReceivedBeforeSecond = 0;
  44. timeElapsedBeforeSecond = 0;
  45. if (busy) {
  46. qWarning("%s:%i: %s", __FILE__, __LINE__, "Ошибка! Обнаружена попытка начала загрузки, когда не завершилась другая загрузка");
  47. return;
  48. }
  49. App *app = &App::getInstance();
  50. app->helper->setState("busy");
  51. busy = true;
  52. if (downloadQueue.isEmpty()) {
  53. app->helper->setState("free");// говорим что приложение освободилось
  54. qDebug("%s:%i: %s%d/%d", __FILE__, __LINE__, "Загрузка завершена. Загружено файлов: ", downloadedCount, totalCount);
  55. busy = false;
  56. emit finished();
  57. return;
  58. }
  59. QUrl url = downloadQueue.dequeue();
  60. QString filename = QFileInfo(url.path()).fileName();
  61. output.setFileName(QApplication::applicationDirPath() + "/data/" + filename);
  62. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Начата загрузка файла: ", filename.toLocal8Bit().data());
  63. // Проверяем целостность файла и игнорируем в случае если он цел
  64. QString hash = FileSystem::fileHash(QApplication::applicationDirPath() + "/data/" + filename, QCryptographicHash::Md5);
  65. QStringList pname = output.fileName().split("/");
  66. QStringList ptype = pname.last().split("_");
  67. qDebug() << ptype.first();
  68. QString keyname = ptype.first();
  69. if(keyname == "loadscreens") keyname = "screens";
  70. if(hash == app->config->getValue("Hashes", ptype.first()) && app->config->getValue("Editor", keyname) == "true"){
  71. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Проверка хэша успешно завершена: ", filename.toLocal8Bit().data());
  72. busy = false;
  73. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  74. return;
  75. }
  76. qDebug("%s:%i: %s%s", __FILE__, __LINE__, "Хэш файла не совпал: ", filename.toLocal8Bit().data());
  77. QStringList parsename = filename.split("_");
  78. QString name = parsename[0] + "Status";
  79. download_name = parsename[0];
  80. // Проверка, что файл не был отменён
  81. if(app->config->getValue("Editor", download_name) == "false") {
  82. emit changePatchStatus(download_name, "Отменён");
  83. busy = false;
  84. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  85. return;
  86. }
  87. if (!output.open(QIODevice::WriteOnly)) {
  88. qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Произошла остановка скачивания (не могу открыть файл) "
  89. , filename.toLocal8Bit().data());
  90. emit changePatchStatus(download_name, "Ошибка записи");
  91. busy = false;
  92. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  93. return;
  94. }
  95. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Начинаем скачивание ", url.fileName().toLocal8Bit().data());
  96. QNetworkRequest request(url);
  97. currentDownload = manager.get(request);
  98. connect(this, SIGNAL(cancelDownload()), currentDownload, SLOT(abort()));
  99. connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)), SLOT(downloadProgress(qint64,qint64)));
  100. connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished()));
  101. connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead()));
  102. // prepare the output
  103. downloadTime.start();
  104. }
  105. void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
  106. App* app = &App::getInstance();
  107. double speed = (bytesReceived - bytesReceivedBeforeSecond) * 1000.0 / (downloadTime.elapsed() - timeElapsedBeforeSecond);
  108. double percent = double(std::ceil(((double)bytesReceived/ bytesTotal) * 100 * 10)) / 10.0;
  109. QString unit;
  110. if (speed < 1024) {
  111. unit = "bytes/sec";
  112. } else if (speed < 1024*1024) {
  113. speed /= 1024;
  114. unit = "kB/s";
  115. } else {
  116. speed /= 1024*1024;
  117. unit = "MB/s";
  118. }
  119. QString speedtext = QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit);
  120. QString percenttext = QString::fromLatin1("%1").arg(percent, 3, 'f', 1);
  121. if (downloadTime.elapsed() - timeElapsedBeforeSecond >= 1000) {
  122. timeElapsedBeforeSecond = downloadTime.elapsed();
  123. bytesReceivedBeforeSecond = bytesReceived;
  124. current_speed = speedtext;
  125. }
  126. if (current_speed == "")
  127. current_speed = speedtext;
  128. QString elapsed_time = app->helper->countFormattedElapsedTime(bytesTotal - bytesReceived, bytesReceived * 1000.0 / downloadTime.elapsed());
  129. emit changePatchStatus(download_name, "Загрузка ... <br/>" + percenttext + "% (" + current_speed + ")");
  130. emit changeHint("Загрузка патча " + LotroManager::getInstance().patchTitleFromName(download_name),
  131. "Завершено " + percenttext + "% (" + current_speed + "). Осталось примерно " + elapsed_time);
  132. }
  133. void DownloadManager::downloadFinished() {
  134. busy = false;
  135. output.close();
  136. qDebug() << "Finished download: " << output.fileName().split('/').last().split('_')[0];
  137. downloaded_list.append(output.fileName().split('/').last().split('_')[0]);
  138. App *app = &App::getInstance();
  139. app->helper->setState("free");// говорим что приложение освободилось
  140. if (currentDownload->error()) {
  141. qWarning("%s:%i: %s%s", __FILE__, __LINE__, "Загрузка не удалась: ", currentDownload->errorString().toLocal8Bit().data());
  142. emit changePatchStatus(download_name, "Не удалась");
  143. } else {
  144. emit changePatchStatus(download_name, "Готово");
  145. ++downloadedCount;
  146. }
  147. if (downloadQueue.isEmpty()) {
  148. qInfo("%s:%i: %s", __FILE__, __LINE__, "Все загрузки завершены. Загрузчик завершил свою работу.");
  149. emit allDownloadsFinished(downloaded_list);
  150. } else {
  151. QTimer::singleShot(0, this, SLOT(startNextDownload()));
  152. }
  153. currentDownload->deleteLater();
  154. }
  155. void DownloadManager::downloadReadyRead(){
  156. output.write(currentDownload->readAll());
  157. }
  158. void DownloadManager::abortDownload(QString name){
  159. App *app = &App::getInstance();
  160. if(download_name == name){
  161. if(app->state != "free" && currentDownload != NULL && currentDownload->isOpen()) {
  162. qDebug() << "Прерываем закачку " + download_name;
  163. qInfo("%s:%i: %s%s", __FILE__, __LINE__, "Пользователь прервал закачку файла ", download_name.toLocal8Bit().data());
  164. emit changePatchStatus(name, "Отменён");
  165. currentDownload->abort();
  166. }
  167. }
  168. downloadQueue.removeAll(name);
  169. }
  170. int DownloadManager::getDownloadedCount() {
  171. return downloadedCount;
  172. }
  173. void DownloadManager::resetDownloadedCount() {
  174. totalCount = 0;
  175. downloadedCount = 0;
  176. downloaded_list.clear();
  177. }