package eu.friedcutlet.yokan.app import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.discord.DiscordRpcService import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl import eu.friedcutlet.yokan.services.http.isLoopbackProxy import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.runBlockingCompat enum class StartupStatus { Ok, Warning, Error, } data class StartupCheck( val name: String, val status: StartupStatus, val notes: String, ) data class PlatformBootstrapInput( val platformName: String, val initialDeepLink: String? = null, val appDataPath: String? = null, ) data class AppBootstrapReport( val platform: PlatformBootstrapInput, val checks: List, ) { val initialDeepLink: String? get() = platform.initialDeepLink val hasErrors: Boolean get() = checks.any { it.status == StartupStatus.Error } val summary: String get() = "${checks.count { it.status == StartupStatus.Ok }} ok, ${checks.count { it.status == StartupStatus.Warning }} warnings, ${checks.count { it.status == StartupStatus.Error }} errors" } /** Runs the startup checks listed in Settings → About and logs each one. */ internal fun runStartupChecks( input: PlatformBootstrapInput, services: YokanServices, discordRpc: DiscordRpcService, ): AppBootstrapReport { val checks = buildList { add(startupOk("Platform", "${input.platformName}${input.appDataPath?.let { " data=$it" }.orEmpty()}")) add(checkPersistence(services.database)) add(checkDownloadWorkers(services)) add(checkExtensionRuntime(services)) add(checkDeepLinks(input)) add(checkLogging()) add(checkDiscordRpc(input, services.database.settings(), discordRpc)) } checks.forEach { check -> when (check.status) { StartupStatus.Ok -> AppLogger.info("${check.name}: ${check.notes}") StartupStatus.Warning -> AppLogger.warn("${check.name}: ${check.notes}") StartupStatus.Error -> AppLogger.error("${check.name}: ${check.notes}") } } return AppBootstrapReport(input, checks) } expect fun platformBootstrapInput(): PlatformBootstrapInput expect fun installPlatformCrashLogger(onCrash: (Throwable) -> Unit) private fun checkPersistence(database: YokanDatabase): StartupCheck { val snapshot = database.snapshot() return startupOk( "Persistence", "loaded ${snapshot.mangas.size} titles, ${snapshot.chapters.size} chapters, ${snapshot.sources.size} sources", ) } private fun checkDownloadWorkers(services: YokanServices): StartupCheck = runCatching { runBlockingCompat { services.downloader.initialize(services.database.settings().concurrentDownloads) } startupOk("Download workers", "initialized pool size ${services.database.settings().concurrentDownloads}; recovered ${services.downloader.activeDownloads().size} active tasks") }.getOrElse { error -> startupError("Download workers", error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }) } private fun checkExtensionRuntime(services: YokanServices): StartupCheck { val sources = services.database.sources() val jsCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.JavaScript } val mihonCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.Mihon } val lnReaderCount = sources.count { it.sourceCodeLanguage == DbSourceCodeLanguage.LnReader } val proxy = services.database.settings().androidProxyServer ?: defaultMihonProxyUrl val usesLocalProxy = isLoopbackProxy(proxy) var serverNote = if (mihonCount > 0 && !usesLocalProxy) "; remote extension server configured" else "" var serverWarning: String? = null if (mihonCount > 0 && usesLocalProxy) { if (!services.extensionServer.isConfigured()) { serverWarning = "local extension server is not installed or bundled" } else { serverNote = "; local server startup scheduled" } } val runtimeFailures = sources.mapNotNull { source -> runCatching { services.extensionRuntimeFactory.create(source).dispose() } .exceptionOrNull() ?.let { error -> "${source.name}: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" } } val notes = "QuickJS=$jsCount, Mihon=$mihonCount via $proxy, LNReader=$lnReaderCount" val fullNotes = notes + serverNote return when { runtimeFailures.isNotEmpty() -> startupError("Extension runtime", runtimeFailures.joinToString()) serverWarning != null -> startupWarning("Extension runtime", "$fullNotes; $serverWarning") else -> startupOk("Extension runtime", fullNotes) } } private fun checkDeepLinks(input: PlatformBootstrapInput): StartupCheck = startupOk("Deep links", input.initialDeepLink?.let { "captured initial link $it" } ?: "initialized; no initial link") private fun checkLogging(): StartupCheck = startupOk("Logging", "in-memory startup and crash log buffer ready") private fun checkDiscordRpc(input: PlatformBootstrapInput, settings: DbSettings, service: DiscordRpcService): StartupCheck = when { !settings.enableDiscordRpc -> startupOk("Discord RPC", "disabled in settings") else -> { val status = service.initialize(settings) if (status.connected) startupOk("Discord RPC", status.message) else startupWarning("Discord RPC", status.message) } } private fun startupOk(name: String, notes: String) = StartupCheck(name, StartupStatus.Ok, notes) private fun startupWarning(name: String, notes: String) = StartupCheck(name, StartupStatus.Warning, notes) private fun startupError(name: String, notes: String) = StartupCheck(name, StartupStatus.Error, notes)