ChapterPageResolver.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ChapterPageResolver.kt
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.data.YokanRepository4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.DbChapterPageUrls6import eu.friedcutlet.yokan.database.DbPageUrl7import eu.friedcutlet.yokan.database.YokanDatabase8import eu.friedcutlet.yokan.domain.Chapter9import eu.friedcutlet.yokan.util.nowMillis10import kotlinx.coroutines.currentCoroutineContext11import kotlinx.coroutines.ensureActive1213/** How long a saved page list is served without asking the source again. */14// ponytail: one TTL for every source; make it per-source if a CDN signs page URLs for less.15const val PAGE_LIST_TTL_MS: Long = 12 * 60 * 60 * 1000L1617/**18 * Resolves a source chapter's page URLs for the reader and downloads: the saved list while it is19 * fresh, otherwise the extension's, saved back. Local-archive chapters never come here; their20 * callers list the files themselves.21 */22class ChapterPageResolver(23 private val repository: YokanRepository,24 private val database: YokanDatabase,25 private val runtimeFactory: ExtensionRuntimeFactory,26 private val clock: () -> Long = ::nowMillis,27) {28 /**29 * Saved list when it is still fresh (fetched within [PAGE_LIST_TTL_MS] by the same source version),30 * otherwise fetched from the extension with the source's headers merged in and saved back.31 * [forceRefresh] skips the saved list. Throws on fetch failure (callers wrap with catchingNonCancellation).32 */33 suspend fun pages(chapter: DbChapter, sourceId: Long?, forceRefresh: Boolean = false): List<DbPageUrl> =34 pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback = null)3536 /**37 * Reader overload of [pages]. With [onFallback] a failing runtime is reported and the offline38 * [DatabaseFallbackRuntimeService] answers instead, as in [withSourceRuntime]; its answer is never saved.39 */40 suspend fun pages(41 chapter: Chapter,42 sourceId: Long?,43 forceRefresh: Boolean = false,44 onFallback: ((Throwable) -> Unit)? = null,45 ensureRequestCurrent: () -> Unit = {},46 ): List<DbPageUrl> = pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback, ensureRequestCurrent)4748 /** The saved list of [chapterId] when it is fresh for [sourceId]'s installed version, else empty. */49 fun savedPages(chapterId: Long, sourceId: Long?): List<DbPageUrl> {50 val saved = database.pageCache(chapterId).firstOrNull() ?: return emptyList()51 val version = sourceId?.let(database::source)?.version52 return if (saved.isFresh(sourceId, version, clock())) repository.pageUrls(chapterId) else emptyList()53 }5455 fun invalidate(chapterId: Long) = database.removePageCache(listOf(chapterId))5657 /** Drops every saved list of [sourceId]'s chapters, e.g. after the extension was updated or removed. */58 fun invalidateSource(sourceId: Long) {59 // Lists saved before they recorded their source are matched through their title.60 val titleIds = database.mangas().filter { it.sourceId == sourceId }.mapTo(HashSet()) { it.id }61 val chapterIds = database.pageCache().mapNotNull { saved ->62 saved.chapterId?.takeIf { id ->63 saved.sourceId == sourceId || (saved.sourceId == null && database.chapter(id)?.mangaId in titleIds)64 }65 }66 database.removePageCache(chapterIds)67 }6869 private suspend fun pages(70 chapterId: Long,71 chapterUrl: String,72 sourceId: Long?,73 forceRefresh: Boolean,74 onFallback: ((Throwable) -> Unit)?,75 ensureRequestCurrent: () -> Unit = {},76 ): List<DbPageUrl> {77 val callContext = currentCoroutineContext()78 fun ensureCurrent() {79 callContext.ensureActive()80 ensureRequestCurrent()81 }82 ensureCurrent()83 if (!forceRefresh) savedPages(chapterId, sourceId).takeIf { it.isNotEmpty() }?.let {84 ensureCurrent()85 return it86 }87 val id = sourceId ?: error("Source is unavailable")88 var live = true89 val pages = runtimeFactory.withSourceRuntime(database, id, onFallback?.let { report ->90 { failure -> ensureCurrent(); report(failure) }91 }) { runtime ->92 ensureCurrent()93 live = runtime !is DatabaseFallbackRuntimeService94 val headers = runtime.headers()95 ensureCurrent()96 val urls = runtime.pageList(chapterUrl)97 ensureCurrent()98 mergeSourcePageHeaders(headers, urls)99 }100 ensureCurrent()101 if (live && pages.isNotEmpty()) {102 database.batch {103 ensureCurrent()104 if (database.chapter(chapterId) != null) {105 repository.cachePageUrls(chapterId, chapterUrl, pages, database.source(id), fetchedAt = clock())106 }107 }108 }109 return pages110 }111}112113/** Fresh = fetched less than [PAGE_LIST_TTL_MS] before [now] by [sourceVersion] of [sourceId]; lists from before timestamps are stale. */114internal fun DbChapterPageUrls.isFresh(sourceId: Long?, sourceVersion: String?, now: Long): Boolean {115 val fetched = fetchedAt ?: return false116 return now - fetched in 0 until PAGE_LIST_TTL_MS && this.sourceId == sourceId && this.sourceVersion == sourceVersion117}118119/** Source headers under each page's own; a page header replaces a source header of any case. */120internal fun mergeSourcePageHeaders(121 sourceHeaders: Map<String, String>,122 pages: List<DbPageUrl>,123): List<DbPageUrl> = pages.map { page ->124 val merged = linkedMapOf<String, String>()125 fun append(headers: Map<String, String>) {126 headers.forEach { (name, value) ->127 merged.keys.firstOrNull { it.equals(name, ignoreCase = true) }?.let(merged::remove)128 merged[name] = value129 }130 }131 append(sourceHeaders)132 append(page.headers.orEmpty())133 page.copy(headers = merged.ifEmpty { null })134}135