package eu.friedcutlet.yokan.app import eu.friedcutlet.yokan.app.profiles.ProfileBackgroundWork import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult import eu.friedcutlet.yokan.services.download.DownloadService import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.services.applock.AppLockController import eu.friedcutlet.yokan.services.applock.createPlatformAppLockController import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.discord.DiscordRpcService import eu.friedcutlet.yokan.services.discord.createPlatformDiscordRpcService import eu.friedcutlet.yokan.services.extensions.mihon.ExtensionServerRuntimeMode import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl import eu.friedcutlet.yokan.services.extensions.mihon.extensionServerPortFromUrl import eu.friedcutlet.yokan.services.http.isLoopbackProxy import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.CrashReportStore import eu.friedcutlet.yokan.services.scheduling.BackgroundScheduler import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskOutcome import eu.friedcutlet.yokan.services.scheduling.PeriodicTaskRunner import eu.friedcutlet.yokan.services.scheduling.backupFrequencyHours import eu.friedcutlet.yokan.services.scheduling.periodicMinutes import eu.friedcutlet.yokan.ui.screens.reader.ReaderSystemUiController import eu.friedcutlet.yokan.ui.screens.reader.createReaderSystemUiController import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.launch import kotlin.concurrent.Volatile /** * Process-wide facade over the currently published session. Mutable dependencies capture that owner; * device resources and profile commands survive foreground session retirement. */ object YokanRuntime { internal val profileUi = eu.friedcutlet.yokan.app.profiles.ProfileUiLifetime() internal val profileCoordinator: eu.friedcutlet.yokan.app.profiles.ProfileCoordinator by lazy { eu.friedcutlet.yokan.app.profiles.ProfileCoordinator( profiles, eu.friedcutlet.yokan.app.profiles.createPlatformProfileSession(ProfileId.Default, profiles.syncLeases(ProfileId.Default), ::reschedulePeriodicTasks), openSession = { eu.friedcutlet.yokan.app.profiles.openPlatformProfileSession(it, profiles.syncLeases(it), ::reschedulePeriodicTasks) }, prepare = { owner -> owner.attachLogging() reschedulePeriodicTasks(owner) if (foregroundStarted) startForeground(owner) }, detach = profileUi::detach, deleteStorage = { id -> eu.friedcutlet.yokan.app.profiles.cancelProfileBackgroundWork(id) val exports = profiles.refresh().profiles.single { it.id == id }.exportedBackups eu.friedcutlet.yokan.app.profiles.deleteProfileStorage(id, exports) scheduleLock.withLock { lastSchedules.remove(id) } }, ) } internal val activeSession: eu.friedcutlet.yokan.app.profiles.ProfileSession get() = profileCoordinator.currentSession val database get() = activeSession.database val localFiles get() = activeSession.localFiles val notifications get() = activeSession.notifications val services get() = activeSession.services internal val together get() = activeSession.together val repository get() = activeSession.repository val periodicTasks get() = activeSession.periodicTasks val settings get() = activeSession.settings val libraryIndex get() = activeSession.libraryIndex val libraryUpdates get() = activeSession.libraryUpdates val localLibrary get() = activeSession.localLibrary val colorizationQueue get() = activeSession.colorizationQueue val migration get() = activeSession.migration val chapterDownloads get() = activeSession.chapterDownloads val sourceInstall get() = activeSession.sourceInstall val discordRpc: DiscordRpcService by lazy { createPlatformDiscordRpcService() } val readerSystemUi: ReaderSystemUiController by lazy { createReaderSystemUiController() } val profiles by lazy { eu.friedcutlet.yokan.app.profiles.createPlatformProfileRegistry() } private val backgroundWork by lazy { ProfileBackgroundWork(profiles, supported = { true }, sessions = profileCoordinator) } suspend fun runBackgroundTask( owner: String?, allowLegacyDefault: Boolean = false, task: suspend PeriodicTaskRunner.() -> PeriodicTaskOutcome, ): ProfileWorkResult = backgroundWork.run(owner, allowLegacyDefault) { session -> session.periodicTasks.task() } suspend fun runBackgroundDownloads( owner: String?, allowLegacyDefault: Boolean = false, task: suspend DownloadService.() -> Unit, ): ProfileWorkResult = backgroundWork.run(owner, allowLegacyDefault) { session -> session.services.downloader.task() } val appIcons by lazy { eu.friedcutlet.yokan.services.appicons.createPlatformAppIconService() } val appLock: AppLockController by lazy { createPlatformAppLockController() } // Serializes [bootstrap]: App.kt, desktop main, iOS BGTasks and Android workers can all call it // concurrently. private val bootstrapLock = PlatformLock() @Volatile private var report: AppBootstrapReport? = null private var foregroundStarted = false private val scheduleLock = PlatformLock() private val lastSchedules = mutableMapOf() /** * Runs the startup checks once per process; later calls return the same report. * * [background] callers (OS workers, BGTasks) only need services: they skip the embedded * extension server and the in-app [ForegroundScheduler], which start on the first foreground * call instead. OS task rescheduling runs in both modes because iOS BGTasks must re-submit * themselves after a cold background launch. */ fun bootstrap( input: PlatformBootstrapInput = platformBootstrapInput(), background: Boolean = false, ): AppBootstrapReport = bootstrapLock.withLock { val current = report ?: startup(input).also { started -> services.scope.launch { catchingNonCancellation { profiles.refresh() } .onFailure { AppLogger.warn("Profile registry unavailable; existing Default storage remains available") } } report = started runCatching { reschedulePeriodicTasks() } .onFailure { AppLogger.warn("Could not schedule periodic tasks: ${it.message.orEmpty()}") } } if (!background && !foregroundStarted) { foregroundStarted = true startForeground(activeSession) } current } fun bootstrapReport(): AppBootstrapReport = report ?: bootstrap() /** * No-op until [bootstrap] has run, and when the settings-derived schedule is unchanged since * the last call; [BackgroundScheduler.schedule] itself is idempotent. */ fun reschedulePeriodicTasks() = reschedulePeriodicTasks(activeSession) private fun reschedulePeriodicTasks(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) { if (owner.status.value != eu.friedcutlet.yokan.app.profiles.ProfileSessionStatus.Open) return val db = owner.database.settings() val syncPreference = owner.database.syncPreferences().firstOrNull() val syncSeconds = syncPreference ?.takeIf { it.syncOn && !it.authToken.isNullOrBlank() } ?.autoSyncFrequency ?: 0 val schedule = PeriodicSchedule( metadataRefreshMinutes = periodicMinutes(if (db.metadataServerEnabled) db.metadataRefreshFrequencySeconds else 0), libraryUpdateMinutes = periodicMinutes(db.libraryUpdateFrequencySeconds), libraryUpdateDailyAtMinutes = db.libraryUpdateDailyAtMinutes, autoSyncMinutes = periodicMinutes(syncSeconds), autoBackupHours = backupFrequencyHours(db.backupFrequency), requireUnmetered = db.downloadOnlyOnWifi, libraryConstraints = db.features.library.deviceConstraints, ) scheduleLock.withLock { if (schedule == lastSchedules[owner.id]) return@withLock owner.backgroundScheduler.schedule( metadataRefreshMinutes = schedule.metadataRefreshMinutes, libraryUpdateMinutes = schedule.libraryUpdateMinutes, libraryUpdateDailyAtMinutes = schedule.libraryUpdateDailyAtMinutes, autoSyncMinutes = schedule.autoSyncMinutes, autoBackupHours = schedule.autoBackupHours, requireUnmetered = schedule.requireUnmetered, libraryConstraints = schedule.libraryConstraints, ) lastSchedules[owner.id] = schedule } } private fun startup(input: PlatformBootstrapInput): AppBootstrapReport { val crashFiles = eu.friedcutlet.yokan.services.files.createPlatformLocalFileService(ProfileId.Default) installPlatformCrashLogger { throwable -> // Broken pipes are routine when a client (player, WebView resource // fetch, etc.) disconnects mid-write — drop them to debug so they // don't masquerade as crashes. val name = throwable::class.simpleName.orEmpty() val message = throwable.message.orEmpty() val isBrokenPipe = name == "SocketException" && message.contains("broken pipe", ignoreCase = true) if (isBrokenPipe) { AppLogger.warn("Suppressed $name: $message") } else { CrashReportStore.record(crashFiles, throwable) AppLogger.error("Unhandled $name: ${CrashReportStore.redact(message)}") } } activeSession.attachLogging() return runStartupChecks(input, services, discordRpc) } private fun startForeground(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) { scheduleExtensionServerStart(owner) if (owner.colorizationQueue.supported) owner.colorizationQueue.start() owner.foregroundScheduler.start() owner.syncTriggers.onTrigger(eu.friedcutlet.yokan.services.sync.SyncTriggerKind.AppStart) } private fun scheduleExtensionServerStart(owner: eu.friedcutlet.yokan.app.profiles.ProfileSession) { val services = owner.services val database = owner.database if (services.extensionServer.mode == ExtensionServerRuntimeMode.IosSideloadedJvm) return if (database.sources().none { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon }) return val proxy = database.settings().androidProxyServer ?: defaultMihonProxyUrl if (!isLoopbackProxy(proxy) || !services.extensionServer.isConfigured()) return services.scope.launch { catchingNonCancellation { services.extensionServer.startIfConfigured(extensionServerPortFromUrl(proxy)) }.onSuccess { status -> AppLogger.info( "Extension runtime: local server ${status?.phase?.name?.lowercase() ?: "not configured"}", ) }.onFailure { error -> AppLogger.warn( "Extension runtime: ${error.message.orEmpty().ifBlank { "local extension server failed to start" }}", ) } } } } /** The arguments of [BackgroundScheduler.schedule], compared to skip redundant rescheduling. */ private data class PeriodicSchedule( val metadataRefreshMinutes: Long, val libraryUpdateMinutes: Long, val libraryUpdateDailyAtMinutes: Int, val autoSyncMinutes: Long, val autoBackupHours: Long, val requireUnmetered: Boolean, val libraryConstraints: eu.friedcutlet.yokan.database.DbAutomaticUpdateConstraints, )