| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "network-web/downloadmanager.h" |
| 4 | |
| 5 | #include "gui/dialogs/filedialog.h" |
| 6 | #include "gui/dialogs/formmain.h" |
| 7 | #include "gui/messagebox.h" |
| 8 | #include "gui/tabwidget.h" |
| 9 | #include "miscellaneous/application.h" |
| 10 | #include "miscellaneous/autosaver.h" |
| 11 | #include "miscellaneous/settings.h" |
| 12 | #include "network-web/silentnetworkaccessmanager.h" |
| 13 | |
| 14 | #include "ui_downloaditem.h" |
| 15 | #include "ui_downloadmanager.h" |
| 16 | |
| 17 | #include <cmath> |
| 18 | |
| 19 | #include <QDebug> |
| 20 | #include <QDesktopServices> |
| 21 | #include <QFileIconProvider> |
| 22 | #include <QHeaderView> |
| 23 | #include <QMessageBox> |
| 24 | #include <QMetaEnum> |
| 25 | #include <QMetaObject> |
| 26 | #include <QMimeData> |
| 27 | #include <QSettings> |
| 28 | |
| 29 | DownloadItem::DownloadItem(QNetworkReply* reply, |
| 30 | const QString& preferred_file_name, |
| 31 | const std::function<void(DownloadItem*)>& run_on_finish, |
| 32 | QWidget* parent) |
| 33 | : QWidget(parent), m_ui(new Ui::DownloadItem), m_reply(reply), m_preferredFileName(preferred_file_name), |
| 34 | m_runOnFinish(run_on_finish), m_bytesReceived(0), m_requestFileName(false), m_startedSaving(false), |
| 35 | m_finishedDownloading(false), m_gettingFileName(false), m_canceledFileSelect(false) { |
| 36 | m_ui->setupUi(this); |
| 37 | m_ui->m_btnTryAgain->hide(); |
| 38 | m_requestFileName = qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::AlwaysPromptForFilename)).toBool(); |
| 39 | |
| 40 | m_ui->m_btnTryAgain->setIcon(qApp->icons()->fromTheme(QSL("view-refresh"))); |
| 41 | m_ui->m_btnOpenFile->setIcon(qApp->icons()->fromTheme(QSL("document-open"))); |
| 42 | m_ui->m_btnOpenFolder->setIcon(qApp->icons()->fromTheme(QSL("folder"))); |
| 43 | m_ui->m_btnStopDownload->setIcon(qApp->icons()->fromTheme(QSL("process-stop"))); |
| 44 | |
| 45 | connect(m_ui->m_btnStopDownload, &QPushButton::clicked, this, &DownloadItem::stop); |
| 46 | connect(m_ui->m_btnOpenFile, &QPushButton::clicked, this, &DownloadItem::openFile); |
| 47 | connect(m_ui->m_btnTryAgain, &QPushButton::clicked, this, &DownloadItem::tryAgain); |
| 48 | connect(m_ui->m_btnOpenFolder, &QPushButton::clicked, this, &DownloadItem::openFolder); |
| 49 | |
| 50 | init(); |
| 51 | } |
| 52 | |
| 53 | DownloadItem::~DownloadItem() { |
| 54 | delete m_ui; |
| 55 | } |
| 56 | |
| 57 | void DownloadItem::init() { |
| 58 | if (m_reply == nullptr) { |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | m_startedSaving = false; |
| 63 | m_finishedDownloading = false; |
| 64 | m_ui->m_btnOpenFile->setEnabled(false); |
| 65 | m_ui->m_btnOpenFolder->setEnabled(false); |
| 66 | m_url = m_reply->url(); |
| 67 | m_reply->setParent(this); |
| 68 | |
| 69 | connect(m_reply, &QNetworkReply::readyRead, this, &DownloadItem::downloadReadyRead); |
| 70 | |
| 71 | #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 |
| 72 | connect(m_reply, &QNetworkReply::errorOccurred, this, &DownloadItem::error); |
| 73 | #else |
| 74 | connect(m_reply, |
| 75 | static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), |
| 76 | this, |
| 77 | &DownloadItem::error); |
| 78 | #endif |
| 79 | |
| 80 | connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadItem::downloadProgress); |
| 81 | connect(m_reply, &QNetworkReply::metaDataChanged, this, &DownloadItem::metaDataChanged); |
| 82 | connect(m_reply, &QNetworkReply::finished, this, &DownloadItem::finished); |
| 83 | |
| 84 | // Reset info. |
| 85 | m_ui->m_lblInfoDownload->clear(); |
| 86 | m_ui->m_progressDownload->setValue(0); |
| 87 | getFileName(); |
| 88 | |
| 89 | // Start timer for the download estimation. |
| 90 | m_downloadTime.start(); |
| 91 | |
| 92 | if (m_reply->error() != QNetworkReply::NoError) { |
| 93 | error(m_reply->error()); |
| 94 | finished(); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | void DownloadItem::getFileName() { |
| 99 | if (m_gettingFileName) { |
| 100 | return; |
| 101 | } |
| 102 | |
| 103 | const QString download_directory = qApp->downloadManager()->downloadDirectory(); |
| 104 | QString chosen_filename = saveFileName(download_directory); |
| 105 | const QString filename_for_prompt = |
| 106 | qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetExplicitDirectory)).toString() + |
| 107 | QDir::separator() + QFileInfo(chosen_filename).fileName(); |
| 108 | |
| 109 | if (m_requestFileName) { |
| 110 | // User must provide the path where he wants to save downloaded file in. |
| 111 | m_gettingFileName = true; |
| 112 | chosen_filename = FileDialog::saveFileName(this, |
| 113 | tr("Select destination for downloaded file"), |
| 114 | filename_for_prompt, |
| 115 | QString(), |
| 116 | nullptr); |
| 117 | m_gettingFileName = false; |
| 118 | |
| 119 | if (chosen_filename.isEmpty()) { |
| 120 | stop(); |
| 121 | m_ui->m_progressDownload->setVisible(false); |
| 122 | m_ui->m_lblLocalFilename->setText(tr("Selection of local file cancelled.")); |
| 123 | m_canceledFileSelect = true; |
| 124 | return; |
| 125 | } |
| 126 | |
| 127 | const QFileInfo file_info = QFileInfo(chosen_filename); |
| 128 | |
| 129 | qApp->settings()->setValue(GROUP(Downloads), |
| 130 | Downloads::TargetExplicitDirectory, |
| 131 | QDir::toNativeSeparators(QFileInfo(chosen_filename).absolutePath())); |
| 132 | qApp->downloadManager()->setDownloadDirectory(file_info.absoluteDir().absolutePath()); |
| 133 | } |
| 134 | |
| 135 | m_output.setFileName(chosen_filename); |
| 136 | |
| 137 | // Check file path for saving. |
| 138 | const QDir save_dir = QFileInfo(m_output.fileName()).dir(); |
| 139 | |
| 140 | if (!save_dir.exists() && !save_dir.mkpath(save_dir.absolutePath())) { |
| 141 | stop(); |
| 142 | m_ui->m_progressDownload->setVisible(false); |
| 143 | m_ui->m_lblInfoDownload->setText(tr("Download directory couldn't be created")); |
| 144 | return; |
| 145 | } |
| 146 | |
| 147 | updateInfoAndUrlLabel(); |
| 148 | |
| 149 | if (m_requestFileName) { |
| 150 | downloadReadyRead(); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | QString DownloadItem::saveFileName(const QString& directory) const { |
| 155 | QString path; |
| 156 | |
| 157 | if (m_reply->hasRawHeader("Content-Disposition")) { |
| 158 | QString value = QLatin1String(m_reply->rawHeader("Content-Disposition")); |
| 159 | QRegularExpression exp(QSL(".*filename\\s*=\\s*\"?([^\"]+)\"?")); |
| 160 | QRegularExpressionMatch match = exp.match(value); |
| 161 | |
| 162 | if (match.isValid()) { |
| 163 | QString name = match.captured(1); |
| 164 | |
| 165 | path = QUrl::fromPercentEncoding(name.toLocal8Bit()); |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | if (!m_preferredFileName.isEmpty()) { |
| 170 | path = m_preferredFileName; |
| 171 | } |
| 172 | else if (path.isEmpty()) { |
| 173 | path = m_url.path(); |
| 174 | } |
| 175 | |
| 176 | const QFileInfo info(path); |
| 177 | QString base_name = info.completeBaseName(); |
| 178 | QString end_name = info.suffix(); |
| 179 | |
| 180 | static QRegularExpression reg(QSL("\\/|<|\\?")); |
| 181 | |
| 182 | if (base_name.isEmpty() || base_name.contains(reg)) { |
| 183 | base_name = QSL("unnamed_download"); |
| 184 | } |
| 185 | |
| 186 | if (!end_name.isEmpty()) { |
| 187 | end_name = QL1C('.') + end_name; |
| 188 | } |
| 189 | |
| 190 | QString name = directory + base_name + end_name; |
| 191 | |
| 192 | if (!m_requestFileName && QFile::exists(name)) { |
| 193 | int i = 1; |
| 194 | |
| 195 | do { |
| 196 | name = directory + base_name + QL1C('-') + QString::number(i++) + end_name; |
| 197 | } |
| 198 | while (QFile::exists(name)); |
| 199 | } |
| 200 | |
| 201 | return name; |
| 202 | } |
| 203 | |
| 204 | const QFile& DownloadItem::output() const { |
| 205 | return m_output; |
| 206 | } |
| 207 | |
| 208 | void DownloadItem::stop() { |
| 209 | setUpdatesEnabled(false); |
| 210 | m_ui->m_btnStopDownload->setEnabled(false); |
| 211 | m_ui->m_btnStopDownload->hide(); |
| 212 | m_ui->m_btnTryAgain->setEnabled(true); |
| 213 | m_ui->m_btnTryAgain->show(); |
| 214 | setUpdatesEnabled(true); |
| 215 | m_reply->abort(); |
| 216 | |
| 217 | emit downloadFinished(); |
| 218 | } |
| 219 | |
| 220 | void DownloadItem::openFile() { |
| 221 | if (!QDesktopServices::openUrl(QUrl::fromLocalFile(m_output.fileName()))) { |
| 222 | qApp->showGuiMessage(Notification::Event::GeneralEvent, |
| 223 | {tr("Cannot open file"), |
| 224 | tr("Cannot open output file. Open it manually."), |
| 225 | QSystemTrayIcon::MessageIcon::Warning}); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | void DownloadItem::openFolder() { |
| 230 | if (m_output.exists()) { |
| 231 | if (!SystemFactory::openFolderFile(m_output.fileName())) { |
| 232 | MsgBox::show(this, |
| 233 | QMessageBox::Icon::Warning, |
| 234 | tr("Cannot open directory"), |
| 235 | tr("Cannot open output directory. Open it manually."), |
| 236 | QString(), |
| 237 | m_output.fileName()); |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | void DownloadItem::tryAgain() { |
| 243 | if (!m_ui->m_btnTryAgain->isEnabled()) { |
| 244 | return; |
| 245 | } |
| 246 | |
| 247 | m_ui->m_btnTryAgain->setEnabled(false); |
| 248 | m_ui->m_btnTryAgain->setVisible(false); |
| 249 | m_ui->m_btnStopDownload->setEnabled(true); |
| 250 | m_ui->m_btnStopDownload->setVisible(true); |
| 251 | m_ui->m_progressDownload->setVisible(true); |
| 252 | QNetworkReply* new_download = qApp->downloadManager()->networkManager()->get(QNetworkRequest(m_url)); |
| 253 | |
| 254 | if (m_reply != nullptr) { |
| 255 | m_reply->deleteLater(); |
| 256 | } |
| 257 | |
| 258 | if (m_output.exists()) { |
| 259 | m_output.remove(); |
| 260 | } |
| 261 | |
| 262 | m_reply = new_download; |
| 263 | init(); |
| 264 | emit statusChanged(); |
| 265 | } |
| 266 | |
| 267 | void DownloadItem::downloadReadyRead() { |
| 268 | if (m_requestFileName && m_output.fileName().isEmpty()) { |
| 269 | return; |
| 270 | } |
| 271 | |
| 272 | if (!m_output.isOpen()) { |
| 273 | if (!m_requestFileName) { |
| 274 | getFileName(); |
| 275 | } |
| 276 | |
| 277 | if (!m_output.open(QIODevice::WriteOnly)) { |
| 278 | m_ui->m_lblInfoDownload->setText(tr("Error opening output file: %1").arg(m_output.errorString())); |
| 279 | stop(); |
| 280 | emit statusChanged(); |
| 281 | |
| 282 | return; |
| 283 | } |
| 284 | |
| 285 | emit statusChanged(); |
| 286 | } |
| 287 | |
| 288 | if (-1 == m_output.write(m_reply->readAll())) { |
| 289 | m_ui->m_lblInfoDownload->setText(tr("Error when saving file: %1").arg(m_output.errorString())); |
| 290 | m_ui->m_btnStopDownload->click(); |
| 291 | } |
| 292 | else { |
| 293 | m_startedSaving = true; |
| 294 | |
| 295 | if (m_finishedDownloading) { |
| 296 | finished(); |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | void DownloadItem::error(QNetworkReply::NetworkError code) { |
| 302 | Q_UNUSED(code) |
| 303 | |
| 304 | m_ui->m_lblInfoDownload->setText(tr("Error: %1").arg(m_reply->errorString())); |
| 305 | m_ui->m_btnTryAgain->setEnabled(true); |
| 306 | m_ui->m_btnTryAgain->setVisible(true); |
| 307 | emit downloadFinished(); |
| 308 | } |
| 309 | |
| 310 | void DownloadItem::metaDataChanged() { |
| 311 | QVariant locationHeader = m_reply->header(QNetworkRequest::KnownHeaders::LocationHeader); |
| 312 | |
| 313 | if (locationHeader.isValid()) { |
| 314 | m_url = locationHeader.toUrl(); |
| 315 | m_reply->deleteLater(); |
| 316 | m_reply = qApp->downloadManager()->networkManager()->get(QNetworkRequest(m_url)); |
| 317 | init(); |
| 318 | return; |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | void DownloadItem::downloadProgress(qint64 bytes_received, qint64 bytes_total) { |
| 323 | QTime now = QTime::currentTime(); |
| 324 | |
| 325 | if (m_lastProgressTime.isValid() && m_lastProgressTime.msecsTo(now) < 25) { |
| 326 | return; |
| 327 | } |
| 328 | |
| 329 | m_lastProgressTime = now; |
| 330 | m_bytesReceived = bytes_received; |
| 331 | qint64 currentValue = 0; |
| 332 | qint64 totalValue = 0; |
| 333 | |
| 334 | if (bytes_total > 0) { |
| 335 | currentValue = bytes_received * 100 / bytes_total; |
| 336 | totalValue = 100; |
| 337 | } |
| 338 | |
| 339 | m_ui->m_progressDownload->setValue(currentValue); |
| 340 | m_ui->m_progressDownload->setMaximum(totalValue); |
| 341 | emit progress(currentValue, totalValue); |
| 342 | |
| 343 | updateDownloadInfoLabel(); |
| 344 | } |
| 345 | |
| 346 | qint64 DownloadItem::bytesTotal() const { |
| 347 | return m_reply == nullptr ? 0 : m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); |
| 348 | } |
| 349 | |
| 350 | qint64 DownloadItem::bytesReceived() const { |
| 351 | return m_bytesReceived; |
| 352 | } |
| 353 | |
| 354 | double DownloadItem::remainingTime() const { |
| 355 | if (!downloading()) { |
| 356 | return -1.0; |
| 357 | } |
| 358 | |
| 359 | double time_remaining = ((double)(bytesTotal() - bytesReceived())) / currentSpeed(); |
| 360 | |
| 361 | // When downloading the ETA should never be 0. |
| 362 | if ((int)time_remaining == 0) { |
| 363 | time_remaining = 1.0; |
| 364 | } |
| 365 | |
| 366 | return time_remaining; |
| 367 | } |
| 368 | |
| 369 | double DownloadItem::currentSpeed() const { |
| 370 | if (!downloading()) { |
| 371 | return -1.0; |
| 372 | } |
| 373 | else { |
| 374 | return m_bytesReceived * 1000.0 / m_downloadTime.elapsed(); |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | void DownloadItem::updateDownloadInfoLabel() { |
| 379 | if (m_reply->error() != QNetworkReply::NoError) { |
| 380 | return; |
| 381 | } |
| 382 | |
| 383 | const qint64 bytes_total = m_reply->header(QNetworkRequest::ContentLengthHeader).toULongLong(); |
| 384 | bool running = !downloadedSuccessfully(); |
| 385 | double speed = currentSpeed(); |
| 386 | double time_remaining = remainingTime(); |
| 387 | QString info; |
| 388 | |
| 389 | if (running) { |
| 390 | QString remaining; |
| 391 | |
| 392 | if (bytes_total != 0) { |
| 393 | remaining = DownloadManager::timeString(time_remaining); |
| 394 | } |
| 395 | |
| 396 | info = QString(tr("%1 of %2 (%3 per second) - %4")) |
| 397 | .arg(DownloadManager::dataString(m_bytesReceived), |
| 398 | bytes_total == 0 ? QSL("?") : DownloadManager::dataString(bytes_total), |
| 399 | DownloadManager::dataString((int)speed), |
| 400 | remaining); |
| 401 | } |
| 402 | else { |
| 403 | if (m_bytesReceived == bytes_total) { |
| 404 | info = DownloadManager::dataString(m_output.size()); |
| 405 | } |
| 406 | else { |
| 407 | info = tr("%1 of %2 - download completed") |
| 408 | .arg(DownloadManager::dataString(m_bytesReceived), DownloadManager::dataString(m_bytesReceived)); |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | m_ui->m_lblInfoDownload->setText(info); |
| 413 | } |
| 414 | |
| 415 | bool DownloadItem::downloading() const { |
| 416 | return !m_finishedDownloading; |
| 417 | |
| 418 | // return (m_ui->m_progressDownload->isVisible()); |
| 419 | } |
| 420 | |
| 421 | bool DownloadItem::downloadedSuccessfully() const { |
| 422 | return (m_ui->m_btnStopDownload->isHidden() && m_ui->m_btnTryAgain->isHidden()); |
| 423 | } |
| 424 | |
| 425 | void DownloadItem::finished() { |
| 426 | m_finishedDownloading = true; |
| 427 | |
| 428 | if (!m_startedSaving) { |
| 429 | return; |
| 430 | } |
| 431 | |
| 432 | m_ui->m_progressDownload->hide(); |
| 433 | m_ui->m_btnStopDownload->setEnabled(false); |
| 434 | m_ui->m_btnStopDownload->hide(); |
| 435 | m_ui->m_btnOpenFile->setEnabled(true); |
| 436 | m_ui->m_btnOpenFolder->setEnabled(true); |
| 437 | m_output.close(); |
| 438 | updateDownloadInfoLabel(); |
| 439 | emit statusChanged(); |
| 440 | emit downloadFinished(); |
| 441 | |
| 442 | if (m_runOnFinish) { |
| 443 | m_runOnFinish(this); |
| 444 | } |
| 445 | |
| 446 | if (downloadedSuccessfully()) { |
| 447 | qApp->showGuiMessage(Notification::Event::GeneralEvent, |
| 448 | {tr("Download finished"), |
| 449 | tr("File '%1' is downloaded.\nClick here to open parent directory.") |
| 450 | .arg(QDir::toNativeSeparators(m_output.fileName())), |
| 451 | QSystemTrayIcon::MessageIcon::Information}, |
| 452 | {}, |
| 453 | {tr("Open folder"), [this] { |
| 454 | openFolder(); |
| 455 | }}); |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | void DownloadItem::updateInfoAndUrlLabel() { |
| 460 | m_ui->m_lblRemoteFilename->setText(tr("URL: %1").arg(m_url.toString())); |
| 461 | m_ui->m_lblLocalFilename->setText(tr("Local file: %1").arg(QDir::toNativeSeparators(m_output.fileName()))); |
| 462 | } |
| 463 | |
| 464 | DownloadManager::DownloadManager(QWidget* parent) |
| 465 | : TabContent(parent), m_ui(new Ui::DownloadManager), m_autoSaver(new AutoSaver(this)), |
| 466 | m_model(new DownloadModel(this)), m_networkManager(new SilentNetworkAccessManager(this)), m_iconProvider(nullptr), |
| 467 | m_removePolicy(RemovePolicy::Never) { |
| 468 | m_ui->setupUi(this); |
| 469 | m_ui->m_viewDownloads->setShowGrid(false); |
| 470 | m_ui->m_viewDownloads->verticalHeader()->hide(); |
| 471 | m_ui->m_viewDownloads->horizontalHeader()->hide(); |
| 472 | m_ui->m_viewDownloads->setAlternatingRowColors(true); |
| 473 | m_ui->m_viewDownloads->horizontalHeader()->setStretchLastSection(true); |
| 474 | m_ui->m_viewDownloads->setModel(m_model); |
| 475 | |
| 476 | m_ui->m_btnCleanup->setIcon(qApp->icons()->fromTheme(QSL("edit-clear"))); |
| 477 | |
| 478 | setDownloadDirectory(qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::TargetDirectory)).toString()); |
| 479 | connect(m_ui->m_btnCleanup, &QPushButton::clicked, this, &DownloadManager::cleanup); |
| 480 | load(); |
| 481 | } |
| 482 | |
| 483 | DownloadManager::~DownloadManager() { |
| 484 | m_autoSaver->changeOccurred(); |
| 485 | m_autoSaver->saveIfNeccessary(); |
| 486 | qDebugNN << LOGSEC_NETWORK << "Destroying DownloadManager instance."; |
| 487 | } |
| 488 | |
| 489 | int DownloadManager::activeDownloads() const { |
| 490 | int count = 0; |
| 491 | |
| 492 | for (const DownloadItem* download : m_downloads) { |
| 493 | if (download->downloading()) { |
| 494 | count++; |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | return count; |
| 499 | } |
| 500 | |
| 501 | int DownloadManager::downloadProgress() const { |
| 502 | qint64 bytes_total = 0; |
| 503 | qint64 bytes_received = 0; |
| 504 | |
| 505 | for (const DownloadItem* download : m_downloads) { |
| 506 | if (download->downloading()) { |
| 507 | bytes_total += download->bytesTotal(); |
| 508 | bytes_received += download->bytesReceived(); |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | if (bytes_total <= 0) { |
| 513 | return -1; |
| 514 | } |
| 515 | else { |
| 516 | return int((bytes_received * 100.0) / bytes_total); |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | void DownloadManager::download(const QNetworkRequest& request, |
| 521 | const QString& preferred_file_name, |
| 522 | const std::function<void(DownloadItem*)>& run_on_finish) { |
| 523 | if (!request.url().isEmpty()) { |
| 524 | handleUnsupportedContent(m_networkManager->get(request), preferred_file_name, run_on_finish); |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | void DownloadManager::download(const QUrl& url) { |
| 529 | download(QNetworkRequest(url)); |
| 530 | } |
| 531 | |
| 532 | void DownloadManager::handleUnsupportedContent(QNetworkReply* reply, |
| 533 | const QString& preferred_file_name, |
| 534 | const std::function<void(DownloadItem*)>& run_on_finish) { |
| 535 | if (reply == nullptr || reply->url().isEmpty()) { |
| 536 | return; |
| 537 | } |
| 538 | |
| 539 | const QVariant header = reply->header(QNetworkRequest::KnownHeaders::ContentLengthHeader); |
| 540 | bool ok; |
| 541 | const int size = header.toInt(&ok); |
| 542 | |
| 543 | if (ok && size == 0) { |
| 544 | return; |
| 545 | } |
| 546 | |
| 547 | auto* item = new DownloadItem(reply, preferred_file_name, run_on_finish, this); |
| 548 | |
| 549 | addItem(item); |
| 550 | |
| 551 | if (!item->m_canceledFileSelect && |
| 552 | qApp->settings()->value(GROUP(Downloads), SETTING(Downloads::ShowDownloadsWhenNewDownloadStarts)).toBool()) { |
| 553 | qApp->mainForm()->tabWidget()->showDownloadManager(); |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | void DownloadManager::addItem(DownloadItem* item) { |
| 558 | connect(item, |
| 559 | &DownloadItem::statusChanged, |
| 560 | this, |
| 561 | static_cast<void (DownloadManager::*)()>(&DownloadManager::updateRow)); |
| 562 | connect(item, &DownloadItem::progress, this, &DownloadManager::itemProgress); |
| 563 | connect(item, &DownloadItem::downloadFinished, this, &DownloadManager::itemFinished); |
| 564 | |
| 565 | const int row = m_downloads.count(); |
| 566 | |
| 567 | m_model->beginInsertRows(QModelIndex(), row, row); |
| 568 | m_downloads.append(item); |
| 569 | m_model->endInsertRows(); |
| 570 | m_ui->m_viewDownloads->setIndexWidget(m_model->index(row, 0), item); |
| 571 | QIcon icon = style()->standardIcon(QStyle::StandardPixmap::SP_FileIcon); |
| 572 | |
| 573 | item->m_ui->m_lblFileIcon->setPixmap(icon.pixmap(DOWNLOADER_ICON_SIZE, DOWNLOADER_ICON_SIZE)); |
| 574 | m_ui->m_viewDownloads->setRowHeight(row, item->sizeHint().height()); |
| 575 | |
| 576 | // Just in case of download finishes before it is actually added. |
| 577 | updateRow(item); |
| 578 | } |
| 579 | |
| 580 | SilentNetworkAccessManager* DownloadManager::networkManager() const { |
| 581 | return m_networkManager; |
| 582 | } |
| 583 | |
| 584 | int DownloadManager::totalDownloads() const { |
| 585 | return m_downloads.size(); |
| 586 | } |
| 587 | |
| 588 | void DownloadManager::itemFinished() { |
| 589 | emit downloadFinished(); |
| 590 | } |
| 591 | |
| 592 | void DownloadManager::updateRow() { |
| 593 | if (auto* item = qobject_cast<DownloadItem*>(sender())) { |
| 594 | updateRow(item); |
| 595 | } |
| 596 | } |
| 597 | |
| 598 | void DownloadManager::itemProgress() { |
| 599 | int progress = downloadProgress(); |
| 600 | |
| 601 | if (progress < 0) { |
| 602 | emit downloadFinished(); |
| 603 | } |
| 604 | else { |
| 605 | emit downloadProgressed(progress, tr("Downloading %n file(s)...", "", activeDownloads())); |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | void DownloadManager::updateRow(DownloadItem* item) { |
| 610 | const int row = m_downloads.indexOf(item); |
| 611 | |
| 612 | if (row == -1) { |
| 613 | return; |
| 614 | } |
| 615 | |
| 616 | if (m_iconProvider.isNull()) { |
| 617 | m_iconProvider.reset(new QFileIconProvider()); |
| 618 | } |
| 619 | |
| 620 | QIcon icon = m_iconProvider->icon(QFileInfo(item->m_output.fileName())); |
| 621 | |
| 622 | if (icon.isNull()) { |
| 623 | icon = style()->standardIcon(QStyle::StandardPixmap::SP_FileIcon); |
| 624 | } |
| 625 | |
| 626 | item->m_ui->m_lblFileIcon->setPixmap(icon.pixmap(DOWNLOADER_ICON_SIZE, DOWNLOADER_ICON_SIZE)); |
| 627 | int old_height = m_ui->m_viewDownloads->rowHeight(row); |
| 628 | |
| 629 | m_ui->m_viewDownloads->setRowHeight(row, qMax(old_height, item->minimumSizeHint().height())); |
| 630 | |
| 631 | // Remove the item if: |
| 632 | // a) It is not downloading and private browsing is enabled. |
| 633 | // OR |
| 634 | // b) Item is already downloaded and it should be remove from downloader list. |
| 635 | bool remove = item->downloadedSuccessfully() && removePolicy() == RemovePolicy::OnSuccessfullDownload; |
| 636 | |
| 637 | if (remove) { |
| 638 | m_model->removeRow(row); |
| 639 | } |
| 640 | |
| 641 | m_ui->m_btnCleanup->setEnabled(m_downloads.count() - activeDownloads() > 0); |
| 642 | } |
| 643 | |
| 644 | DownloadManager::RemovePolicy DownloadManager::removePolicy() const { |
| 645 | return m_removePolicy; |
| 646 | } |
| 647 | |
| 648 | void DownloadManager::setRemovePolicy(RemovePolicy policy) { |
| 649 | if (policy != m_removePolicy) { |
| 650 | m_removePolicy = policy; |
| 651 | m_autoSaver->changeOccurred(); |
| 652 | |
| 653 | emit removePolicyChanged(); |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | void DownloadManager::save() const { |
| 658 | if (m_removePolicy == RemovePolicy::OnExit) { |
| 659 | // No saving. |
| 660 | return; |
| 661 | } |
| 662 | |
| 663 | Settings* settings = qApp->settings(); |
| 664 | QString key; |
| 665 | |
| 666 | settings->setValue(GROUP(Downloads), Downloads::RemovePolicy, (int)removePolicy()); |
| 667 | |
| 668 | // Save all download items. |
| 669 | for (int i = 0; i < m_downloads.count(); i++) { |
| 670 | settings->setValue(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i), m_downloads[i]->m_url); |
| 671 | settings->setValue(GROUP(Downloads), |
| 672 | QString(Downloads::ItemLocation).arg(i), |
| 673 | QFileInfo(m_downloads[i]->m_output).filePath()); |
| 674 | settings->setValue(GROUP(Downloads), QString(Downloads::ItemDone).arg(i), m_downloads[i]->downloadedSuccessfully()); |
| 675 | } |
| 676 | |
| 677 | // Remove all redundant saved download items. |
| 678 | int i = m_downloads.size(); |
| 679 | |
| 680 | while (!(key = QString(Downloads::ItemUrl).arg(i)).isEmpty() && settings->contains(GROUP(Downloads), key)) { |
| 681 | settings->remove(GROUP(Downloads), key); |
| 682 | settings->remove(GROUP(Downloads), QString(Downloads::ItemLocation).arg(i)); |
| 683 | settings->remove(GROUP(Downloads), QString(Downloads::ItemDone).arg(i)); |
| 684 | i++; |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | void DownloadManager::load() { |
| 689 | const Settings* settings = qApp->settings(); |
| 690 | int i = 0; |
| 691 | |
| 692 | // Restore the policy. |
| 693 | m_removePolicy = |
| 694 | static_cast<RemovePolicy>(settings->value(GROUP(Downloads), SETTING(Downloads::RemovePolicy)).toInt()); |
| 695 | |
| 696 | // Restore downloads. |
| 697 | while (settings->contains(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i))) { |
| 698 | QUrl url = settings->value(GROUP(Downloads), QString(Downloads::ItemUrl).arg(i)).toUrl(); |
| 699 | QString file_name = settings->value(GROUP(Downloads), QString(Downloads::ItemLocation).arg(i)).toString(); |
| 700 | bool done = settings->value(GROUP(Downloads), QString(Downloads::ItemDone).arg(i), true).toBool(); |
| 701 | |
| 702 | if (!url.isEmpty() && !file_name.isEmpty()) { |
| 703 | auto* item = new DownloadItem(nullptr, {}, {}, this); |
| 704 | |
| 705 | item->m_finishedDownloading = done; |
| 706 | item->m_output.setFileName(file_name); |
| 707 | item->m_url = url; |
| 708 | |
| 709 | item->updateInfoAndUrlLabel(); |
| 710 | |
| 711 | item->m_ui->m_btnStopDownload->setVisible(false); |
| 712 | item->m_ui->m_btnStopDownload->setEnabled(false); |
| 713 | item->m_ui->m_btnTryAgain->setVisible(!done); |
| 714 | item->m_ui->m_btnTryAgain->setEnabled(!done); |
| 715 | item->m_ui->m_progressDownload->setVisible(false); |
| 716 | |
| 717 | addItem(item); |
| 718 | } |
| 719 | |
| 720 | i++; |
| 721 | } |
| 722 | |
| 723 | m_ui->m_btnCleanup->setEnabled(m_downloads.size() - activeDownloads() > 0); |
| 724 | } |
| 725 | |
| 726 | void DownloadManager::cleanup() { |
| 727 | if (!m_downloads.isEmpty()) { |
| 728 | m_model->removeRows(0, m_downloads.count()); |
| 729 | m_ui->m_btnCleanup->setEnabled(false); |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | void DownloadManager::setDownloadDirectory(const QString& directory) { |
| 734 | m_downloadDirectory = directory; |
| 735 | |
| 736 | if (!m_downloadDirectory.isEmpty() && !m_downloadDirectory.endsWith(QDir::separator())) { |
| 737 | m_downloadDirectory += QDir::separator(); |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | QString DownloadManager::downloadDirectory() { |
| 742 | return m_downloadDirectory; |
| 743 | } |
| 744 | |
| 745 | QString DownloadManager::timeString(double time_remaining) { |
| 746 | QString remaining; |
| 747 | |
| 748 | if (time_remaining > 60) { |
| 749 | time_remaining = time_remaining / 60; |
| 750 | time_remaining = floor(time_remaining); |
| 751 | remaining = tr("%n minutes remaining", "", (int)time_remaining); |
| 752 | } |
| 753 | else { |
| 754 | time_remaining = floor(time_remaining); |
| 755 | remaining = tr("%n seconds remaining", "", (int)time_remaining); |
| 756 | } |
| 757 | |
| 758 | return remaining; |
| 759 | } |
| 760 | |
| 761 | QString DownloadManager::dataString(qint64 size) { |
| 762 | QString unit; |
| 763 | double new_size; |
| 764 | |
| 765 | if (size < 1024) { |
| 766 | new_size = size; |
| 767 | unit = tr("bytes"); |
| 768 | } |
| 769 | else if (size < 1024 * 1024) { |
| 770 | new_size = (double)size / (double)1024; |
| 771 | unit = QSL("kB"); |
| 772 | } |
| 773 | else if (size < 1024 * 1024 * 1024) { |
| 774 | new_size = (double)size / (double)(1024 * 1024); |
| 775 | unit = QSL("MB"); |
| 776 | } |
| 777 | else { |
| 778 | new_size = (double)size / (double)(1024 * 1024 * 1024); |
| 779 | unit = QSL("GB"); |
| 780 | } |
| 781 | |
| 782 | return QSL("%1 %2").arg(new_size, 0, 'f', 1).arg(unit); |
| 783 | } |
| 784 | |
| 785 | DownloadModel::DownloadModel(DownloadManager* download_manager, QObject* parent) |
| 786 | : QAbstractListModel(parent), m_downloadManager(download_manager) {} |
| 787 | |
| 788 | QVariant DownloadModel::data(const QModelIndex& index, int role) const { |
| 789 | if (index.row() < 0 || index.row() >= rowCount(index.parent())) { |
| 790 | return QVariant(); |
| 791 | } |
| 792 | |
| 793 | if (role == Qt::ToolTipRole) { |
| 794 | if (!m_downloadManager->m_downloads.at(index.row())->downloadedSuccessfully()) { |
| 795 | return m_downloadManager->m_downloads.at(index.row())->m_ui->m_lblInfoDownload->text(); |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | return QVariant(); |
| 800 | } |
| 801 | |
| 802 | int DownloadModel::rowCount(const QModelIndex& parent) const { |
| 803 | return parent.isValid() ? 0 : m_downloadManager->m_downloads.count(); |
| 804 | } |
| 805 | |
| 806 | bool DownloadModel::removeRows(int row, int count, const QModelIndex& parent) { |
| 807 | if (parent.isValid()) { |
| 808 | return false; |
| 809 | } |
| 810 | |
| 811 | int lastRow = row + count - 1; |
| 812 | |
| 813 | for (int i = lastRow; i >= row; --i) { |
| 814 | if (m_downloadManager->m_downloads.at(i)->downloadedSuccessfully() || |
| 815 | m_downloadManager->m_downloads.at(i)->m_ui->m_btnTryAgain->isEnabled()) { |
| 816 | beginRemoveRows(parent, i, i); |
| 817 | m_downloadManager->m_downloads.takeAt(i)->deleteLater(); |
| 818 | endRemoveRows(); |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | m_downloadManager->m_autoSaver->changeOccurred(); |
| 823 | |
| 824 | if (m_downloadManager->totalDownloads() == 0) { |
| 825 | m_downloadManager->m_ui->m_btnCleanup->setEnabled(false); |
| 826 | } |
| 827 | |
| 828 | return true; |
| 829 | } |
| 830 | |
| 831 | Qt::ItemFlags DownloadModel::flags(const QModelIndex& index) const { |
| 832 | if (index.row() < 0 || index.row() >= rowCount(index.parent())) { |
| 833 | return Qt::ItemFlag::NoItemFlags; |
| 834 | } |
| 835 | |
| 836 | Qt::ItemFlags default_flags = QAbstractListModel::flags(index); |
| 837 | DownloadItem* item = m_downloadManager->m_downloads.at(index.row()); |
| 838 | |
| 839 | if (item->downloadedSuccessfully()) { |
| 840 | return default_flags | Qt::ItemFlag::ItemIsDragEnabled; |
| 841 | } |
| 842 | |
| 843 | return default_flags; |
| 844 | } |
| 845 | |
| 846 | QMimeData* DownloadModel::mimeData(const QModelIndexList& indexes) const { |
| 847 | auto* mimeData = new QMimeData(); |
| 848 | QList<QUrl> urls; |
| 849 | |
| 850 | for (const QModelIndex& index : indexes) { |
| 851 | if (!index.isValid()) { |
| 852 | continue; |
| 853 | } |
| 854 | |
| 855 | urls.append(QUrl::fromLocalFile(QFileInfo(m_downloadManager->m_downloads.at(index.row())->m_output) |
| 856 | .absoluteFilePath())); |
| 857 | } |
| 858 | |
| 859 | mimeData->setUrls(urls); |
| 860 | return mimeData; |
| 861 | } |