package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.database.DbRepo import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSourceCodeLanguage import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.logging.redactUrlForLog import eu.friedcutlet.yokan.util.nowMillis import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi private const val AnimePaheSourceId = 920451267L private const val AnimePaheUserAgentPreferenceKey = "user_agent" private const val AnimePaheCloudflareUserAgent = "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Mobile Safari/537.36" /** User agent for opening [source] in the in-app WebView; AnimePahe needs its Cloudflare-cleared one. */ fun DbSettings.webViewUserAgent(source: Source?): String { if (source == null) return userAgent if (source.id == AnimePaheSourceId || source.name.equals("AnimePahe", ignoreCase = true)) { return sourcePreferences.orEmpty() .firstOrNull { it.sourceId == source.id && it.key == AnimePaheUserAgentPreferenceKey } ?.value ?.takeIf { it.isNotBlank() } ?: AnimePaheCloudflareUserAgent } return userAgent } /** Installs, updates and removes extension sources, and syncs them with their repositories. */ class SourceInstallService( private val database: YokanDatabase, private val repository: YokanRepository, private val sourceCatalog: SourceCatalogService, private val runtimeFactory: ExtensionRuntimeFactory, private val settings: SettingsStore, private val chapterPages: ChapterPageResolver, ) { /** * Upserts [repo]'s sources, flags updates, installs them when [autoUpdate] is on and the source * is added, and marks sources the repository dropped as obsolete. */ suspend fun refreshRepository( itemType: ItemType, repo: DbRepo, autoUpdate: Boolean = settings.db.value.autoExtensionsUpdates, ): SourceRepositoryRefreshResult { val jsonUrl = repo.jsonUrl?.trim().orEmpty() if (jsonUrl.isBlank()) return SourceRepositoryRefreshResult(0, 0, 0, 0, 0) val dbType = itemType.toDb() val now = nowMillis() val remoteSources = sourceCatalog.fetchSources(jsonUrl, dbType) val existingSources = database.sources(dbType).filter { it.itemType == dbType && !it.isLocal } val touchedIds = mutableSetOf() var added = 0 var updateAvailable = 0 var updated = 0 remoteSources.forEach { remote -> val existing = database.source(remote.id) ?: existingSources.firstOrNull { candidate -> candidate.name == remote.name && candidate.lang == remote.lang && candidate.baseUrl == remote.baseUrl && candidate.itemType == dbType } val remoteWithRepo = remote.copy( itemType = dbType, repo = repo, versionLast = remote.version, isObsolete = false, updatedAt = now, ) if (existing == null) { val inserted = database.upsertSource( remoteWithRepo.copy( isAdded = false, isActive = true, isPinned = false, ), ) touchedIds += inserted.id added += 1 return@forEach } touchedIds += existing.id val hasUpdate = VersionComparison.compare(existing.version, remote.version) < 0 if (hasUpdate) updateAvailable += 1 val shouldInstallUpdate = hasUpdate && autoUpdate && existing.isAdded val downloadedSourceCode = if (shouldInstallUpdate) fetchPayload(remoteWithRepo) else null if (downloadedSourceCode != null) { updated += 1 chapterPages.invalidateSource(existing.id) } val metadata = if (downloadedSourceCode != null && remoteWithRepo.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) { fetchMihonMetadata(remoteWithRepo.copy(sourceCode = downloadedSourceCode, isAdded = true)) } else { null } database.upsertSource( existing.copy( name = remote.name, baseUrl = remote.baseUrl, lang = remote.lang, isNsfw = remote.isNsfw, sourceCode = downloadedSourceCode ?: existing.sourceCode, sourceCodeUrl = remote.sourceCodeUrl, typeSource = remote.typeSource, iconUrl = remote.iconUrl, isFullData = existing.isFullData || downloadedSourceCode != null, hasCloudflare = remote.hasCloudflare, dateFormat = remote.dateFormat, dateFormatLocale = remote.dateFormatLocale, apiUrl = remote.apiUrl, version = if (downloadedSourceCode != null) remote.version else existing.version, versionLast = remote.version, headers = metadata?.headers ?: existing.headers.ifBlank { remote.headers }, supportLatest = metadata?.supportLatest ?: remote.supportLatest ?: existing.supportLatest, filterList = metadata?.filterList ?: existing.filterList ?: remote.filterList, preferenceList = metadata?.preferenceList ?: existing.preferenceList ?: remote.preferenceList, itemType = dbType, appMinVerReq = remote.appMinVerReq, additionalParams = remote.additionalParams, isLocal = false, isObsolete = false, sourceCodeLanguage = remote.sourceCodeLanguage, notes = remote.notes, repo = repo, updatedAt = now, ), ) } var obsolete = 0 database.sources(dbType) .filter { source -> !source.isLocal && source.itemType == dbType && source.repo?.jsonUrl == jsonUrl && source.id !in touchedIds } .forEach { source -> if (!source.isObsolete) { obsolete += 1 database.upsertSource(source.copy(isObsolete = true, updatedAt = now)) } } AppLogger.info( "[extensions] refreshed ${redactUrlForLog(jsonUrl)} ($itemType): ${remoteSources.size} sources, $added added, " + "$updateAvailable with updates, $updated updated, $obsolete obsolete", ) return SourceRepositoryRefreshResult( fetched = remoteSources.size, added = added, updateAvailable = updateAvailable, updated = updated, obsolete = obsolete, ) } /** Refreshes every repository of every item type; one failing repository does not stop the rest. */ suspend fun refreshAllRepositories() { ItemType.entries.forEach { type -> repository.repositories(type).forEach { repo -> catchingNonCancellation { refreshRepository(type, repo) } .onFailure { AppLogger.warn("[extensions] refreshing ${redactUrlForLog(repo.jsonUrl.orEmpty())} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } } } } /** Downloads the source's latest payload and marks it installed; false when no code is available. */ suspend fun installOrUpdate(sourceId: Long): Boolean { val source = database.source(sourceId) ?: return false val downloadedSourceCode = fetchPayload(source) if (source.sourceCodeUrl.isNotBlank() && downloadedSourceCode == null && source.sourceCode.isBlank()) { AppLogger.warn("[extensions] install ${source.name} failed: no source code available") return false } val sourceCode = downloadedSourceCode ?: source.sourceCode val nextVersion = source.versionLast.takeIf { it.isNotBlank() } ?: source.version val metadata = if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) { fetchMihonMetadata(source.copy(sourceCode = sourceCode, isAdded = true)) } else { null } chapterPages.invalidateSource(sourceId) database.upsertSource( source.copy( isAdded = true, isActive = true, isFullData = sourceCode.isNotBlank(), isObsolete = false, sourceCode = sourceCode, version = nextVersion, versionLast = nextVersion, headers = metadata?.headers ?: source.headers, supportLatest = metadata?.supportLatest ?: source.supportLatest, filterList = metadata?.filterList ?: source.filterList, preferenceList = metadata?.preferenceList ?: source.preferenceList, updatedAt = nowMillis(), ), ) AppLogger.info("[extensions] installed ${source.name} ${source.version} -> $nextVersion") return true } /** * Full uninstall: clears the payload, un-adds and un-pins the source and drops its stored * preferences. An obsolete source (dropped by its repository) is deleted outright; returns true * in that case. */ fun uninstall(sourceId: Long): Boolean { val dbSource = database.source(sourceId) ?: return false val obsolete = dbSource.isObsolete runtimeFactory.evict(sourceId) chapterPages.invalidateSource(sourceId) if (obsolete) { database.removeSource(sourceId) } else { database.upsertSource( dbSource.copy( sourceCode = "", isAdded = false, isPinned = false, isFullData = false, updatedAt = nowMillis(), ), ) } settings.updateDb { current -> current.copy(sourcePreferences = current.sourcePreferences.orEmpty().filterNot { it.sourceId == sourceId }) } AppLogger.info("[extensions] uninstalled ${dbSource.name}${if (obsolete) " (obsolete, removed)" else ""}") return obsolete } fun remove(sourceId: Long) { repository.removeSource(sourceId) AppLogger.info("[extensions] removed source $sourceId") runtimeFactory.evict(sourceId) chapterPages.invalidateSource(sourceId) } /** Drops every persisted cookie scoped to the source's base host. */ fun deleteCookies(source: Source) { val host = source.baseUrl.substringAfter("//").substringBefore('/').lowercase() if (host.isBlank()) return settings.updateDb { current -> current.copy( cookiesList = current.cookiesList.orEmpty() .filterNot { (it.host ?: "").lowercase().contains(host) }, ) } } private suspend fun fetchPayload(source: DbSource): String? = catchingNonCancellation { encodePayload(source, sourceCatalog.fetchSourcePayload(source) ?: return null) }.onFailure { AppLogger.warn("[extensions] fetching ${source.name} payload failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } .getOrNull() // The source is not installed yet, so it runs on a runtime for this exact DbSource. private suspend fun fetchMihonMetadata(source: DbSource): MihonSourceMetadata? = catchingNonCancellation { runtimeFactory.withRuntime(source) { runtime -> (runtime as? MihonExtensionRuntimeService)?.fetchMetadata() } }.onFailure { AppLogger.warn("[extensions] fetching ${source.name} Mihon metadata failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } .getOrNull() } @OptIn(ExperimentalEncodingApi::class) private fun encodePayload(source: DbSource, bytes: ByteArray): String = if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) Base64.encode(bytes) else bytes.decodeToString()