package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.system.isOnUnmeteredNetwork import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * Process-local fallback for desktop/web and an immediate in-app companion to * OS background schedulers. Every completed task uses [PeriodicTaskRunner], so * foreground and background executions produce the same result notification. * * The ticker runs in the owner's [scope]; cancelling it stops the scheduler. */ class ForegroundScheduler( private val database: YokanDatabase, private val periodicTasks: PeriodicTaskRunner, private val scope: CoroutineScope, ) { private var job: Job? = null fun start() { if (job?.isActive == true) return job = scope.launch { val lastRun = LastRun(startedAt = nowMillis()) while (true) { catchingNonCancellation { tick(lastRun) } .onFailure { AppLogger.warn("ForegroundScheduler tick failed: ${it.message.orEmpty()}") } delay(60_000) } } } fun stop() { job?.cancel() job = null } private suspend fun tick(lastRun: LastRun) { val settings = database.settings() val networkAllowed = !settings.downloadOnlyOnWifi || isOnUnmeteredNetwork() if ( networkAllowed && settings.metadataServerEnabled && shouldRun(settings.metadataRefreshFrequencySeconds, lastRun.metadataRefresh) ) { if (attempt("Metadata refresh") { periodicTasks.refreshMetadata() }) lastRun.metadataRefresh = nowMillis() } // Library-specific admission belongs to the shared runner, including explicit overrides. if (shouldRunLibraryUpdate(settings, lastRun.libraryUpdate, lastRun.startedAt)) { if (attempt("Library update") { periodicTasks.updateLibrary() }) lastRun.libraryUpdate = nowMillis() } if (shouldRunBackup(settings, lastRun.backup)) { if (attempt("Automatic backup") { periodicTasks.backup() }) lastRun.backup = nowMillis() } val syncPreference = database.syncPreferences().firstOrNull() if ( networkAllowed && syncPreference?.syncOn == true && !syncPreference.authToken.isNullOrBlank() && shouldRun(syncPreference.autoSyncFrequency, lastRun.sync) ) { if (attempt("Automatic sync") { periodicTasks.sync() }) lastRun.sync = nowMillis() } if (!networkAllowed) { AppLogger.info("ForegroundScheduler skipped network work: metered connection while downloadOnlyOnWifi is on.") } } /** * Runs one task in isolation so its failure neither skips the others nor resets their * timestamps. A task that throws still counts as attempted and waits for its next slot * instead of re-running every tick. */ private suspend fun attempt(label: String, task: suspend () -> PeriodicTaskOutcome): Boolean = catchingNonCancellation { task().attempted }.getOrElse { error -> AppLogger.warn("$label failed: ${error.message.orEmpty()}") true } private fun shouldRun(seconds: Int, last: Long): Boolean = seconds > 0 && nowMillis() - last >= seconds.toLong() * 1000L /** Daily mode fires once per slot, and only for slots after this scheduler started. */ private fun shouldRunLibraryUpdate(settings: DbSettings, last: Long, startedAt: Long): Boolean { if (settings.libraryUpdateFrequencySeconds <= 0) return false if (settings.libraryUpdateDailyAtMinutes < 0) return shouldRun(settings.libraryUpdateFrequencySeconds, last) return latestDailySlotMillis(settings.libraryUpdateDailyAtMinutes) > maxOf(last, startedAt) } private fun shouldRunBackup(settings: DbSettings, last: Long): Boolean { val frequencyHours = backupFrequencyHours(settings.backupFrequency) return frequencyHours > 0 && nowMillis() - last >= frequencyHours * 60L * 60L * 1000L } /** Last-run timestamps, confined to the ticker coroutine. */ private class LastRun(val startedAt: Long) { var metadataRefresh = 0L var libraryUpdate = 0L var backup = 0L var sync = 0L } }