Yokan / rebuild
Course 1 8624561

ExtensionRuntimeService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionRuntimeService.kt

implementation205 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbPageUrl4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.DbVideo6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.domain.TitleCredit8import eu.friedcutlet.yokan.services.catchingNonCancellation910/**11 * One installed source's extension code. Implementations own their threading: engine work is12 * confined to background dispatchers, so every member is safe to call from the main thread.13 */14interface ExtensionRuntimeService {15    val source: DbSource1617    /** Releases the engine; never called while another call on this runtime is still running. */18    fun dispose() = Unit19    suspend fun supportsLatest(): Boolean = false20    suspend fun headers(): Map<String, String> = emptyMap()21    suspend fun popular(page: Int): SourceListing22    suspend fun latest(page: Int): SourceListing23    suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing24    suspend fun detail(url: String): RemoteDetail25    /** Source-provided relations, kept separate from tracker recommendations. */26    suspend fun related(url: String): SourceRelations = SourceRelations(supported = false)27    suspend fun pageList(url: String): List<DbPageUrl> = emptyList()28    suspend fun videoList(url: String): List<DbVideo> = emptyList()29    suspend fun htmlContent(name: String, url: String): String = ""30    suspend fun cleanHtmlContent(html: String): String = html31    suspend fun filterList(): List<SourceFilter> = emptyList()32    suspend fun sourcePreferences(): List<SourcePreferenceValue> = emptyList()33}3435interface ExtensionRuntimeFactory {36    /** Builds a fresh runtime owned by the caller, who must [ExtensionRuntimeService.dispose] it. */37    fun create(source: DbSource): ExtensionRuntimeService3839    /**40     * Runs [block] against a runtime for [source]. This default builds and disposes one per call;41     * [DynamicExtensionRuntimeFactory] reuses cached runtimes instead.42     */43    suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {44        val runtime = create(source)45        try {46            return block(runtime)47        } finally {48            runtime.dispose()49        }50    }5152    /** Drops any runtime kept for [sourceId], e.g. after the source was uninstalled. */53    fun evict(sourceId: Long) = Unit5455    /** Drops every kept runtime. */56    fun clear() = Unit57}5859/**60 * The entry point for running extension code of an installed source: looks [sourceId] up in61 * [database] and runs [block] on the factory's runtime for it. With [onFallback], a failing runtime62 * is reported to it and [block] is retried against the offline [DatabaseFallbackRuntimeService].63 * Cancellation always propagates and is never turned into a fallback.64 */65suspend fun <T> ExtensionRuntimeFactory.withSourceRuntime(66    database: YokanDatabase,67    sourceId: Long,68    onFallback: ((Throwable) -> Unit)? = null,69    block: suspend (ExtensionRuntimeService) -> T,70): T {71    val source = database.source(sourceId) ?: run {72        evict(sourceId)73        error("This source is no longer installed")74    }75    if (onFallback == null) return withRuntime(source, block)76    return catchingNonCancellation { withRuntime(source, block) }.getOrElse { error ->77        onFallback(error)78        block(DatabaseFallbackRuntimeService(source, database))79    }80}8182data class SourceListing(83    val items: List<RemoteManga>,84    val hasNextPage: Boolean,85)8687data class SourceRelatedGroup(val name: String, val items: List<RemoteManga>)88data class SourceRelations(val supported: Boolean, val groups: List<SourceRelatedGroup> = emptyList())8990data class RemoteManga(91    val title: String,92    val url: String,93    val thumbnailUrl: String? = null,94    val description: String? = null,95    val initialized: Boolean = false,96    /** Animetail `season_number` when this entry is a season; null when unknown. */97    val seasonNumber: Double? = null,98    /** Animetail `FetchType.Seasons`: the entry lists seasons rather than episodes. */99    val fetchesSeasons: Boolean = false,100)101102data class RemoteChapter(103    val title: String,104    val url: String,105    val dateUpload: String = "",106    val scanlator: String = "",107)108109data class RemoteDetail(110    val title: String,111    val url: String,112    val description: String = "",113    val author: String? = null,114    val artist: String? = null,115    val thumbnailUrl: String? = null,116    val chapters: List<RemoteChapter> = emptyList(),117    /** Null preserves saved credits; an empty list explicitly clears them. */118    val cast: List<TitleCredit>? = null,119    /** Non-null for an Animetail Seasons-type title: its season entries replace the episode list. */120    val seasons: List<RemoteManga>? = null,121)122123/**124 * Schema-side representation of a source filter as returned by `extension.filterList()`.125 *126 * Filters originating from JavaScript extensions arrive as heterogenous shapes:127 *  - `CheckBox` — single toggle.128 *  - `GroupFilter` — header with a `state` array of typed children (commonly129 *    CheckBoxes), each carrying its own `name` / `value`. Renders as a130 *    multi-select list.131 *  - `SelectFilter` / `ListFilter` — single-select from a list of entries.132 *  - `TriStateFilter` — three-state checkbox (off / include / exclude).133 *  - `TextFilter` / `EditTextFilter` — free-form text input.134 *  - `SortFilter` — single-select among sort options.135 *136 * [kind] is the dominant classification used by the UI. [entries] carries the137 * displayable label / outbound value pairs (empty for free-form/text filters).138 * Selection state is held outside the schema, in `Map<String, FilterSelection>`.139 */140data class SourceFilter(141    val id: String,142    val name: String,143    val type: String,144    val kind: SourceFilterKind = SourceFilterKind.Toggle,145    val entries: List<FilterEntry> = emptyList(),146    val defaultValue: String? = null,147    /** Current runtime selection. Carried on the schema so existing `search(filters)` signatures stay stable. */148    val selection: FilterSelection? = null,149    /** True only when the extension exposes an ID independent of labels/positions. */150    val hasStableId: Boolean = false,151    val defaultAscending: Boolean = true,152) {153    /** Back-compat shim: callers that only need labels still get the entry names. */154    val values: List<String> get() = entries.map { it.label }155}156157enum class SourceFilterKind {158    /** Single boolean filter (JavaScript `CheckBox`). */159    Toggle,160    /** One-of selection from [SourceFilter.entries]. */161    SingleSelect,162    /** Many-of selection from [SourceFilter.entries]. */163    MultiSelect,164    /** Three-state checkbox: Ignore (default) / Include / Exclude. */165    TriState,166    /** Free-form text input. */167    Text,168    /** Sort option and direction, kept together for faithful runtime requests. */169    Sort,170}171172data class FilterEntry(173    val label: String,174    val value: String,175)176177/**178 * Runtime selection for a single [SourceFilter]. Stored in the UI's selection179 * map; the runtime layer translates this back into the extension's filter180 * payload via `sourceFiltersToJson`.181 */182sealed interface FilterSelection {183    data class Toggle(val checked: Boolean) : FilterSelection184    data class Single(val value: String) : FilterSelection185    data class Multi(val values: Set<String>) : FilterSelection186    /** -1 = exclude, 0 = ignore, 1 = include. */187    data class TriState(val state: Int) : FilterSelection188    data class Text(val value: String) : FilterSelection189    data class Sort(val value: String, val ascending: Boolean) : FilterSelection190}191192data class SourcePreferenceValue(193    val key: String,194    val title: String,195    val value: String,196    val type: String = "editTextPreference",197    val values: List<String> = emptyList(),198)199200data class MihonSourceMetadata(201    val headers: String? = null,202    val supportLatest: Boolean? = null,203    val filterList: String? = null,204    val preferenceList: String? = null,205)206

Search chapters, reference and source filenames.