package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.AndroidAppContext import android.content.Context import android.net.NetworkCapabilities import android.net.NetworkRequest import android.os.Build import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.ListenableWorker import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.YokanDatabase import java.util.concurrent.TimeUnit actual fun createPlatformBackgroundScheduler(database: YokanDatabase, profileId: ProfileId): BackgroundScheduler = AndroidBackgroundScheduler(profileId) /** * Implemented by the `Application`: a worker in a cold process bootstraps the app through it and gets * a profile-bound execution path, like WorkManager's `Configuration.Provider` lookup. */ interface BackgroundTaskHost { suspend fun runBackgroundTask(owner: String?, task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome): ProfileWorkResult } private const val METADATA_REFRESH_WORK = "yokan.metadata_refresh" private const val LIBRARY_UPDATE_WORK = "yokan.library_update" private const val AUTO_SYNC_WORK = "yokan.auto_sync" private const val AUTO_BACKUP_WORK = "yokan.auto_backup" /** Retries within one period before giving up until the next scheduled run. */ private const val MAX_WORKER_RETRIES = 3 internal fun libraryWorkConstraints(requireUnmetered: Boolean, config: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints): Constraints { val network = when (config.network) { eu.friedcutlet.yokan.database.DbUpdateNetwork.Legacy -> if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED eu.friedcutlet.yokan.database.DbUpdateNetwork.Unmetered -> NetworkType.UNMETERED else -> NetworkType.CONNECTED } val builder = Constraints.Builder().setRequiredNetworkType(network).setRequiresCharging(config.requireExternalPower) if (config.network == eu.friedcutlet.yokan.database.DbUpdateNetwork.Wifi && Build.VERSION.SDK_INT >= 28) { builder.setRequiredNetworkRequest(NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), NetworkType.CONNECTED) } return builder.build() } internal fun libraryWorkPolicy(previous: Pair?, next: Pair): ExistingPeriodicWorkPolicy = if (next.second >= 0 && previous != null && previous != next) ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE else ExistingPeriodicWorkPolicy.UPDATE internal fun periodicWorkerResult(outcome: ProfileWorkResult, attempt: Int): ListenableWorker.Result = when { !outcome.shouldRetry -> ListenableWorker.Result.success() outcome is ProfileWorkResult.Completed && outcome.value.status == PeriodicTaskStatus.Deferred -> ListenableWorker.Result.retry() attempt < MAX_WORKER_RETRIES -> ListenableWorker.Result.retry() else -> ListenableWorker.Result.failure() } private class AndroidBackgroundScheduler(profileId: ProfileId) : BackgroundScheduler { private val names = ProfileWorkNamespace(profileId) private val owner = workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value) /** Last (minutes, dailyAt) applied in this process; a change re-anchors instead of UPDATE-ing in place. */ private var appliedLibrarySchedule: Pair? = null override fun schedule( metadataRefreshMinutes: Long, libraryUpdateMinutes: Long, libraryUpdateDailyAtMinutes: Int, autoSyncMinutes: Long, autoBackupHours: Long, requireUnmetered: Boolean, libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints, ) { val ctx = AndroidAppContext.appContext ?: return val wm = WorkManager.getInstance(ctx) val constraints = Constraints.Builder() .setRequiredNetworkType(if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED) .build() if (metadataRefreshMinutes > 0) { wm.enqueueUniquePeriodicWork( names.uniqueName(METADATA_REFRESH_WORK), ExistingPeriodicWorkPolicy.UPDATE, PeriodicWorkRequestBuilder(metadataRefreshMinutes, TimeUnit.MINUTES) .setInputData(owner) .setConstraints(constraints) .build(), ) } else { wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK)) } if (libraryUpdateMinutes > 0) { val libraryOnlyConstraints = libraryWorkConstraints(requireUnmetered, libraryConstraints) val daily = libraryUpdateDailyAtMinutes >= 0 val schedule = libraryUpdateMinutes to libraryUpdateDailyAtMinutes // UPDATE keeps the existing period anchor, so a changed daily time must cancel and re-enqueue; // interval mode keeps UPDATE so every settings save does not push the next run further out. val policy = libraryWorkPolicy(appliedLibrarySchedule, schedule) appliedLibrarySchedule = schedule // ponytail: WorkManager re-anchors each period on the previous run's start, so a daily slot drifts // by however long constraints/Doze delayed the last run; switch to a self-rescheduling // OneTimeWorkRequest if users report drift. val request = PeriodicWorkRequestBuilder( if (daily) 24L * 60L else libraryUpdateMinutes, TimeUnit.MINUTES, ).setConstraints(libraryOnlyConstraints).setInputData(owner) if (daily) request.setInitialDelay(nextDailySlotDelayMillis(libraryUpdateDailyAtMinutes), TimeUnit.MILLISECONDS) wm.enqueueUniquePeriodicWork(names.uniqueName(LIBRARY_UPDATE_WORK), policy, request.build()) } else { appliedLibrarySchedule = null wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK)) } if (autoSyncMinutes > 0) { wm.enqueueUniquePeriodicWork( names.uniqueName(AUTO_SYNC_WORK), ExistingPeriodicWorkPolicy.UPDATE, PeriodicWorkRequestBuilder(autoSyncMinutes, TimeUnit.MINUTES) .setInputData(owner) .setConstraints(constraints) .build(), ) } else { wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK)) } if (autoBackupHours > 0) { wm.enqueueUniquePeriodicWork( names.uniqueName(AUTO_BACKUP_WORK), ExistingPeriodicWorkPolicy.UPDATE, PeriodicWorkRequestBuilder(autoBackupHours, TimeUnit.HOURS) .setInputData(owner) .setConstraints(Constraints.NONE) .build(), ) } else { wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK)) } } override fun cancelAll() { val ctx = AndroidAppContext.appContext ?: return val wm = WorkManager.getInstance(ctx) wm.cancelUniqueWork(names.uniqueName(METADATA_REFRESH_WORK)) wm.cancelUniqueWork(names.uniqueName(LIBRARY_UPDATE_WORK)) wm.cancelUniqueWork(names.uniqueName(AUTO_SYNC_WORK)) wm.cancelUniqueWork(names.uniqueName(AUTO_BACKUP_WORK)) } } /** * WorkManager workers delegate to the shared runner so a killed UI process * produces the same outcome and notification as an in-app periodic tick. */ class MetadataRefreshWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::refreshMetadata) } class LibraryUpdateWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::updateLibrary) } class AutoSyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::sync) } class AutoBackupWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = runPeriodicTask(PeriodicTaskRunner::backup) } private suspend fun CoroutineWorker.runPeriodicTask( task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome, ): ListenableWorker.Result { // YokanApplication normally sets this; never let a worker fail on a missing context. if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext // Missing data belongs only to pre-profile Default jobs. A present but non-string ID is invalid. val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) { inputData.getString(ProfileWorkNamespace.OwnerKey) ?: "" } else null val outcome = (applicationContext as BackgroundTaskHost).runBackgroundTask(owner, task) return periodicWorkerResult(outcome, runAttemptCount) }