package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.backup.BackupService import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.library.LibraryUpdaterService import eu.friedcutlet.yokan.services.metadata.MetadataService import eu.friedcutlet.yokan.services.notifications.NotificationChannel import eu.friedcutlet.yokan.services.notifications.NotificationPayload import eu.friedcutlet.yokan.services.notifications.NotificationService import eu.friedcutlet.yokan.services.sync.SyncService enum class PeriodicTaskStatus { Completed, Failed, Skipped, Deferred } data class PeriodicTaskOutcome( val status: PeriodicTaskStatus, val message: String, ) { val shouldRetry: Boolean get() = status == PeriodicTaskStatus.Failed || status == PeriodicTaskStatus.Deferred val attempted: Boolean get() = status != PeriodicTaskStatus.Skipped && status != PeriodicTaskStatus.Deferred } /** Shared execution path for foreground timers and OS background workers. */ class PeriodicTaskRunner( private val database: YokanDatabase, private val repository: YokanRepository, private val metadata: MetadataService, private val libraryUpdater: LibraryUpdaterService, private val sync: SyncService, private val notifications: NotificationService, private val backup: BackupService? = null, private val updateGate: AutomaticUpdateGate = AutomaticUpdateGate(), ) { suspend fun refreshMetadata(): PeriodicTaskOutcome = execute(PeriodicTask.Metadata) { val settings = database.settings() if (!settings.metadataServerEnabled) { return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Metadata refresh is disabled.") } val baseUrl = settings.metadataServerUrl.trim() if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) { return@execute PeriodicTaskOutcome( PeriodicTaskStatus.Failed, "Metadata server URL must start with http:// or https://.", ) } val titles = ItemType.entries.flatMap(repository::library) var updated = 0 var unmatched = 0 var failed = 0 titles.forEach { title -> catchingNonCancellation { metadata.bestMatch(baseUrl, title.name, title.itemType.toDb()) } .onSuccess { match -> if (match == null) { unmatched++ } else if (repository.applyMetadata(title.id, match) != null) { updated++ } else { failed++ } } .onFailure { failed++ } } PeriodicTaskOutcome( PeriodicTaskStatus.Completed, "Updated metadata for $updated of ${titles.size} titles; $unmatched unmatched, $failed failed.", ) } suspend fun updateLibrary(): PeriodicTaskOutcome = execute(PeriodicTask.Library) { if (!updateGate.check(database.settings()).allowed) { return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Automatic library update is waiting for device/network conditions.") } var checked = 0 var updated = 0 var failed = 0 var crashedTypes = 0 for (type in DbItemType.entries) { var deferred = false catchingNonCancellation { libraryUpdater.updateLibrary(type, mayStartTitle = { updateGate.check(database.settings()).allowed }) } .onSuccess { result -> checked += result.checked updated += result.updated failed += result.failed deferred = result.deferred } .onFailure { crashedTypes++ } if (deferred) return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Deferred, "Automatic library update paused after $checked titles; $updated updated, $failed failed. Waiting for device/network conditions.") } val message = "Checked $checked titles; $updated updated, $failed failed" + if (crashedTypes > 0) ", $crashedTypes libraries could not run." else "." PeriodicTaskOutcome( if (crashedTypes == DbItemType.entries.size) PeriodicTaskStatus.Failed else PeriodicTaskStatus.Completed, message, ) } suspend fun sync(): PeriodicTaskOutcome = execute(PeriodicTask.Sync) { val preference = database.syncPreferences().firstOrNull() if (preference?.syncOn != true || preference.authToken.isNullOrBlank()) { return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic sync is not configured.") } val result = sync.sync(preference.syncId ?: 1L, database.settings()) val details = buildList { add("${result.uploadedChanges} uploaded") add("${result.downloadedChanges} downloaded") if (result.settingsSynced) add("settings synced") }.joinToString(", ") PeriodicTaskOutcome( if (result.errors.isEmpty()) PeriodicTaskStatus.Completed else PeriodicTaskStatus.Failed, if (result.errors.isEmpty()) { "Sync complete: $details." } else { "Sync finished with ${result.errors.size} errors: $details." }, ) } suspend fun backup(): PeriodicTaskOutcome = execute(PeriodicTask.Backup) { val settings = database.settings() if (backup == null || backupFrequencyHours(settings.backupFrequency) <= 0) { return@execute PeriodicTaskOutcome(PeriodicTaskStatus.Skipped, "Automatic backup is disabled.") } val result = backup.createBackup(BackupOptions(compressionLevel = settings.backupCompressionLevel ?: 6)) PeriodicTaskOutcome(PeriodicTaskStatus.Completed, "Saved ${result.itemCount} items to ${result.fileName}.") } private suspend fun execute( task: PeriodicTask, block: suspend () -> PeriodicTaskOutcome, ): PeriodicTaskOutcome { val outcome = catchingNonCancellation { block() }.getOrElse { error -> PeriodicTaskOutcome( PeriodicTaskStatus.Failed, error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty().ifBlank { "Unknown error" } }, ) } if (outcome.status == PeriodicTaskStatus.Skipped || outcome.status == PeriodicTaskStatus.Deferred) return outcome val title = "${task.label} ${if (outcome.status == PeriodicTaskStatus.Completed) "complete" else "failed"}" if (outcome.status == PeriodicTaskStatus.Failed || task.notifiesSuccess) { notifications.notify( NotificationPayload( channel = task.channel, title = title, message = outcome.message.take(240), tag = task.tag, ), ) } val log = "$title: ${outcome.message}" if (outcome.status == PeriodicTaskStatus.Completed) AppLogger.info(log) else AppLogger.warn(log) return outcome } private enum class PeriodicTask( val label: String, val channel: NotificationChannel, val tag: String, val notifiesSuccess: Boolean = true, ) { Metadata("Metadata refresh", NotificationChannel.LibraryUpdates, "periodic.metadata"), Library("Library update", NotificationChannel.LibraryUpdates, "periodic.library"), Sync("Automatic sync", NotificationChannel.Sync, "periodic.sync"), // BackupService already posts "Backup created" for every successful backup. Backup("Automatic backup", NotificationChannel.Backup, "periodic.backup", notifiesSuccess = false), } }