Yokan / rebuild
Course 1 8624561

DownloadKeepAlive.android.kt

composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.android.kt

implementation85 lines
1package eu.friedcutlet.yokan.services.download23import android.content.Context4import androidx.work.Constraints5import androidx.work.CoroutineWorker6import androidx.work.ExistingWorkPolicy7import androidx.work.NetworkType8import androidx.work.OneTimeWorkRequestBuilder9import androidx.work.WorkManager10import androidx.work.WorkerParameters11import androidx.work.workDataOf12import eu.friedcutlet.yokan.AndroidAppContext13import eu.friedcutlet.yokan.domain.ProfileId14import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace15import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult16import eu.friedcutlet.yokan.database.YokanDatabase17import eu.friedcutlet.yokan.services.logging.AppLogger18import kotlinx.coroutines.CoroutineScope19import kotlinx.coroutines.flow.first20import kotlinx.coroutines.launch2122/** Implemented by the `Application`: a resume worker in a cold process gets a profile-bound download service through it. */23interface DownloadTaskHost {24    suspend fun runBackgroundDownloads(owner: String?, task: suspend DownloadService.() -> Unit): ProfileWorkResult<Unit>25}2627private const val DOWNLOAD_RESUME_WORK = "yokan.download_resume"28internal val androidDownloadBindings = ProfileDownloadBindings()2930actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) {31    val context = AndroidAppContext.appContext ?: return32    val binding = androidDownloadBindings.install(profileId, downloads, scope) { database.settings().features.privacy.hideNotificationContent }33    val workName = ProfileWorkNamespace(profileId).uniqueName(DOWNLOAD_RESUME_WORK)34    scope.launch {35        var resumeScheduled = false36        downloads.queueStatus.collect { status ->37            // Asked again on every queue change: a start refused in the background succeeds once the app is back.38            if (needsKeepAlive(status)) DownloadForegroundService.start(context, binding)39            val pending = status.pending > 040            if (pending == resumeScheduled) return@collect41            resumeScheduled = pending42            runCatching {43                val work = WorkManager.getInstance(context)44                if (pending) {45                    // ponytail: KEEP keeps the network constraint the work was enqueued with; a Wi-Fi-only toggle46                    // while downloads are pending applies from the next queue.47                    work.enqueueUniqueWork(workName, ExistingWorkPolicy.KEEP, resumeRequest(database.settings().downloadOnlyOnWifi, profileId))48                } else {49                    work.cancelUniqueWork(workName)50                }51            }.onFailure { AppLogger.warn("Could not schedule the download resume job: ${it.message.orEmpty()}") }52        }53    }54}5556private fun resumeRequest(wifiOnly: Boolean, profileId: ProfileId) = OneTimeWorkRequestBuilder<DownloadResumeWorker>()57    .setInputData(workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value))58    .setConstraints(59        Constraints.Builder()60            .setRequiredNetworkType(if (wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED)61            .build(),62    )63    .build()6465/**66 * Resumes downloads in a process the system killed: bootstrapping re-queues the interrupted ones. It runs until67 * the queue drains, which keeps the process alive; when the system stops it, WorkManager runs it again later.68 */69class DownloadResumeWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {70    override suspend fun doWork(): Result {71        // YokanApplication normally sets this; never let a worker fail on a missing context.72        if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext73        val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) {74            inputData.getString(ProfileWorkNamespace.OwnerKey) ?: ""75        } else null // Explicit adoption of pre-profile Default resume jobs only.76        val outcome = (applicationContext as DownloadTaskHost).runBackgroundDownloads(owner) {77            initialize()78            queueStatus.first { it.pending == 0 }79        }80        return when (outcome) {81            is ProfileWorkResult.Completed, ProfileWorkResult.Skipped -> Result.success()82            ProfileWorkResult.Retry -> if (runAttemptCount < 3) Result.retry() else Result.failure()83        }84    }85}86

Search chapters, reference and source filenames.