From fa418a6aa014c2f19c928165bb36f1638a46802e Mon Sep 17 00:00:00 2001 From: Veloman Yunkan Date: Sun, 10 Mar 2024 18:23:38 +0400 Subject: [PATCH] Safer ContentManager::pauseBook() --- src/contentmanager.cpp | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/contentmanager.cpp b/src/contentmanager.cpp index 18f2c01..45acd73 100644 --- a/src/contentmanager.cpp +++ b/src/contentmanager.cpp @@ -670,12 +670,29 @@ void ContentManager::eraseBook(const QString& id) void ContentManager::pauseBook(const QString& id, QModelIndex index) { - auto& b = mp_library->getBookById(id); - auto download = mp_downloader->getDownload(b.getDownloadId()); + const auto downloadId = mp_library->getBookById(id).getDownloadId(); + if ( downloadId.empty() ) { + // Completion of the download has been detected (and its id was reset) + // before the pause-download action was triggered (most likely through + // the context menu which can stay open for an arbitrarily long time, + // or, unlikely, through the ⏸ button during the last milliseconds of + // the download progress). + return; + } + + auto download = mp_downloader->getDownload(downloadId); if (download->getStatus() == kiwix::Download::K_ACTIVE) { - download->pauseDownload(); - if ( const auto downloadState = m_downloads.value(id) ) { - downloadState->pause(); + try { + download->pauseDownload(); + if ( const auto downloadState = m_downloads.value(id) ) { + downloadState->pause(); + } + } catch (const kiwix::AriaError&) { + // Download has completed before the pause request was handled. + // Most likely the download was already complete at the time + // when ContentManager::pauseBook() started executing, but its + // completion was not yet detected (and/or handled) by the download + // updater thread. } } managerModel->triggerDataUpdateAt(index);