SourceInstallService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceInstallService.kt
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.data.SettingsStore4import eu.friedcutlet.yokan.data.YokanRepository5import eu.friedcutlet.yokan.data.toDb6import eu.friedcutlet.yokan.database.DbRepo7import eu.friedcutlet.yokan.database.DbSettings8import eu.friedcutlet.yokan.database.DbSource9import eu.friedcutlet.yokan.database.DbSourceCodeLanguage10import eu.friedcutlet.yokan.database.YokanDatabase11import eu.friedcutlet.yokan.domain.ItemType12import eu.friedcutlet.yokan.domain.Source13import eu.friedcutlet.yokan.services.catchingNonCancellation14import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService15import eu.friedcutlet.yokan.services.logging.AppLogger16import eu.friedcutlet.yokan.services.logging.redactUrlForLog17import eu.friedcutlet.yokan.util.nowMillis18import kotlin.io.encoding.Base6419import kotlin.io.encoding.ExperimentalEncodingApi2021private const val AnimePaheSourceId = 920451267L22private const val AnimePaheUserAgentPreferenceKey = "user_agent"23private const val AnimePaheCloudflareUserAgent =24 "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Mobile Safari/537.36"2526/** User agent for opening [source] in the in-app WebView; AnimePahe needs its Cloudflare-cleared one. */27fun DbSettings.webViewUserAgent(source: Source?): String {28 if (source == null) return userAgent29 if (source.id == AnimePaheSourceId || source.name.equals("AnimePahe", ignoreCase = true)) {30 return sourcePreferences.orEmpty()31 .firstOrNull { it.sourceId == source.id && it.key == AnimePaheUserAgentPreferenceKey }32 ?.value33 ?.takeIf { it.isNotBlank() }34 ?: AnimePaheCloudflareUserAgent35 }36 return userAgent37}3839/** Installs, updates and removes extension sources, and syncs them with their repositories. */40class SourceInstallService(41 private val database: YokanDatabase,42 private val repository: YokanRepository,43 private val sourceCatalog: SourceCatalogService,44 private val runtimeFactory: ExtensionRuntimeFactory,45 private val settings: SettingsStore,46 private val chapterPages: ChapterPageResolver,47) {48 /**49 * Upserts [repo]'s sources, flags updates, installs them when [autoUpdate] is on and the source50 * is added, and marks sources the repository dropped as obsolete.51 */52 suspend fun refreshRepository(53 itemType: ItemType,54 repo: DbRepo,55 autoUpdate: Boolean = settings.db.value.autoExtensionsUpdates,56 ): SourceRepositoryRefreshResult {57 val jsonUrl = repo.jsonUrl?.trim().orEmpty()58 if (jsonUrl.isBlank()) return SourceRepositoryRefreshResult(0, 0, 0, 0, 0)59 val dbType = itemType.toDb()60 val now = nowMillis()61 val remoteSources = sourceCatalog.fetchSources(jsonUrl, dbType)62 val existingSources = database.sources(dbType).filter { it.itemType == dbType && !it.isLocal }63 val touchedIds = mutableSetOf<Long>()64 var added = 065 var updateAvailable = 066 var updated = 06768 remoteSources.forEach { remote ->69 val existing = database.source(remote.id)70 ?: existingSources.firstOrNull { candidate ->71 candidate.name == remote.name &&72 candidate.lang == remote.lang &&73 candidate.baseUrl == remote.baseUrl &&74 candidate.itemType == dbType75 }76 val remoteWithRepo = remote.copy(77 itemType = dbType,78 repo = repo,79 versionLast = remote.version,80 isObsolete = false,81 updatedAt = now,82 )83 if (existing == null) {84 val inserted = database.upsertSource(85 remoteWithRepo.copy(86 isAdded = false,87 isActive = true,88 isPinned = false,89 ),90 )91 touchedIds += inserted.id92 added += 193 return@forEach94 }9596 touchedIds += existing.id97 val hasUpdate = VersionComparison.compare(existing.version, remote.version) < 098 if (hasUpdate) updateAvailable += 199 val shouldInstallUpdate = hasUpdate && autoUpdate && existing.isAdded100 val downloadedSourceCode = if (shouldInstallUpdate) fetchPayload(remoteWithRepo) else null101 if (downloadedSourceCode != null) {102 updated += 1103 chapterPages.invalidateSource(existing.id)104 }105 val metadata = if (downloadedSourceCode != null && remoteWithRepo.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) {106 fetchMihonMetadata(remoteWithRepo.copy(sourceCode = downloadedSourceCode, isAdded = true))107 } else {108 null109 }110111 database.upsertSource(112 existing.copy(113 name = remote.name,114 baseUrl = remote.baseUrl,115 lang = remote.lang,116 isNsfw = remote.isNsfw,117 sourceCode = downloadedSourceCode ?: existing.sourceCode,118 sourceCodeUrl = remote.sourceCodeUrl,119 typeSource = remote.typeSource,120 iconUrl = remote.iconUrl,121 isFullData = existing.isFullData || downloadedSourceCode != null,122 hasCloudflare = remote.hasCloudflare,123 dateFormat = remote.dateFormat,124 dateFormatLocale = remote.dateFormatLocale,125 apiUrl = remote.apiUrl,126 version = if (downloadedSourceCode != null) remote.version else existing.version,127 versionLast = remote.version,128 headers = metadata?.headers ?: existing.headers.ifBlank { remote.headers },129 supportLatest = metadata?.supportLatest ?: remote.supportLatest ?: existing.supportLatest,130 filterList = metadata?.filterList ?: existing.filterList ?: remote.filterList,131 preferenceList = metadata?.preferenceList ?: existing.preferenceList ?: remote.preferenceList,132 itemType = dbType,133 appMinVerReq = remote.appMinVerReq,134 additionalParams = remote.additionalParams,135 isLocal = false,136 isObsolete = false,137 sourceCodeLanguage = remote.sourceCodeLanguage,138 notes = remote.notes,139 repo = repo,140 updatedAt = now,141 ),142 )143 }144145 var obsolete = 0146 database.sources(dbType)147 .filter { source ->148 !source.isLocal &&149 source.itemType == dbType &&150 source.repo?.jsonUrl == jsonUrl &&151 source.id !in touchedIds152 }153 .forEach { source ->154 if (!source.isObsolete) {155 obsolete += 1156 database.upsertSource(source.copy(isObsolete = true, updatedAt = now))157 }158 }159160 AppLogger.info(161 "[extensions] refreshed ${redactUrlForLog(jsonUrl)} ($itemType): ${remoteSources.size} sources, $added added, " +162 "$updateAvailable with updates, $updated updated, $obsolete obsolete",163 )164 return SourceRepositoryRefreshResult(165 fetched = remoteSources.size,166 added = added,167 updateAvailable = updateAvailable,168 updated = updated,169 obsolete = obsolete,170 )171 }172173 /** Refreshes every repository of every item type; one failing repository does not stop the rest. */174 suspend fun refreshAllRepositories() {175 ItemType.entries.forEach { type ->176 repository.repositories(type).forEach { repo ->177 catchingNonCancellation { refreshRepository(type, repo) }178 .onFailure { AppLogger.warn("[extensions] refreshing ${redactUrlForLog(repo.jsonUrl.orEmpty())} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }179 }180 }181 }182183 /** Downloads the source's latest payload and marks it installed; false when no code is available. */184 suspend fun installOrUpdate(sourceId: Long): Boolean {185 val source = database.source(sourceId) ?: return false186 val downloadedSourceCode = fetchPayload(source)187 if (source.sourceCodeUrl.isNotBlank() && downloadedSourceCode == null && source.sourceCode.isBlank()) {188 AppLogger.warn("[extensions] install ${source.name} failed: no source code available")189 return false190 }191 val sourceCode = downloadedSourceCode ?: source.sourceCode192 val nextVersion = source.versionLast.takeIf { it.isNotBlank() } ?: source.version193 val metadata = if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) {194 fetchMihonMetadata(source.copy(sourceCode = sourceCode, isAdded = true))195 } else {196 null197 }198 chapterPages.invalidateSource(sourceId)199 database.upsertSource(200 source.copy(201 isAdded = true,202 isActive = true,203 isFullData = sourceCode.isNotBlank(),204 isObsolete = false,205 sourceCode = sourceCode,206 version = nextVersion,207 versionLast = nextVersion,208 headers = metadata?.headers ?: source.headers,209 supportLatest = metadata?.supportLatest ?: source.supportLatest,210 filterList = metadata?.filterList ?: source.filterList,211 preferenceList = metadata?.preferenceList ?: source.preferenceList,212 updatedAt = nowMillis(),213 ),214 )215 AppLogger.info("[extensions] installed ${source.name} ${source.version} -> $nextVersion")216 return true217 }218219 /**220 * Full uninstall: clears the payload, un-adds and un-pins the source and drops its stored221 * preferences. An obsolete source (dropped by its repository) is deleted outright; returns true222 * in that case.223 */224 fun uninstall(sourceId: Long): Boolean {225 val dbSource = database.source(sourceId) ?: return false226 val obsolete = dbSource.isObsolete227 runtimeFactory.evict(sourceId)228 chapterPages.invalidateSource(sourceId)229 if (obsolete) {230 database.removeSource(sourceId)231 } else {232 database.upsertSource(233 dbSource.copy(234 sourceCode = "",235 isAdded = false,236 isPinned = false,237 isFullData = false,238 updatedAt = nowMillis(),239 ),240 )241 }242 settings.updateDb { current ->243 current.copy(sourcePreferences = current.sourcePreferences.orEmpty().filterNot { it.sourceId == sourceId })244 }245 AppLogger.info("[extensions] uninstalled ${dbSource.name}${if (obsolete) " (obsolete, removed)" else ""}")246 return obsolete247 }248249 fun remove(sourceId: Long) {250 repository.removeSource(sourceId)251 AppLogger.info("[extensions] removed source $sourceId")252 runtimeFactory.evict(sourceId)253 chapterPages.invalidateSource(sourceId)254 }255256 /** Drops every persisted cookie scoped to the source's base host. */257 fun deleteCookies(source: Source) {258 val host = source.baseUrl.substringAfter("//").substringBefore('/').lowercase()259 if (host.isBlank()) return260 settings.updateDb { current ->261 current.copy(262 cookiesList = current.cookiesList.orEmpty()263 .filterNot { (it.host ?: "").lowercase().contains(host) },264 )265 }266 }267268 private suspend fun fetchPayload(source: DbSource): String? = catchingNonCancellation {269 encodePayload(source, sourceCatalog.fetchSourcePayload(source) ?: return null)270 }.onFailure { AppLogger.warn("[extensions] fetching ${source.name} payload failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }271 .getOrNull()272273 // The source is not installed yet, so it runs on a runtime for this exact DbSource.274 private suspend fun fetchMihonMetadata(source: DbSource): MihonSourceMetadata? = catchingNonCancellation {275 runtimeFactory.withRuntime(source) { runtime ->276 (runtime as? MihonExtensionRuntimeService)?.fetchMetadata()277 }278 }.onFailure { AppLogger.warn("[extensions] fetching ${source.name} Mihon metadata failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }279 .getOrNull()280}281282@OptIn(ExperimentalEncodingApi::class)283private fun encodePayload(source: DbSource, bytes: ByteArray): String =284 if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) Base64.encode(bytes) else bytes.decodeToString()285