package eu.friedcutlet.yokan.services.extensions import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.TitleCredit import eu.friedcutlet.yokan.services.catchingNonCancellation /** * One installed source's extension code. Implementations own their threading: engine work is * confined to background dispatchers, so every member is safe to call from the main thread. */ interface ExtensionRuntimeService { val source: DbSource /** Releases the engine; never called while another call on this runtime is still running. */ fun dispose() = Unit suspend fun supportsLatest(): Boolean = false suspend fun headers(): Map = emptyMap() suspend fun popular(page: Int): SourceListing suspend fun latest(page: Int): SourceListing suspend fun search(query: String, page: Int, filters: List): SourceListing suspend fun detail(url: String): RemoteDetail /** Source-provided relations, kept separate from tracker recommendations. */ suspend fun related(url: String): SourceRelations = SourceRelations(supported = false) suspend fun pageList(url: String): List = emptyList() suspend fun videoList(url: String): List = emptyList() suspend fun htmlContent(name: String, url: String): String = "" suspend fun cleanHtmlContent(html: String): String = html suspend fun filterList(): List = emptyList() suspend fun sourcePreferences(): List = emptyList() } interface ExtensionRuntimeFactory { /** Builds a fresh runtime owned by the caller, who must [ExtensionRuntimeService.dispose] it. */ fun create(source: DbSource): ExtensionRuntimeService /** * Runs [block] against a runtime for [source]. This default builds and disposes one per call; * [DynamicExtensionRuntimeFactory] reuses cached runtimes instead. */ suspend fun withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T { val runtime = create(source) try { return block(runtime) } finally { runtime.dispose() } } /** Drops any runtime kept for [sourceId], e.g. after the source was uninstalled. */ fun evict(sourceId: Long) = Unit /** Drops every kept runtime. */ fun clear() = Unit } /** * The entry point for running extension code of an installed source: looks [sourceId] up in * [database] and runs [block] on the factory's runtime for it. With [onFallback], a failing runtime * is reported to it and [block] is retried against the offline [DatabaseFallbackRuntimeService]. * Cancellation always propagates and is never turned into a fallback. */ suspend fun ExtensionRuntimeFactory.withSourceRuntime( database: YokanDatabase, sourceId: Long, onFallback: ((Throwable) -> Unit)? = null, block: suspend (ExtensionRuntimeService) -> T, ): T { val source = database.source(sourceId) ?: run { evict(sourceId) error("This source is no longer installed") } if (onFallback == null) return withRuntime(source, block) return catchingNonCancellation { withRuntime(source, block) }.getOrElse { error -> onFallback(error) block(DatabaseFallbackRuntimeService(source, database)) } } data class SourceListing( val items: List, val hasNextPage: Boolean, ) data class SourceRelatedGroup(val name: String, val items: List) data class SourceRelations(val supported: Boolean, val groups: List = emptyList()) data class RemoteManga( val title: String, val url: String, val thumbnailUrl: String? = null, val description: String? = null, val initialized: Boolean = false, /** Animetail `season_number` when this entry is a season; null when unknown. */ val seasonNumber: Double? = null, /** Animetail `FetchType.Seasons`: the entry lists seasons rather than episodes. */ val fetchesSeasons: Boolean = false, ) data class RemoteChapter( val title: String, val url: String, val dateUpload: String = "", val scanlator: String = "", ) data class RemoteDetail( val title: String, val url: String, val description: String = "", val author: String? = null, val artist: String? = null, val thumbnailUrl: String? = null, val chapters: List = emptyList(), /** Null preserves saved credits; an empty list explicitly clears them. */ val cast: List? = null, /** Non-null for an Animetail Seasons-type title: its season entries replace the episode list. */ val seasons: List? = null, ) /** * Schema-side representation of a source filter as returned by `extension.filterList()`. * * Filters originating from JavaScript extensions arrive as heterogenous shapes: * - `CheckBox` — single toggle. * - `GroupFilter` — header with a `state` array of typed children (commonly * CheckBoxes), each carrying its own `name` / `value`. Renders as a * multi-select list. * - `SelectFilter` / `ListFilter` — single-select from a list of entries. * - `TriStateFilter` — three-state checkbox (off / include / exclude). * - `TextFilter` / `EditTextFilter` — free-form text input. * - `SortFilter` — single-select among sort options. * * [kind] is the dominant classification used by the UI. [entries] carries the * displayable label / outbound value pairs (empty for free-form/text filters). * Selection state is held outside the schema, in `Map`. */ data class SourceFilter( val id: String, val name: String, val type: String, val kind: SourceFilterKind = SourceFilterKind.Toggle, val entries: List = emptyList(), val defaultValue: String? = null, /** Current runtime selection. Carried on the schema so existing `search(filters)` signatures stay stable. */ val selection: FilterSelection? = null, /** True only when the extension exposes an ID independent of labels/positions. */ val hasStableId: Boolean = false, val defaultAscending: Boolean = true, ) { /** Back-compat shim: callers that only need labels still get the entry names. */ val values: List get() = entries.map { it.label } } enum class SourceFilterKind { /** Single boolean filter (JavaScript `CheckBox`). */ Toggle, /** One-of selection from [SourceFilter.entries]. */ SingleSelect, /** Many-of selection from [SourceFilter.entries]. */ MultiSelect, /** Three-state checkbox: Ignore (default) / Include / Exclude. */ TriState, /** Free-form text input. */ Text, /** Sort option and direction, kept together for faithful runtime requests. */ Sort, } data class FilterEntry( val label: String, val value: String, ) /** * Runtime selection for a single [SourceFilter]. Stored in the UI's selection * map; the runtime layer translates this back into the extension's filter * payload via `sourceFiltersToJson`. */ sealed interface FilterSelection { data class Toggle(val checked: Boolean) : FilterSelection data class Single(val value: String) : FilterSelection data class Multi(val values: Set) : FilterSelection /** -1 = exclude, 0 = ignore, 1 = include. */ data class TriState(val state: Int) : FilterSelection data class Text(val value: String) : FilterSelection data class Sort(val value: String, val ascending: Boolean) : FilterSelection } data class SourcePreferenceValue( val key: String, val title: String, val value: String, val type: String = "editTextPreference", val values: List = emptyList(), ) data class MihonSourceMetadata( val headers: String? = null, val supportLatest: Boolean? = null, val filterList: String? = null, val preferenceList: String? = null, )