uniflix: installable JavaScript stream plugins via QuickJS
- Commit
73914fa6165270fc06cbea1f027a6a9dd74e4be6- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-23 23:48 UTC (1 month ago)
- Parents
23dfb19
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 32e72f3ae0..e7015e4861 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -124,6 +124,7 @@ apksig = "9.4.1" # JavaScript engines & HTML quickjs = "1.0.15"+chicory = "1.4.0" # Git jgit = "7.8.0.202609011348-r"@@ -332,6 +333,8 @@ apksig = { module = "com.android.tools.build:apksig", version.ref = "apksig" } # JavaScript engines & HTML quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" }+# Pure-Java WebAssembly runtime (JS plugin WASM host). No native libs, no WASI.+chicory-runtime = { module = "com.dylibso.chicory:runtime", version.ref = "chicory" } # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" }
metadata_data/uniflix.md
diff --git a/metadata_data/uniflix.md b/metadata_data/uniflix.mdindex 5ed509399e..bd1bf29cd2 100644--- a/metadata_data/uniflix.md+++ b/metadata_data/uniflix.md@@ -5,5 +5,6 @@ Features: - Search the catalog, keep a watchlist and custom lists - Resume playback where you left off - Install stream addons by URL and manage them in-app+- Import JavaScript stream plugins (.js) Requires internet
uniflix/AGENTS.md
diff --git a/uniflix/AGENTS.md b/uniflix/AGENTS.mdindex 9a183174f8..99122c6a5b 100644--- a/uniflix/AGENTS.md+++ b/uniflix/AGENTS.md@@ -3,11 +3,11 @@ > Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `uniflix/` + allowed shared modules. Do not root-scan. _Install: ./install uniflix (dev by default)._-<!-- last-reviewed: 2026-10-21 -->+<!-- last-reviewed: 2026-10-23 --> - Gradle: :uniflix / dir: uniflix/ - Package roots present: ui, data, domain, platform - Entry files: MainActivity.kt, Route.kt, Navigation.kt-- Deps: :library:network, :library:image, :library:room, media3 exoplayer/hls, datastore-preferences+- Deps: :library:network, :library:image, :library:room, media3 exoplayer/hls, datastore-preferences, quickjs-kt, chicory-runtime - Metadata: metadata_data/uniflix.md (present) - Rust: no / screenshotTest: no (previews pending) @@ -20,12 +20,13 @@ Watch/Detail link to the addon manager. - Addon manager: add-by-URL, enable/disable, default star, priority ordering, per-addon settings, error badges - `StreamProvider` is the single player-facing contract; `PluginRegistry` resolves default-first then priority fallbacks - Pure-HTTP addon protocol subset: `manifest.json` + `GET {base}/stream/{type}/{id}.json` with `tmdb:` ids-**Architecture / data-flow:** `ui/` (Home→Detail→Watch, AddonsScreen/AddonDetailScreen) → `platform/` (`DetailViewModel` resolves via `RegistryFactory.HttpAddons`, `AddonsViewModel` owns install/order toggles) → `data/` (`AddonStreamProvider` HTTP impl, `UniflixRepository` over Room v2 `AddonEntity`) with pure `domain/` (`AddonManifest` validation, `PluginRegistry` ordering). `Navigation`: TMDB-key onboarding gate (`reset()` not `add()`); `Addons` + `AddonDetail(dbId)` routes.+- Installable JS plugins (`.js` import): QuickJS runtime + generic host (`__ufetch` via NetworkClient, `__uwasm_*` via Chicory, `__uaesgcm_open`, `__urand`); sync-only contract, WASM travels inside the plugin file+**Architecture / data-flow:** `ui/` (Home→Detail→Watch, AddonsScreen/AddonDetailScreen) → `platform/` (`DetailViewModel` resolves via `RegistryFactory.AllInstalled`, `AddonsViewModel` owns install/order toggles + `addJsPlugin`) -> (`data/` (`AddonStreamProvider` HTTP impl, `JsStreamProvider`/`JsPluginEngine` JS impl, `UniflixRepository` over Room v3 `AddonEntity` with `kind`/`jsSource`) with pure `domain/` (`AddonManifest` validation, `JsPluginManifest` parsing, `PluginRegistry` ordering). `Navigation`: TMDB-key onboarding gate (`reset()` not `add()`); `Addons` + `AddonDetail(dbId)` routes. **Entry points + reading order:** `Route` (`Onboarding` / `Home` / `Addons` / `Detail` / `Watch`) → `MainActivity.kt` → `Navigation.kt` → `platform/AddonsViewModel.kt` + `platform/DetailViewModel.kt` → `domain/PluginRegistry.kt` + `data/AddonStreamProvider.kt`. **Gotchas:** - Manifest `resources` accepts Stremio string-or-object forms; only `stream` for movie/series validates - URL addons enforce HTTPS except loopback/private (dev); remote `http://` is rejected as `InsecureUrl`-- `UniflixDatabase` v1→v2 migration adds `AddonEntity`; default addon id lives in DataStore, ordering in Room priority+- `UniflixDatabase` v1→v2 migration adds `AddonEntity`; v2→v3 adds `kind`/`jsSource`; default addon id lives in DataStore, ordering in Room priority - Private `personal/uniflix_strem/` keeps the native Strem provider + hardcoded TMDB key — never copy those into `uniflix/` ## Key files@@ -38,10 +39,13 @@ Watch/Detail link to the addon manager. - com/vayunmathur/uniflix/domain/PluginRegistry.kt — default-first, priority fallback ordering - com/vayunmathur/uniflix/domain/AddonManifest.kt — manifest parse + validate - com/vayunmathur/uniflix/domain/AddonModels.kt — tmdb: id mapping, stream→VideoSource-### data/ — HTTP provider, Room, prefs+- com/vayunmathur/uniflix/domain/JsPluginManifest.kt — JS plugin header + wasm section parse+### data/ — HTTP provider, JS engine, Room, prefs - com/vayunmathur/uniflix/data/AddonStreamProvider.kt — URL addon as StreamProvider+- com/vayunmathur/uniflix/data/JsPluginEngine.kt — QuickJS + Chicory host, sync-only contract+- com/vayunmathur/uniflix/data/JsStreamProvider.kt — JS plugin as StreamProvider - com/vayunmathur/uniflix/data/AddonEntity.kt — installed-addon entity + DAO-- com/vayunmathur/uniflix/data/UniflixDatabase.kt — Room v2 + Migration(1,2)+- com/vayunmathur/uniflix/data/UniflixDatabase.kt — Room v3 + Migration(1,2) + Migration(2,3) - com/vayunmathur/uniflix/data/UniflixRepository.kt — singleton incl. addon flows - com/vayunmathur/uniflix/data/AddonPrefs.kt — default addon id (DataStore) - com/vayunmathur/uniflix/data/TmdbKeyStore.kt — user key only, no default
uniflix/build.gradle.kts
diff --git a/uniflix/build.gradle.kts b/uniflix/build.gradle.ktsindex 02d6ae4218..331f348aaa 100644--- a/uniflix/build.gradle.kts+++ b/uniflix/build.gradle.kts@@ -23,4 +23,19 @@ dependencies { implementation(libs.androidx.media3.exoplayer.hls) implementation(libs.androidx.media3.ui.compose.material3) implementation(libs.androidx.datastore.preferences)+ // JS plugin runtime: QuickJS engine + pure-Java WASM host (Chicory).+ implementation(libs.quickjs.kt)+ implementation(libs.chicory.runtime)+}++// Desktop JVM unit tests cannot load the Android QuickJS .so: run them against+// the -jvm artifact (per quickjs-kt README) while the app keeps the -android AAR.+// configureEach (not named) so this holds however AGP creates the test configs.+configurations.configureEach {+ if (name.endsWith("UnitTestRuntimeClasspath")) {+ resolutionStrategy.dependencySubstitution {+ substitute(module("io.github.dokar3:quickjs-kt-android"))+ .using(module("io.github.dokar3:quickjs-kt-jvm:${libs.versions.quickjs.get()}"))+ }+ } }
uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.ktindex 2e60592a2c..478dddfdbc 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt@@ -25,6 +25,10 @@ data class AddonEntity( /** Last fetch/resolve failure, shown as a badge; null when healthy. */ val lastError: String? = null, val updatedAt: Long = 0L,+ /** `http` for URL addons, `js` for installable JavaScript plugins. */+ val kind: String = "http",+ /** Full plugin file source; only set when [kind] is `js`. */+ val jsSource: String = "", ) @Dao
uniflix/src/main/java/com/vayunmathur/uniflix/data/JsPluginEngine.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsPluginEngine.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsPluginEngine.ktnew file mode 100644index 0000000000..8ec168d634--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsPluginEngine.kt@@ -0,0 +1,330 @@+package com.vayunmathur.uniflix.data++import com.dokar.quickjs.QuickJs+import com.dokar.quickjs.QuickJsException+import com.dokar.quickjs.QuickJsInterruptedException+import com.dokar.quickjs.binding.function+import com.dylibso.chicory.runtime.Instance+import com.dylibso.chicory.wasm.Parser+import com.vayunmathur.uniflix.domain.JsPluginManifest+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.TimeoutCancellationException+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.builtins.serializer+import kotlinx.serialization.json.Json+import java.security.SecureRandom+import javax.crypto.Cipher+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec++/**+ * Wall-clock bound for one plugin call. QuickJS's [QuickJs.evaluationTimeoutMillis]+ * hard-bounds time spent executing JavaScript; the [withTimeout] below is a+ * backstop for it, and socket timeouts in [NetworkClientBridge] bound network.+ */+private const val ENGINE_TIMEOUT_MS = 15_000L+private const val BRIDGE_CONNECT_TIMEOUT_MS = 10_000L+private const val BRIDGE_READ_TIMEOUT_MS = 15_000L+private const val GCM_TAG_BITS = 128++/** One bridged HTTP response, mirroring NetworkClient's RawResponse. */+data class FetchResult(+ val status: Int,+ val bytes: ByteArray,+ val headers: Map<String, List<String>> = emptyMap(),+) {+ val isSuccess: Boolean get() = status in 200..299+}++/**+ * Host HTTP for JS plugins. Production delegates to [NetworkClient] so the+ * STANDARD trust bundle and pinning apply; tests inject a fake (no Robolectric).+ */+interface NetworkBridge {+ suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult+}++/** Production bridge: all plugin traffic flows through NetworkClient. */+object NetworkClientBridge : NetworkBridge {+ override suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult {+ val resp = com.vayunmathur.library.network.NetworkClient.execute(+ url,+ method = method,+ headers = headers,+ body = body,+ connectTimeoutMs = BRIDGE_CONNECT_TIMEOUT_MS,+ readTimeoutMs = BRIDGE_READ_TIMEOUT_MS,+ )+ return FetchResult(status = resp.status, bytes = resp.bytes, headers = resp.headers)+ }+}++private val bridgeJson = Json { ignoreUnknownKeys = true }++/** Live WASM instances for one engine invocation, keyed by small integer handles. */+private class WasmTable {+ private var nextId = 1+ private val instances = mutableMapOf<Int, Instance>()++ fun add(bytes: ByteArray): Int {+ // Zero-import modules take the empty-imports path; the default memory+ // factory is ByteBufferMemory, the Android-preferred implementation.+ // Never select ByteArrayMemory (VarHandle/MethodHandles).+ val instance = Instance.builder(Parser.parse(bytes)).build()+ val id = nextId+++ instances[id] = instance+ return id+ }++ fun get(id: Int): Instance = instances[id] ?: error("__uwasm: unknown handle $id")+}++/**+ * Runs one installable JS plugin inside QuickJS with generic host capabilities.+ *+ * The contract is fully synchronous by design: plugin functions+ * (`resolve(args)`, `servers()`, `alternates(args)`) are plain sync functions+ * returning JSON strings, and every host binding is a sync `function`. In+ * particular `__ufetch` blocks the JS thread (via `runBlocking` over+ * [NetworkBridge]) instead of returning a promise — quickjs-kt only unwraps a+ * promise result on paths no plugin should depend on, so promises are kept+ * out of the contract entirely.+ *+ * Exposed globals (capabilities only — no provider logic, origins, or keys):+ * - `__ufetch(url, method, headersJson, body?)` -> `{status, ok, text, bytes, headers}` (blocking)+ * - `__uwasm_embedded()` -> handle for the plugin's embedded WASM section (0 when absent)+ * - `__uwasm_new(bytes)` / `__uwasm_alloc(handle, size)` / `__uwasm_write(handle, ptr, data)` /+ * `__uwasm_read(handle, ptr, len)` / `__uwasm_call(handle, name, argsJson)` / `__uwasm_free(handle, ptr, size)`+ * - `__uaesgcm_open(key, iv, aad, ctAndTag)` -> plaintext bytes (throws on auth failure)+ * - `__urand(n)` -> n random bytes+ *+ * Byte arrays cross the boundary as `Uint8Array` (Kotlin `UByteArray`); inputs+ * also accept `Int8Array` (Kotlin `ByteArray`).+ *+ * A fresh runtime is created per call and closed in `finally`. There is no+ * DOM, no fetch, and no system trust — all network flows through+ * [NetworkBridge].+ */+@OptIn(ExperimentalUnsignedTypes::class)+class JsPluginEngine(+ private val manifest: JsPluginManifest,+ private val network: NetworkBridge,+ private val timeoutMs: Long = ENGINE_TIMEOUT_MS,+ private val bridgeTimeoutMs: Long = timeoutMs,+) {+ /** Calls `resolve(args)`; returns the plugin's JSON string. */+ suspend fun resolve(argsJson: String): String = call("resolve", argsJson)++ /** Calls `servers()`; returns the plugin's JSON string array. */+ suspend fun servers(): String = call("servers", null)++ /** Calls `alternates(args)`; `[]` when the plugin does not define it. */+ suspend fun alternates(argsJson: String): String =+ runCatching { call("alternates", argsJson) }.getOrDefault("[]")++ private suspend fun call(function: String, argsJson: String?): String {+ val qjs = runCatching { QuickJs.create(Dispatchers.Default) }.getOrElse {+ error("'${manifest.name}' could not start JS runtime: ${it.message}")+ }+ try {+ qjs.evaluationTimeoutMillis = timeoutMs+ val wasm = WasmTable()+ defineFetch(qjs)+ defineWasm(qjs, wasm)+ defineCrypto(qjs)+ return withTimeout(timeoutMs) {+ runCatching {+ qjs.evaluate<Unit>(manifest.jsSource, "${manifest.id}.js")+ }.getOrElse {+ throw mapError("failed to load: ${it.message}")+ }+ // Args travel as a JSON string literal parsed inside JS, so+ // object literals never hit expression-position parsing and+ // quoting is handled by the JSON encoding, not by hand.+ //+ // One sync IIFE per call: the async-constructor check rejects+ // promise-returning plugin fns up front (quickjs-kt does not+ // unwrap promise results on the JNI path), and the typeof+ // check keeps non-string returns as JS errors with the fn+ // name instead of converter failures.+ val args = if (argsJson == null) {+ "undefined"+ } else {+ "JSON.parse(${bridgeJson.encodeToString(argsJson)})"+ }+ val expression = "(() => { if ($function.constructor.name === 'AsyncFunction') " ++ "throw new Error('$function() must be sync and return a JSON string (no promises)'); " ++ "var r = $function($args); " ++ "if (typeof r !== 'string') throw new Error('$function() must return a JSON string'); " ++ "return r; })()"+ val raw = runCatching {+ qjs.evaluate<String>(expression, "${manifest.id}.js")+ }.getOrElse {+ throw mapError(it)+ }+ if (raw.startsWith("Promise {")) {+ throw mapError("$function() must be sync and return a JSON string (no promises)")+ }+ raw+ }+ } catch (e: TimeoutCancellationException) {+ qjs.interruptEvaluation()+ throw IllegalStateException("'${manifest.name}' timed out after ${timeoutMs}ms")+ } finally {+ runCatching { qjs.close() }+ }+ }++ private fun mapError(cause: Throwable): Throwable {+ // Structured cancellation (outer withTimeout) must propagate as-is so+ // the caller's catch maps it to the timeout message; wrapping it here+ // would defeat the deadline.+ if (cause is TimeoutCancellationException) throw cause+ if (cause is QuickJsInterruptedException) {+ return IllegalStateException("'${manifest.name}' timed out after ${timeoutMs}ms")+ }+ if (cause is QuickJsException) {+ val location = listOfNotNull(cause.fileName, cause.lineNumber?.let { ":$it" })+ .joinToString("").ifBlank { null }+ val detail = listOfNotNull(cause.message, location?.let { "at $it" }).joinToString(" ")+ return IllegalStateException("'${manifest.name}' error: $detail")+ }+ return IllegalStateException("'${manifest.name}' error: ${cause.message}")+ }++ private fun mapError(message: String): Throwable =+ IllegalStateException("'${manifest.name}' $message")++ private fun defineFetch(qjs: QuickJs) {+ // Sync binding over a suspend bridge: blocks the evaluating worker+ // while the fetch runs on IO. Safe because the bridge never re-enters+ // this QuickJs instance (it only touches NetworkClient), and the+ // registry resolves addons sequentially so at most one worker blocks.+ qjs.function("__ufetch") { args ->+ val url = args.getOrNull(0) as? String ?: error("__ufetch: url must be a string")+ val method = args.getOrNull(1) as? String ?: "GET"+ val headersJson = args.getOrNull(2) as? String ?: "{}"+ val body = args.bytesOrNull(3)+ val headers = runCatching {+ bridgeJson.decodeFromString<Map<String, String>>(headersJson)+ }.getOrDefault(emptyMap())+ val res = runBlocking(Dispatchers.IO) {+ // Bounded here, not just by the outer withTimeout: the worker+ // thread blocks inside this binding, so an unbounded fetch+ // would wedge it past every outer deadline.+ withTimeout(bridgeTimeoutMs) { network.fetch(url, method, headers, body) }+ }+ bridgeJson.encodeToString(+ FetchResponse.serializer(),+ FetchResponse(+ status = res.status,+ ok = res.isSuccess,+ text = res.bytes.toString(Charsets.UTF_8),+ bytes = java.util.Base64.getEncoder().encodeToString(res.bytes),+ ),+ )+ }+ }++ private fun defineWasm(qjs: QuickJs, table: WasmTable) {+ qjs.function("__uwasm_embedded") {+ val bytes = manifest.wasmBytes ?: return@function 0+ table.add(bytes)+ }+ qjs.function("__uwasm_new") { args ->+ table.add(args.bytes(0, "__uwasm_new"))+ }+ qjs.function("__uwasm_alloc") { args ->+ val handle = args.int(0, "__uwasm_alloc")+ val size = args.int(1, "__uwasm_alloc")+ table.get(handle).export("alloc").apply(size.toLong())[0].toInt()+ }+ qjs.function("__uwasm_write") { args ->+ val handle = args.int(0, "__uwasm_write")+ val ptr = args.int(1, "__uwasm_write")+ val data = args.bytes(2, "__uwasm_write")+ table.get(handle).exports().memory("memory").write(ptr, data)+ true+ }+ qjs.function("__uwasm_read") { args ->+ val handle = args.int(0, "__uwasm_read")+ val ptr = args.int(1, "__uwasm_read")+ val len = args.int(2, "__uwasm_read")+ table.get(handle).exports().memory("memory").readBytes(ptr, len).asUByteArray()+ }+ qjs.function("__uwasm_call") { args ->+ val handle = args.int(0, "__uwasm_call")+ val name = args.getOrNull(1) as? String ?: error("__uwasm_call: name required")+ val paramsJson = args.getOrNull(2) as? String ?: "[]"+ val params = runCatching {+ bridgeJson.decodeFromString(ListSerializer(Long.serializer()), paramsJson)+ }.getOrElse { error("__uwasm_call: args must be a JSON array of numbers") }+ table.get(handle).export(name).apply(*params.toLongArray())[0]+ }+ qjs.function("__uwasm_free") { args ->+ val handle = args.int(0, "__uwasm_free")+ val ptr = args.int(1, "__uwasm_free")+ val size = args.int(2, "__uwasm_free")+ table.get(handle).export("dealloc").apply(ptr.toLong(), size.toLong())+ true+ }+ }++ private fun defineCrypto(qjs: QuickJs) {+ qjs.function("__uaesgcm_open") { args ->+ val key = args.bytes(0, "__uaesgcm_open")+ val iv = args.bytes(1, "__uaesgcm_open")+ val aad = args.bytes(2, "__uaesgcm_open")+ val ct = args.bytes(3, "__uaesgcm_open")+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))+ cipher.updateAAD(aad)+ cipher.doFinal(ct).asUByteArray()+ }+ qjs.function("__urand") { args ->+ val n = args.int(0, "__urand")+ if (n < 0 || n > 1024) error("__urand: byte count out of range")+ ByteArray(n).also { SecureRandom().nextBytes(it) }.asUByteArray()+ }+ }++ private fun Array<Any?>.int(index: Int, what: String): Int =+ (getOrNull(index) as? Number)?.toInt() ?: error("$what: numeric argument required")++ /** Accepts `Uint8Array` (UByteArray) or `Int8Array` (ByteArray) from JS. */+ private fun Array<Any?>.bytes(index: Int, what: String): ByteArray =+ bytesOrNull(index) ?: error("$what: byte array required")++ private fun Array<Any?>.bytesOrNull(index: Int): ByteArray? =+ when (val value = getOrNull(index)) {+ null -> null+ is ByteArray -> value+ is UByteArray -> value.asByteArray()+ else -> null+ }+}++/**+ * `__ufetch` result as a JSON string (not a JS object): string returns are+ * the proven marshalling shape, so structured host results cross as JSON the+ * plugin parses. `bytes` is base64; decode with a tiny `b64ToBytes` helper.+ */[email protected]+private data class FetchResponse(+ val status: Int,+ val ok: Boolean,+ val text: String,+ val bytes: String,+)
uniflix/src/main/java/com/vayunmathur/uniflix/data/JsStreamProvider.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsStreamProvider.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsStreamProvider.ktnew file mode 100644index 0000000000..eb4ff6eee7--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/JsStreamProvider.kt@@ -0,0 +1,137 @@+package com.vayunmathur.uniflix.data++import com.vayunmathur.uniflix.domain.JsPluginManifest+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.StreamProvider+import com.vayunmathur.uniflix.domain.SubtitleTrack+import com.vayunmathur.uniflix.domain.VideoSource+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++@Serializable+private data class JsResolveArgs(+ val tmdb: Int,+ val type: String,+ val season: Int = 0,+ val episode: Int = 0,+ val server: String? = null,+ val config: String = "{}",+)++@Serializable+private data class JsResolveResult(+ val streamUrl: String = "",+ val title: String = "",+ val subtitles: List<JsSubtitle> = emptyList(),+) {+ fun toVideoSource(fallbackTitle: String): VideoSource? {+ if (streamUrl.isBlank()) return null+ return VideoSource(+ streamUrl = streamUrl,+ title = title.ifBlank { fallbackTitle },+ subtitles = subtitles.mapNotNull {+ if (it.url.isBlank()) null+ else SubtitleTrack(+ language = it.language.ifBlank { "en" },+ displayName = it.displayName.ifBlank { it.language },+ url = it.url,+ )+ },+ )+ }+}++@Serializable+private data class JsSubtitle(+ val language: String = "",+ val displayName: String = "",+ val url: String = "",+)++private val pluginJson = Json { ignoreUnknownKeys = true }++/**+ * An installable JavaScript plugin as a [StreamProvider].+ *+ * Delegates resolution to [JsPluginEngine]: builds JSON args from the catalog+ * id, calls the plugin's `resolve()`/`servers()`/`alternates()`, and maps the+ * returned JSON onto [VideoSource]. All failures are wrapped with the plugin+ * name so the registry's per-addon error badge reads correctly.+ */+class JsStreamProvider(+ private val manifest: JsPluginManifest,+ private val displayName: String,+ private val configJson: String = "{}",+ private val network: NetworkBridge = NetworkClientBridge,+) : StreamProvider() {+ override val name: String get() = displayName+ override val supports4k: Boolean = false++ private fun engine() = JsPluginEngine(manifest, network)++ override suspend fun resolve(+ tmdbId: Int,+ mediaType: MediaType,+ season: Int,+ episode: Int,+ server: String?,+ ): VideoSource {+ val args = pluginJson.encodeToString(+ JsResolveArgs.serializer(),+ JsResolveArgs(+ tmdb = tmdbId,+ type = if (mediaType == MediaType.TV) "series" else "movie",+ season = season,+ episode = episode,+ server = server,+ config = configJson,+ ),+ )+ val raw = runCatching { engine().resolve(args) }.getOrElse { throw wrap(it) }+ val result = runCatching {+ pluginJson.decodeFromString(JsResolveResult.serializer(), raw)+ }.getOrElse { throw wrap("returned malformed result: ${it.message}") }+ return result.toVideoSource(displayName)+ ?: throw wrap("has no streams for this title")+ }++ override suspend fun alternates(+ tmdbId: Int,+ mediaType: MediaType,+ season: Int,+ episode: Int,+ ): List<VideoSource> {+ val args = pluginJson.encodeToString(+ JsResolveArgs.serializer(),+ JsResolveArgs(+ tmdb = tmdbId,+ type = if (mediaType == MediaType.TV) "series" else "movie",+ season = season,+ episode = episode,+ config = configJson,+ ),+ )+ val raw = runCatching { engine().alternates(args) }.getOrElse { return emptyList() }+ if (raw.isBlank()) return emptyList()+ val list = runCatching {+ pluginJson.decodeFromString<List<JsResolveResult>>(raw)+ }.getOrDefault(emptyList())+ return list.mapNotNull { it.toVideoSource(displayName) }+ }++ override suspend fun servers(): List<String> {+ val raw = runCatching { engine().servers() }.getOrElse { throw wrap(it) }+ return runCatching {+ pluginJson.decodeFromString<List<String>>(raw)+ }.getOrElse { throw wrap("returned malformed servers: ${it.message}") }+ .map { it.trim() }+ .filter { it.isNotEmpty() }+ }++ private fun wrap(cause: Throwable): Throwable =+ if (cause.message?.startsWith("'$displayName'") == true) cause+ else IllegalStateException("'$displayName' failed: ${cause.message}", cause)++ private fun wrap(message: String): Throwable =+ IllegalStateException("'$displayName' $message")+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.ktindex ea28dfcee5..6bec892fed 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt@@ -143,7 +143,7 @@ interface UserListDao { TitleNote::class, AddonEntity::class, ],- version = 2,+ version = 3, exportSchema = false, ) abstract class UniflixDatabase : RoomDatabase() {@@ -170,7 +170,21 @@ abstract class UniflixDatabase : RoomDatabase() { "priority INTEGER NOT NULL, " + "configJson TEXT NOT NULL, " + "lastError TEXT, " +- "updatedAt INTEGER NOT NULL)"+ "updatedAt INTEGER NOT NULL, " ++ "kind TEXT NOT NULL DEFAULT 'http', " ++ "jsSource TEXT NOT NULL DEFAULT '')"+ )+ }+ },+ object : Migration(2, 3) {+ override suspend fun migrate(connection: SQLiteConnection) {+ // Installable JavaScript plugins: kind + embedded source.+ // Existing rows stay `http` URL addons.+ connection.execSQL(+ "ALTER TABLE AddonEntity ADD COLUMN kind TEXT NOT NULL DEFAULT 'http'",+ )+ connection.execSQL(+ "ALTER TABLE AddonEntity ADD COLUMN jsSource TEXT NOT NULL DEFAULT ''", ) } },
uniflix/src/main/java/com/vayunmathur/uniflix/domain/JsPluginManifest.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/JsPluginManifest.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/JsPluginManifest.ktnew file mode 100644index 0000000000..f073bd31ea--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/JsPluginManifest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.uniflix.domain++/** Maximum accepted plugin file size (covers ~90KB base64 wasm + JS with headroom). */+const val JS_PLUGIN_MAX_CHARS = 512 * 1024++private const val HEADER_PREFIX = "@uniflix-plugin"+private const val WASM_BEGIN = "@uniflix-wasm-begin"+private const val WASM_END = "@uniflix-wasm-end"+private val ID_PATTERN = Regex("[a-z0-9][a-z0-9._-]*")++/**+ * Identity + sources of an installable JavaScript plugin.+ *+ * The file declares itself in a leading comment header:+ * `// @uniflix-plugin id=<id> name=<name> version=<version>`+ * followed by the plugin JS. An optional WASM section carries embedded+ * module bytes (e.g. a seal implementation) as base64 between+ * `// @uniflix-wasm-begin` and `// @uniflix-wasm-end` markers:+ *+ * The host ([data.JsPluginEngine]) exposes capabilities only; all provider+ * logic lives in [jsSource]. Pure (no Android) so parsing is unit-testable.+ */+data class JsPluginManifest(+ val id: String,+ val name: String,+ val version: String,+ val jsSource: String,+ val wasmBytes: ByteArray? = null,+) {+ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is JsPluginManifest) return false+ return id == other.id && name == other.name && version == other.version &&+ jsSource == other.jsSource && (wasmBytes == null) == (other.wasmBytes == null)+ }++ override fun hashCode(): Int {+ var result = id.hashCode()+ result = 31 * result + name.hashCode()+ result = 31 * result + version.hashCode()+ return result+ }++ companion object {+ /** Parses and validates a plugin file; throws [ManifestError.Parse] when invalid. */+ fun parse(source: String): JsPluginManifest {+ if (source.length > JS_PLUGIN_MAX_CHARS) {+ throw ManifestError.Parse(+ "Plugin file too large (${source.length} chars, max $JS_PLUGIN_MAX_CHARS)",+ )+ }+ val lines = source.lines()+ val header = lines.firstOrNull { HEADER_PREFIX in it }+ ?: throw ManifestError.Parse(+ "Not a UniFlix plugin: missing '$HEADER_PREFIX id=.. name=.. version=..' header",+ )+ val id = field(header, "id") ?: throw ManifestError.Parse("Plugin header missing id=")+ val name = field(header, "name") ?: throw ManifestError.Parse("Plugin header missing name=")+ val version = field(header, "version")+ ?: throw ManifestError.Parse("Plugin header missing version=")+ if (!ID_PATTERN.matches(id)) {+ throw ManifestError.Parse("Plugin id must match [a-z0-9._-]: '$id'")+ }+ if (name.isBlank()) throw ManifestError.Parse("Plugin name must not be blank")+ if (version.isBlank()) throw ManifestError.Parse("Plugin version must not be blank")++ val wasmBytes = extractWasm(lines)+ return JsPluginManifest(+ id = id,+ name = name,+ version = version,+ jsSource = source,+ wasmBytes = wasmBytes,+ )+ }++ private fun field(header: String, key: String): String? {+ val pattern = Regex("$key=(\"[^\"]*\"|\\S+)")+ val raw = pattern.find(header)?.groupValues?.getOrNull(1) ?: return null+ return raw.removeSurrounding("\"")+ }++ private fun extractWasm(lines: List<String>): ByteArray? {+ val begin = lines.indexOfFirst { WASM_BEGIN in it }+ if (begin < 0) return null+ val end = lines.indexOfFirst { WASM_END in it }+ if (end < 0 || end <= begin) {+ throw ManifestError.Parse("Plugin has '$WASM_BEGIN' without '$WASM_END'")+ }+ val base64 = lines.subList(begin + 1, end)+ .map { it.removePrefix("//").trim() }+ .filter { it.isNotEmpty() }+ .joinToString("")+ if (base64.isEmpty()) throw ManifestError.Parse("Plugin WASM section is empty")+ return runCatching {+ java.util.Base64.getMimeDecoder().decode(base64)+ }.getOrElse {+ throw ManifestError.Parse("Plugin WASM section is not valid base64")+ }+ }+ }+}
uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.ktindex a4b3649132..f0a987449d 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.kt@@ -103,4 +103,14 @@ data class InstalledAddon( val name: String, val version: String = "", val priority: Int = 0,+ /** `http` for URL addons, `js` for installable JavaScript plugins. */+ val kind: String = AddonKind.HTTP,+ /** Full plugin file source; only set when [kind] is [AddonKind.JS]. */+ val jsSource: String = "", )++/** Addon kinds: URL (Stremio HTTP) vs installable JavaScript plugin. */+object AddonKind {+ const val HTTP = "http"+ const val JS = "js"+}
uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.ktindex 8fb1f34c42..d2a0e7226c 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt@@ -11,7 +11,11 @@ import com.vayunmathur.library.util.AppMessages import com.vayunmathur.uniflix.data.AddonEntity import com.vayunmathur.uniflix.data.AddonPrefs import com.vayunmathur.uniflix.data.AddonStreamProvider+import com.vayunmathur.uniflix.data.JsStreamProvider+import com.vayunmathur.uniflix.data.NetworkClientBridge import com.vayunmathur.uniflix.data.UniflixRepository+import com.vayunmathur.uniflix.domain.AddonKind+import com.vayunmathur.uniflix.domain.JsPluginManifest import com.vayunmathur.uniflix.domain.ManifestError import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.combine@@ -76,6 +80,44 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { } } + /** Validates [source] as a JS plugin and stores it. */+ fun addJsPlugin(source: String) {+ if (source.isBlank()) return+ viewModelScope.launch {+ adding = true+ runCatching {+ val manifest = JsPluginManifest.parse(source)+ val key = "js:${manifest.id}"+ val existing = repository.addonByManifestUrl(key)+ val count = repository.addonCount()+ repository.upsertAddon(+ (existing ?: AddonEntity(+ manifestUrl = key,+ baseUrl = "",+ addonId = manifest.id,+ name = manifest.name,+ priority = count,+ kind = AddonKind.JS,+ )).copy(+ addonId = manifest.id,+ name = manifest.name,+ version = manifest.version,+ kind = AddonKind.JS,+ jsSource = source,+ lastError = null,+ updatedAt = System.currentTimeMillis(),+ ),+ )+ AppMessages.show("Added ${manifest.name}")+ }.onFailure {+ val message = it.message ?: "Could not add plugin"+ Log.error(TAG, "Add plugin failed: $message", it)+ AppMessages.show(message)+ }+ adding = false+ }+ }+ fun remove(row: AddonRow) { viewModelScope.launch { repository.deleteAddon(row.entity.dbId)@@ -126,6 +168,7 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { val rows = addons.first() var failures = 0 for (row in rows) {+ if (row.entity.kind == AddonKind.JS) continue runCatching { val (base, manifest) = AddonStreamProvider.fetchManifest(row.entity.manifestUrl) repository.upsertAddon(@@ -150,6 +193,10 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { /** Re-fetches the manifest; updates identity, clears or sets [AddonEntity.lastError]. */ fun refreshManifest(row: AddonRow) {+ if (row.entity.kind == AddonKind.JS) {+ AppMessages.show("Re-import the .js file to update ${row.entity.name}")+ return+ } viewModelScope.launch { refreshing = true runCatching {@@ -176,6 +223,10 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { /** Re-resolves identity without changing priority/enabled; reports reachability. */ fun testAddon(row: AddonRow) {+ if (row.entity.kind == AddonKind.JS) {+ testJsPlugin(row)+ return+ } viewModelScope.launch { runCatching { AddonStreamProvider.fetchManifest(row.entity.manifestUrl)@@ -190,6 +241,30 @@ class AddonsViewModel(app: Application) : AndroidViewModel(app) { } } + /** Runs the plugin's `servers()` as a health probe; failures land on the row badge. */+ private fun testJsPlugin(row: AddonRow) {+ viewModelScope.launch {+ runCatching {+ val manifest = JsPluginManifest.parse(row.entity.jsSource)+ val provider = JsStreamProvider(+ manifest = manifest,+ displayName = row.entity.name,+ configJson = row.entity.configJson,+ network = NetworkClientBridge,+ )+ val servers = provider.servers()+ repository.setAddonError(row.entity.dbId, null)+ val detail = if (servers.isEmpty()) "no servers listed" else "${servers.size} server(s)"+ AppMessages.show("${row.entity.name} works ($detail)")+ }.onFailure {+ val message = it.message ?: "Plugin failed"+ repository.setAddonError(row.entity.dbId, message)+ Log.error(TAG, "Test plugin failed: $message", it)+ AppMessages.show(message)+ }+ }+ }+ fun updateConfig(dbId: Long, config: String) { viewModelScope.launch { repository.setAddonConfig(dbId, config)
uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.ktindex 13998f6c17..ec0783917d 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt@@ -10,6 +10,7 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.AppMessages import com.vayunmathur.uniflix.data.AddonPrefs import com.vayunmathur.uniflix.data.AddonStreamProvider+import com.vayunmathur.uniflix.data.JsStreamProvider import com.vayunmathur.uniflix.data.ContinueWatchingEntry import com.vayunmathur.uniflix.data.TitleNote import com.vayunmathur.uniflix.data.TmdbApi@@ -17,7 +18,9 @@ import com.vayunmathur.uniflix.data.UniflixRepository import com.vayunmathur.uniflix.data.WatchlistEntry import com.vayunmathur.uniflix.data.watchKey import com.vayunmathur.uniflix.domain.Episode+import com.vayunmathur.uniflix.domain.AddonKind import com.vayunmathur.uniflix.domain.InstalledAddon+import com.vayunmathur.uniflix.domain.JsPluginManifest import com.vayunmathur.uniflix.domain.MediaDetail import com.vayunmathur.uniflix.domain.MediaType import com.vayunmathur.uniflix.domain.PluginRegistry@@ -58,6 +61,37 @@ fun interface RegistryFactory { }, ) }++ /** Installed addons of both kinds: HTTP URL addons + JS plugins. */+ val AllInstalled = RegistryFactory { repository, prefs ->+ val entities = repository.enabledAddons.first()+ val defaultId = prefs.defaultAddonDbId.first()+ PluginRegistry.ordered(+ entities = entities.map {+ InstalledAddon(+ dbId = it.dbId,+ addonId = it.addonId,+ baseUrl = it.baseUrl,+ name = it.name,+ version = it.version,+ priority = it.priority,+ kind = it.kind,+ jsSource = it.jsSource,+ )+ },+ defaultDbId = defaultId,+ build = { installed ->+ if (installed.kind == AddonKind.JS) {+ runCatching {+ val manifest = JsPluginManifest.parse(installed.jsSource)+ JsStreamProvider(manifest = manifest, displayName = installed.name)+ }.getOrNull()+ } else {+ AddonStreamProvider(baseUrl = installed.baseUrl, displayName = installed.name)+ }+ },+ )+ } } } @@ -83,7 +117,7 @@ data class DetailUiState( class DetailViewModel( app: Application,- private val registryFactory: RegistryFactory = RegistryFactory.HttpAddons,+ private val registryFactory: RegistryFactory = RegistryFactory.AllInstalled, ) : AndroidViewModel(app) { private val api = TmdbApi() private val repository = UniflixRepository.get(app)
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.ktindex 7c8d429d87..e954c615f9 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt@@ -2,6 +2,7 @@ package com.vayunmathur.uniflix.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState@@ -16,7 +17,9 @@ import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.IconUpload import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.uniflix.platform.AddonRow@@ -32,6 +35,7 @@ fun AddonsContent( refreshing: Boolean, onBack: () -> Unit, onAddClick: () -> Unit,+ onImportJsClick: () -> Unit, onToggle: (AddonRow) -> Unit, onSetDefault: (AddonRow) -> Unit, onClearDefault: () -> Unit,@@ -48,6 +52,7 @@ fun AddonsContent( scrollBehavior = appBarScrollBehavior(), actions = { IconButton(onClick = onRefreshAll, enabled = !refreshing) { IconRefresh() }+ IconButton(onClick = onImportJsClick) { IconUpload() } IconButton(onClick = onAddClick) { IconAdd() } }, ) { padding ->@@ -57,7 +62,7 @@ fun AddonsContent( verticalArrangement = Arrangement.spacedBy(12.dp), ) { Text(- "Addons supply streams. Uniflix ships none — paste an addon URL to watch.",+ "Addons supply streams. Uniflix ships none — paste an addon URL or import a .js plugin to watch.", style = MaterialTheme.typography.bodyMedium, ) if (rows.isEmpty()) {@@ -65,7 +70,10 @@ fun AddonsContent( "No stream addons yet. Add one to enable playback.", style = MaterialTheme.typography.bodyMedium, )- Button(onClick = onAddClick, enabled = !adding) { Text("Add addon") }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Button(onClick = onAddClick, enabled = !adding) { Text("Add addon") }+ OutlinedButton(onClick = onImportJsClick, enabled = !adding) { Text("Import .js") }+ } return@Column } rows.forEach { row ->
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.ktindex 19754858a8..0ddd861ca8 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt@@ -1,14 +1,25 @@ package com.vayunmathur.uniflix.ui +import android.net.Uri+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.uniflix.platform.AddonsViewModel import com.vayunmathur.uniflix.ui.dialogs.AddAddonDialog+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++private val JS_MIME_TYPES = arrayOf("text/javascript", "application/javascript", "text/plain") /** * Addon manager: installed URL addons with enable toggle, default star,@@ -20,6 +31,26 @@ fun AddonsScreen(onBack: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit) { val vm: AddonsViewModel = viewModel() val rows by vm.addons.collectAsState() var showAddDialog by remember { mutableStateOf(false) }+ val context = LocalContext.current+ val scope = rememberCoroutineScope()++ val importLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.OpenDocument(),+ ) { uri: Uri? ->+ if (uri == null) return@rememberLauncherForActivityResult+ scope.launch {+ runCatching {+ val source = withContext(Dispatchers.IO) {+ context.contentResolver.openInputStream(uri)?.bufferedReader()?.readText()+ ?: error("Could not read file")+ }+ vm.addJsPlugin(source)+ }.onFailure {+ AppMessages.show(it.message ?: "Could not import plugin")+ }+ }+ }+ val importJs: () -> Unit = { importLauncher.launch(JS_MIME_TYPES) } AddonsContent( rows = rows,@@ -27,6 +58,7 @@ fun AddonsScreen(onBack: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit) { refreshing = vm.refreshing, onBack = onBack, onAddClick = { showAddDialog = true },+ onImportJsClick = importJs, onToggle = { row -> vm.setEnabled(row, !row.entity.enabled) }, onSetDefault = { row -> vm.setDefault(row) }, onClearDefault = { vm.clearDefault() },@@ -46,6 +78,10 @@ fun AddonsScreen(onBack: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit) { vm.addByUrl(url) showAddDialog = false },+ onImportJs = {+ showAddDialog = false+ importJs()+ }, ) } }
uniflix/src/main/java/com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.ktindex 22af5cbb3c..8f6e003a14 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.kt@@ -18,7 +18,12 @@ import com.vayunmathur.library.ui.TextButton /** Add-by-URL dialog: accepts a bare addon base or a full `.../manifest.json` URL. */ @Composable-fun AddAddonDialog(adding: Boolean, onDismiss: () -> Unit, onConfirm: (String) -> Unit) {+fun AddAddonDialog(+ adding: Boolean,+ onDismiss: () -> Unit,+ onConfirm: (String) -> Unit,+ onImportJs: () -> Unit,+) { var url by remember { mutableStateOf("") } AlertDialog( onDismissRequest = onDismiss,@@ -33,6 +38,9 @@ fun AddAddonDialog(adding: Boolean, onDismiss: () -> Unit, onConfirm: (String) - modifier = Modifier.fillMaxWidth(), singleLine = true, )+ TextButton(onClick = onImportJs, enabled = !adding) {+ Text("Import .js plugin instead")+ } if (adding) CircularProgressIndicator() } },
uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt
diff --git a/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt b/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.ktindex 937b72ecaa..bf0ad1de10 100644--- a/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt+++ b/uniflix/src/screenshotTest/kotlin/com/vayunmathur/uniflix/ui/MetadataPreviews.kt@@ -34,6 +34,7 @@ class MetadataPreviews { refreshing = false, onBack = {}, onAddClick = {},+ onImportJsClick = {}, onToggle = {}, onSetDefault = {}, onClearDefault = {},@@ -88,6 +89,7 @@ class MetadataPreviews { refreshing = false, onBack = {}, onAddClick = {},+ onImportJsClick = {}, onToggle = {}, onSetDefault = {}, onClearDefault = {},
uniflix/src/test/java/com/vayunmathur/uniflix/data/JsPluginEngineTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/data/JsPluginEngineTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/data/JsPluginEngineTest.ktnew file mode 100644index 0000000000..30a0f1fe9e--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/data/JsPluginEngineTest.kt@@ -0,0 +1,303 @@+package com.vayunmathur.uniflix.data++import com.vayunmathur.uniflix.domain.JsPluginManifest+import com.vayunmathur.uniflix.domain.MediaType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertIs+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++private fun manifest(source: String) = JsPluginManifest.parse(+ "// @uniflix-plugin id=test.plugin name=\"Test\" version=1.0.0\n$source",+)++private val stubBridge = object : NetworkBridge {+ override suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult = FetchResult(status = 200, bytes = "{}".toByteArray())+}++/**+ * Engine: sync plugin fns, JSON contract, error wrapping, timeouts.+ *+ * The contract is deliberately sync-only (async plugin fns are rejected):+ * quickjs-kt does not reliably unwrap promise results on the JNI path, so+ * promises are kept out of the plugin surface entirely.+ */+class JsPluginEngineTest {++ @Test+ fun sync_resolve_returns_json() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ return JSON.stringify({ok: a.tmdb}); }"),+ stubBridge,+ )+ assertEquals("""{"ok":550}""", engine.resolve("""{"tmdb":550}"""))+ }+ }++ @Test+ fun async_resolve_is_rejected_with_contract_error() { runBlocking {+ val engine = JsPluginEngine(+ manifest("async function resolve(a){ return '\"async-ok\"'; }"),+ stubBridge,+ )+ val failure = assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ assertTrue(failure.message!!.contains("must be sync"), failure.message)+ }+ }++ @Test+ fun servers_parses_string_array() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function servers(){ return '[\"Nebula\",\"Lisbon\"]'; }"),+ stubBridge,+ )+ assertEquals("""["Nebula","Lisbon"]""", engine.servers())+ }+ }++ @Test+ fun alternates_defaults_to_empty_when_undefined() { runBlocking {+ val engine = JsPluginEngine(manifest("function resolve(a){return '{}';}"), stubBridge)+ assertEquals("[]", engine.alternates("{}"))+ }+ }++ @Test+ fun sync_ufetch_bridge_round_trips() { runBlocking {+ val seen = mutableListOf<String>()+ val bridge = object : NetworkBridge {+ override suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult {+ seen += "$method $url"+ return FetchResult(status = 200, bytes = """{"hello":"world"}""".toByteArray())+ }+ }+ val engine = JsPluginEngine(+ manifest(+ "function resolve(a){ " ++ "var r = JSON.parse(__ufetch('https://x.example/g', 'POST', '{}', null)); " ++ "return JSON.stringify({status: r.status, ok: r.ok, body: r.text}); }",+ ),+ bridge,+ )+ val out = engine.resolve("{}")+ assertTrue(out.contains("\"status\":200"), out)+ assertTrue(out.contains("\"ok\":true"), out)+ assertTrue(out.contains("world"), out)+ assertEquals(listOf("POST https://x.example/g"), seen)+ }+ }++ @Test+ fun ufetch_bytes_arrive_as_base64() { runBlocking {+ val bridge = object : NetworkBridge {+ override suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult = FetchResult(status = 200, bytes = byteArrayOf(1, 2, 3))+ }+ val engine = JsPluginEngine(+ manifest("function resolve(a){ var r = JSON.parse(__ufetch('https://x.example/', 'GET', '{}', null)); return r.bytes; }"),+ bridge,+ )+ assertEquals("AQID", engine.resolve("{}"))+ }+ }++ @Test+ fun plugin_throw_surfaces_plugin_name() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ throw new Error('boom'); }"),+ stubBridge,+ )+ val failure = assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ assertTrue(failure.message!!.contains("'Test'"), failure.message)+ assertTrue(failure.message!!.contains("boom"), failure.message)+ }+ }++ @Test+ fun missing_resolve_function_errors() { runBlocking {+ val engine = JsPluginEngine(manifest("function servers(){return '[]';}"), stubBridge)+ assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ }+ }++ @Test+ fun non_string_return_rejected_with_contract_error() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ return {not: 'a string'}; }"),+ stubBridge,+ )+ val failure = assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ assertTrue(failure.message!!.contains("must return a JSON string"), failure.message)+ }+ }++ @Test+ fun network_hang_hits_wall_clock_timeout() { runBlocking {+ val hanging = object : NetworkBridge {+ override suspend fun fetch(+ url: String,+ method: String,+ headers: Map<String, String>,+ body: ByteArray?,+ ): FetchResult {+ kotlinx.coroutines.delay(30_000)+ return FetchResult(200, ByteArray(0))+ }+ }+ val engine = JsPluginEngine(+ manifest(+ "function resolve(a){ __ufetch('https://x.example/', 'GET', '{}', null); return '{}'; }",+ ),+ hanging,+ timeoutMs = 500,+ )+ val failure = assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ assertTrue(failure.message!!.contains("imed out"), failure.message)+ }+ }++ @Test+ fun urand_returns_requested_bytes() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ return JSON.stringify({n: __urand(44).length}); }"),+ stubBridge,+ )+ assertEquals("""{"n":44}""", engine.resolve("{}"))+ }+ }++ @Test+ fun wasm_new_without_bytes_errors() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ __uwasm_new(new Uint8Array(0)); return '{}'; }"),+ stubBridge,+ )+ assertFailsWith<IllegalStateException> { engine.resolve("{}") }+ }+ }++ @Test+ fun resolve_receives_episode_args() { runBlocking {+ val engine = JsPluginEngine(+ manifest("function resolve(a){ return JSON.stringify(a); }"),+ stubBridge,+ )+ val out = engine.resolve("""{"tmdb":1396,"type":"series","season":1,"episode":2}""")+ assertTrue(out.contains("\"season\":1"), out)+ assertTrue(out.contains("\"episode\":2"), out)+ assertTrue(out.contains("\"type\":\"series\""), out)+ }+ }+}++/** Provider: JSON mapping onto VideoSource, error naming, server filtering. */+class JsStreamProviderTest {++ private fun provider(+ source: String,+ bridge: NetworkBridge = stubBridge,+ name: String = "Test",+ ) = JsStreamProvider(manifest = manifest(source), displayName = name, network = bridge)++ @Test+ fun resolve_maps_playlist_and_subtitles() { runBlocking {+ val plugin = provider(+ "function resolve(a){ return JSON.stringify({" ++ "streamUrl:'https://cdn.example/s.m3u8', title:'1080p'," ++ "subtitles:[{language:'en', displayName:'English', url:'https://cdn.example/en.vtt'}]}); }",+ )+ val result = plugin.resolve(550, MediaType.MOVIE)+ assertEquals("https://cdn.example/s.m3u8", result.streamUrl)+ assertEquals("1080p", result.title)+ assertEquals("https://cdn.example/en.vtt", result.subtitles.single().url)+ assertEquals("en", result.subtitles.single().language)+ }+ }++ @Test+ fun resolve_falls_back_to_plugin_name_title() { runBlocking {+ val plugin = provider(+ "function resolve(a){ return JSON.stringify({streamUrl:'https://cdn.example/s.m3u8'}); }",+ name = "Nebula",+ )+ assertEquals("Nebula", plugin.resolve(550, MediaType.MOVIE).title)+ }+ }++ @Test+ fun resolve_blank_url_errors_with_plugin_name() { runBlocking {+ val plugin = provider("function resolve(a){ return JSON.stringify({streamUrl:''}); }")+ val failure = assertFailsWith<IllegalStateException> {+ plugin.resolve(550, MediaType.MOVIE)+ }+ assertTrue(failure.message!!.startsWith("'Test'"), failure.message)+ }+ }++ @Test+ fun resolve_malformed_json_errors() { runBlocking {+ val plugin = provider("function resolve(a){ return 'not json'; }")+ assertFailsWith<IllegalStateException> { plugin.resolve(550, MediaType.MOVIE) }+ }+ }++ @Test+ fun servers_lists_names() { runBlocking {+ val plugin = provider("function servers(){ return '[\"Nebula\", \"Lisbon\", \"\"]'; }")+ assertEquals(listOf("Nebula", "Lisbon"), plugin.servers())+ }+ }++ @Test+ fun alternates_failure_returns_empty() { runBlocking {+ val plugin = provider(+ "function resolve(a){ return JSON.stringify({streamUrl:'https://cdn.example/s.m3u8'}); }",+ )+ assertEquals(emptyList(), plugin.alternates(550, MediaType.MOVIE))+ }+ }++ @Test+ fun resolve_selects_url_from_episode_args() { runBlocking {+ val plugin = provider(+ "function resolve(a){ " ++ "return JSON.stringify({streamUrl:'https://cdn.example/' + a.season + 'x' + a.episode + '.m3u8'}); }",+ )+ val out = plugin.resolve(1396, MediaType.TV, season = 1, episode = 2)+ assertEquals("https://cdn.example/1x2.m3u8", out.streamUrl)+ }+ }++ @Test+ fun registry_serves_js_then_falls_back() { runBlocking {+ val failing = provider("function resolve(a){ throw new Error('nope'); }", name = "Js")+ val good = provider(+ "function resolve(a){ return JSON.stringify({streamUrl:'https://ok.example/s.m3u8'}); }",+ name = "JsGood",+ )+ val registry = com.vayunmathur.uniflix.domain.PluginRegistry(+ listOf("js-1" to failing, "js-2" to good),+ )+ val result = registry.resolve(550, MediaType.MOVIE)+ assertIs<com.vayunmathur.uniflix.domain.ResolutionResult.Success>(result)+ assertEquals("https://ok.example/s.m3u8", result.source.streamUrl)+ assertEquals("js-2", result.addonId)+ }+ }+}
uniflix/src/test/java/com/vayunmathur/uniflix/domain/JsPluginManifestTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/JsPluginManifestTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/JsPluginManifestTest.ktnew file mode 100644index 0000000000..94b1584c2a--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/JsPluginManifestTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.uniflix.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertNull++private fun plugin(+ header: String = "// @uniflix-plugin id=test.plugin name=\"Test Plugin\" version=1.0.0",+ body: String = "function resolve(a){return '{}';}\nfunction servers(){return '[]';}",+ wasmBase64: String? = null,+): String = buildString {+ appendLine(header)+ if (wasmBase64 != null) {+ appendLine("// @uniflix-wasm-begin")+ appendLine("// $wasmBase64")+ appendLine("// @uniflix-wasm-end")+ }+ append(body)+}++/** Plugin file parsing: header identity, wasm section, size cap. */+class JsPluginManifestTest {++ @Test+ fun parses_valid_header() {+ val manifest = JsPluginManifest.parse(plugin())+ assertEquals("test.plugin", manifest.id)+ assertEquals("Test Plugin", manifest.name)+ assertEquals("1.0.0", manifest.version)+ assertNull(manifest.wasmBytes)+ }++ @Test+ fun parses_unquoted_header_fields() {+ val manifest = JsPluginManifest.parse(+ plugin(header = "// @uniflix-plugin id=nebula name=Nebula version=2.1"),+ )+ assertEquals("nebula", manifest.id)+ assertEquals("Nebula", manifest.name)+ assertEquals("2.1", manifest.version)+ }++ @Test+ fun rejects_missing_header() {+ assertFailsWith<ManifestError.Parse> {+ JsPluginManifest.parse("function resolve(a){return '{}';}")+ }+ }++ @Test+ fun rejects_missing_id() {+ assertFailsWith<ManifestError.Parse> {+ JsPluginManifest.parse(+ plugin(header = "// @uniflix-plugin name=Nope version=1.0"),+ )+ }+ }++ @Test+ fun rejects_bad_id_characters() {+ assertFailsWith<ManifestError.Parse> {+ JsPluginManifest.parse(+ plugin(header = "// @uniflix-plugin id=BAD_ID! name=Bad version=1.0"),+ )+ }+ }++ @Test+ fun rejects_oversize_file() {+ val big = "// @uniflix-plugin id=big name=Big version=1.0\n" + "x".repeat(JS_PLUGIN_MAX_CHARS)+ assertFailsWith<ManifestError.Parse> { JsPluginManifest.parse(big) }+ }++ @Test+ fun parses_wasm_section() {+ val wasm = byteArrayOf(0x00, 0x61, 0x73.toByte(), 0x6D)+ val base64 = java.util.Base64.getEncoder().encodeToString(wasm)+ val manifest = JsPluginManifest.parse(plugin(wasmBase64 = base64))+ assertNotNull(manifest.wasmBytes)+ assertEquals(wasm.toList(), manifest.wasmBytes!!.toList())+ }++ @Test+ fun rejects_unterminated_wasm_section() {+ val source = "// @uniflix-plugin id=w name=W version=1.0\n// @uniflix-wasm-begin\n// aGVsbG8=\nresolve();"+ assertFailsWith<ManifestError.Parse> { JsPluginManifest.parse(source) }+ }++ @Test+ fun rejects_invalid_wasm_base64() {+ val source = plugin(wasmBase64 = "!!!not-base64!!!")+ assertFailsWith<ManifestError.Parse> { JsPluginManifest.parse(source) }+ }+}
uniflix/src/test/java/com/vayunmathur/uniflix/domain/PluginRegistryTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/PluginRegistryTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/PluginRegistryTest.ktindex af2f5ce514..1671b139dc 100644--- a/uniflix/src/test/java/com/vayunmathur/uniflix/domain/PluginRegistryTest.kt+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/domain/PluginRegistryTest.kt@@ -133,4 +133,5 @@ class PluginRegistryTest { registry.resolve(550, MediaType.MOVIE) assertEquals(listOf("addon-2", "addon-1"), seen, "lower priority resolves first") }+ } }