From dd59b89ddf8c9c021d5e8ee567699e112a0f2f74 Mon Sep 17 00:00:00 2001 From: Bnyro Date: Sun, 14 Apr 2024 13:08:31 +0200 Subject: [PATCH] fix: crash in DownloadService if trying to read dead download item --- .../com/github/libretube/db/dao/DownloadDao.kt | 2 +- .../github/libretube/services/DownloadService.kt | 16 +++++++--------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/com/github/libretube/db/dao/DownloadDao.kt b/app/src/main/java/com/github/libretube/db/dao/DownloadDao.kt index 297676ef52..e0d1e0dba8 100644 --- a/app/src/main/java/com/github/libretube/db/dao/DownloadDao.kt +++ b/app/src/main/java/com/github/libretube/db/dao/DownloadDao.kt @@ -23,7 +23,7 @@ interface DownloadDao { suspend fun findById(videoId: String): DownloadWithItems @Query("SELECT * FROM downloaditem WHERE id = :id") - suspend fun findDownloadItemById(id: Int): DownloadItem + suspend fun findDownloadItemById(id: Int): DownloadItem? @Query("DELETE FROM downloaditem WHERE id = :id") suspend fun deleteDownloadItemById(id: Int) diff --git a/app/src/main/java/com/github/libretube/services/DownloadService.kt b/app/src/main/java/com/github/libretube/services/DownloadService.kt index 64654bf123..e37d125922 100644 --- a/app/src/main/java/com/github/libretube/services/DownloadService.kt +++ b/app/src/main/java/com/github/libretube/services/DownloadService.kt @@ -55,7 +55,6 @@ import kotlin.io.path.div import kotlin.io.path.fileSize import kotlin.math.min import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob @@ -341,7 +340,8 @@ class DownloadService : LifecycleService() { } lifecycleScope.launch(coroutineContext) { - downloadFile(Database.downloadDao().findDownloadItemById(id)) + val file = Database.downloadDao().findDownloadItemById(id) ?: return@launch + downloadFile(file) } } @@ -361,16 +361,14 @@ class DownloadService : LifecycleService() { /** * Stop downloading job for given [id]. If no downloads are active, stop the service. */ - private fun stop(id: Int) = CoroutineScope(Dispatchers.IO).launch { + private fun stop(id: Int) = lifecycleScope.launch(coroutineContext) { downloadQueue[id] = false _downloadFlow.emit(id to DownloadStatus.Stopped) - lifecycleScope.launch { - val item = Database.downloadDao().findDownloadItemById(id) - notificationManager.cancel(item.getNotificationId()) - Database.downloadDao().deleteDownloadItemById(id) - stopServiceIfDone() - } + val item = Database.downloadDao().findDownloadItemById(id) ?: return@launch + notificationManager.cancel(item.getNotificationId()) + Database.downloadDao().deleteDownloadItemById(id) + stopServiceIfDone() } /**