package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterPageUrls import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive /** How long a saved page list is served without asking the source again. */ // ponytail: one TTL for every source; make it per-source if a CDN signs page URLs for less. const val PAGE_LIST_TTL_MS: Long = 12 * 60 * 60 * 1000L /** * Resolves a source chapter's page URLs for the reader and downloads: the saved list while it is * fresh, otherwise the extension's, saved back. Local-archive chapters never come here; their * callers list the files themselves. */ class ChapterPageResolver( private val repository: YokanRepository, private val database: YokanDatabase, private val runtimeFactory: ExtensionRuntimeFactory, private val clock: () -> Long = ::nowMillis, ) { /** * Saved list when it is still fresh (fetched within [PAGE_LIST_TTL_MS] by the same source version), * otherwise fetched from the extension with the source's headers merged in and saved back. * [forceRefresh] skips the saved list. Throws on fetch failure (callers wrap with catchingNonCancellation). */ suspend fun pages(chapter: DbChapter, sourceId: Long?, forceRefresh: Boolean = false): List = pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback = null) /** * Reader overload of [pages]. With [onFallback] a failing runtime is reported and the offline * [DatabaseFallbackRuntimeService] answers instead, as in [withSourceRuntime]; its answer is never saved. */ suspend fun pages( chapter: Chapter, sourceId: Long?, forceRefresh: Boolean = false, onFallback: ((Throwable) -> Unit)? = null, ensureRequestCurrent: () -> Unit = {}, ): List = pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback, ensureRequestCurrent) /** The saved list of [chapterId] when it is fresh for [sourceId]'s installed version, else empty. */ fun savedPages(chapterId: Long, sourceId: Long?): List { val saved = database.pageCache(chapterId).firstOrNull() ?: return emptyList() val version = sourceId?.let(database::source)?.version return if (saved.isFresh(sourceId, version, clock())) repository.pageUrls(chapterId) else emptyList() } fun invalidate(chapterId: Long) = database.removePageCache(listOf(chapterId)) /** Drops every saved list of [sourceId]'s chapters, e.g. after the extension was updated or removed. */ fun invalidateSource(sourceId: Long) { // Lists saved before they recorded their source are matched through their title. val titleIds = database.mangas().filter { it.sourceId == sourceId }.mapTo(HashSet()) { it.id } val chapterIds = database.pageCache().mapNotNull { saved -> saved.chapterId?.takeIf { id -> saved.sourceId == sourceId || (saved.sourceId == null && database.chapter(id)?.mangaId in titleIds) } } database.removePageCache(chapterIds) } private suspend fun pages( chapterId: Long, chapterUrl: String, sourceId: Long?, forceRefresh: Boolean, onFallback: ((Throwable) -> Unit)?, ensureRequestCurrent: () -> Unit = {}, ): List { val callContext = currentCoroutineContext() fun ensureCurrent() { callContext.ensureActive() ensureRequestCurrent() } ensureCurrent() if (!forceRefresh) savedPages(chapterId, sourceId).takeIf { it.isNotEmpty() }?.let { ensureCurrent() return it } val id = sourceId ?: error("Source is unavailable") var live = true val pages = runtimeFactory.withSourceRuntime(database, id, onFallback?.let { report -> { failure -> ensureCurrent(); report(failure) } }) { runtime -> ensureCurrent() live = runtime !is DatabaseFallbackRuntimeService val headers = runtime.headers() ensureCurrent() val urls = runtime.pageList(chapterUrl) ensureCurrent() mergeSourcePageHeaders(headers, urls) } ensureCurrent() if (live && pages.isNotEmpty()) { database.batch { ensureCurrent() if (database.chapter(chapterId) != null) { repository.cachePageUrls(chapterId, chapterUrl, pages, database.source(id), fetchedAt = clock()) } } } return pages } } /** Fresh = fetched less than [PAGE_LIST_TTL_MS] before [now] by [sourceVersion] of [sourceId]; lists from before timestamps are stale. */ internal fun DbChapterPageUrls.isFresh(sourceId: Long?, sourceVersion: String?, now: Long): Boolean { val fetched = fetchedAt ?: return false return now - fetched in 0 until PAGE_LIST_TTL_MS && this.sourceId == sourceId && this.sourceVersion == sourceVersion } /** Source headers under each page's own; a page header replaces a source header of any case. */ internal fun mergeSourcePageHeaders( sourceHeaders: Map, pages: List, ): List = pages.map { page -> val merged = linkedMapOf() fun append(headers: Map) { headers.forEach { (name, value) -> merged.keys.firstOrNull { it.equals(name, ignoreCase = true) }?.let(merged::remove) merged[name] = value } } append(sourceHeaders) append(page.headers.orEmpty()) page.copy(headers = merged.ifEmpty { null }) }