package eu.friedcutlet.yokan.services.download import android.content.Context import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import eu.friedcutlet.yokan.AndroidAppContext import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.logging.AppLogger import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch /** Implemented by the `Application`: a resume worker in a cold process gets a profile-bound download service through it. */ interface DownloadTaskHost { suspend fun runBackgroundDownloads(owner: String?, task: suspend DownloadService.() -> Unit): ProfileWorkResult } private const val DOWNLOAD_RESUME_WORK = "yokan.download_resume" internal val androidDownloadBindings = ProfileDownloadBindings() actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) { val context = AndroidAppContext.appContext ?: return val binding = androidDownloadBindings.install(profileId, downloads, scope) { database.settings().features.privacy.hideNotificationContent } val workName = ProfileWorkNamespace(profileId).uniqueName(DOWNLOAD_RESUME_WORK) scope.launch { var resumeScheduled = false downloads.queueStatus.collect { status -> // Asked again on every queue change: a start refused in the background succeeds once the app is back. if (needsKeepAlive(status)) DownloadForegroundService.start(context, binding) val pending = status.pending > 0 if (pending == resumeScheduled) return@collect resumeScheduled = pending runCatching { val work = WorkManager.getInstance(context) if (pending) { // ponytail: KEEP keeps the network constraint the work was enqueued with; a Wi-Fi-only toggle // while downloads are pending applies from the next queue. work.enqueueUniqueWork(workName, ExistingWorkPolicy.KEEP, resumeRequest(database.settings().downloadOnlyOnWifi, profileId)) } else { work.cancelUniqueWork(workName) } }.onFailure { AppLogger.warn("Could not schedule the download resume job: ${it.message.orEmpty()}") } } } } private fun resumeRequest(wifiOnly: Boolean, profileId: ProfileId) = OneTimeWorkRequestBuilder() .setInputData(workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value)) .setConstraints( Constraints.Builder() .setRequiredNetworkType(if (wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED) .build(), ) .build() /** * Resumes downloads in a process the system killed: bootstrapping re-queues the interrupted ones. It runs until * the queue drains, which keeps the process alive; when the system stops it, WorkManager runs it again later. */ class DownloadResumeWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result { // YokanApplication normally sets this; never let a worker fail on a missing context. if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) { inputData.getString(ProfileWorkNamespace.OwnerKey) ?: "" } else null // Explicit adoption of pre-profile Default resume jobs only. val outcome = (applicationContext as DownloadTaskHost).runBackgroundDownloads(owner) { initialize() queueStatus.first { it.pending == 0 } } return when (outcome) { is ProfileWorkResult.Completed, ProfileWorkResult.Skipped -> Result.success() ProfileWorkResult.Retry -> if (runAttemptCount < 3) Result.retry() else Result.failure() } } }