Modern Apps git

← Modern-Apps.git

uniflix: new app

Commit
cbfe52ea9d317b733dbfc73a47b9f96d4c43260f
Author
vayun-mathur <[email protected]>
When
2026-10-21 20:02 UTC (1 month ago)
Parents
30d6ad9

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 3ce68af828..06a81f5b85 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -66,6 +66,7 @@ body:         - travel         - tuner         - unblockjam+        - uniflix         - updater         - vpn         - watch
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 2141231dba..29ea123f3c 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -66,6 +66,7 @@ body:         - travel         - tuner         - unblockjam+        - uniflix         - updater         - vpn         - watch
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex ad8050c27a..8b4e771136 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'uniflix', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
README.md
diff --git a/README.md b/README.mdindex ea759b76cc..078e63d292 100644--- a/README.md+++ b/README.md@@ -90,6 +90,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Translate** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/translate) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.translate/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Translate&packageName=com.vayunmathur.translate&apk=translate-release.apk) | | **Travel** | MA-E | [Homepage](https://ma.vayunmathur.com/apps/travel) | In Progress | In Progress | | **Tuner** | MA-3 | [Homepage](https://ma.vayunmathur.com/apps/tuner) | In Progress | In Progress |+| **Uniflix** | MA-1 | [Homepage](https://ma.vayunmathur.com/apps/uniflix) | In Progress | In Progress | | **VPN** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/vpn) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.vpn/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=VPN&packageName=com.vayunmathur.vpn&apk=vpn-release.apk) | | **Watch** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/watch) | In Progress | In Progress | | **Weather** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/weather) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.weather) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Weather&packageName=com.vayunmathur.weather&apk=weather-release.apk) |
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex df0c5c053c..05e650a69b 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -60,6 +60,7 @@ include(":photos") include(":health") include(":youpipe") include(":youpipe:extractor")+include(":uniflix") include(":findfamily") include(":maps") include(":games:chess")
uniflix/AGENTS.md
diff --git a/uniflix/AGENTS.md b/uniflix/AGENTS.mdnew file mode 100644index 0000000000..90ae52cf93--- /dev/null+++ b/uniflix/AGENTS.md@@ -0,0 +1,61 @@+# AGENTS.md — uniflix/ (':uniflix')++> 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 -->+- 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+- Metadata: metadata_data/uniflix.md (present)+- Rust: no / screenshotTest: no (previews pending)++## Overview+**Purpose:** TMDB catalog browser (trending/top-rated/search, watchlist, lists,+resume) with playback supplied by user-installed Stremio-style URL addons. Ships+with no provider and no secrets — with zero addons the app is catalog-only and+Watch/Detail link to the addon manager.+**Key features:**+- 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.+**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+- Private `personal/uniflix/` keeps the native Strem provider + hardcoded TMDB key — never copy those into `uniflix/`++## Key files+### Root — entry + navigation+- com/vayunmathur/uniflix/MainActivity.kt+- com/vayunmathur/uniflix/Navigation.kt+- com/vayunmathur/uniflix/Route.kt+### domain/ — pure addon protocol + resolution order (no Android)+- com/vayunmathur/uniflix/domain/StreamProvider.kt — player contract both plugin kinds implement+- 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/data/AddonStreamProvider.kt — URL addon 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/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+### platform/ — ViewModels+- com/vayunmathur/uniflix/platform/DetailViewModel.kt — registry injection + RegistryFactory+- com/vayunmathur/uniflix/platform/AddonsViewModel.kt — manager state+### ui/ — catalog + manager+- com/vayunmathur/uniflix/ui/AddonsScreen.kt — manager list+- com/vayunmathur/uniflix/ui/AddonDetailScreen.kt — per-addon settings+- com/vayunmathur/uniflix/ui/dialogs/AddAddonDialog.kt — add-by-URL++## Verify (this module only)+```+./gradlew :uniflix:compileDevKotlin+./gradlew :uniflix:lint+./gradlew :uniflix:checkMetadata+```
uniflix/build.gradle.kts
diff --git a/uniflix/build.gradle.kts b/uniflix/build.gradle.ktsnew file mode 100644index 0000000000..02d6ae4218--- /dev/null+++ b/uniflix/build.gradle.kts@@ -0,0 +1,26 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "movie"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.uniflix"+    }+}++dependencies {+    implementation(project(":library:network"))+    implementation(project(":library:image"))+    implementRoom(libs)+    implementation(project(":library:room"))+    implementation(libs.androidx.media3.exoplayer)+    implementation(libs.androidx.media3.exoplayer.hls)+    implementation(libs.androidx.media3.ui.compose.material3)+    implementation(libs.androidx.datastore.preferences)+}
uniflix/src/main/AndroidManifest.xml
diff --git a/uniflix/src/main/AndroidManifest.xml b/uniflix/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..bf5a7ac179--- /dev/null+++ b/uniflix/src/main/AndroidManifest.xml@@ -0,0 +1,28 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:launchMode="singleTask"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>++</manifest>
uniflix/src/main/java/com/vayunmathur/uniflix/MainActivity.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/MainActivity.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/MainActivity.ktnew file mode 100644index 0000000000..bbc7e72874--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/MainActivity.kt@@ -0,0 +1,23 @@+package com.vayunmathur.uniflix++import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.uniflix.platform.SettingsViewModel++class MainActivity : MaActivity() {+    private val settingsViewModel: SettingsViewModel by viewModels()++    override fun onCreateBeforeContent() {+        // Public catalog + artwork hosts only. The player itself streams+        // user-supplied URLs; trust stays at STANDARD, never SYSTEM.+        NetworkClient.init(this, TrustBundle.STANDARD)+    }++    @Composable+    override fun Content() {+        Navigation(settingsViewModel)+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/Navigation.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/Navigation.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/Navigation.ktnew file mode 100644index 0000000000..5e64473634--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/Navigation.kt@@ -0,0 +1,197 @@+package com.vayunmathur.uniflix++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.util.FullscreenPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.AddonsViewModel+import com.vayunmathur.uniflix.platform.BrowseViewModel+import com.vayunmathur.uniflix.platform.DetailViewModel+import com.vayunmathur.uniflix.platform.HomeViewModel+import com.vayunmathur.uniflix.platform.ListsViewModel+import com.vayunmathur.uniflix.platform.SearchViewModel+import com.vayunmathur.uniflix.platform.SettingsViewModel+import com.vayunmathur.uniflix.ui.AddonDetailScreen+import com.vayunmathur.uniflix.ui.AddonsScreen+import com.vayunmathur.uniflix.ui.ContinueWatchingScreen+import com.vayunmathur.uniflix.ui.DetailScreen+import com.vayunmathur.uniflix.ui.HomeScreen+import com.vayunmathur.uniflix.ui.ListsScreen+import com.vayunmathur.uniflix.ui.MediaGridScreen+import com.vayunmathur.uniflix.ui.OnboardingScreen+import com.vayunmathur.uniflix.ui.PlayerSettingsScreen+import com.vayunmathur.uniflix.ui.SearchScreen+import com.vayunmathur.uniflix.ui.WatchScreen++private fun mediaTypeOf(raw: String): MediaType =+    if (raw == "tv") MediaType.TV else MediaType.MOVIE++@Composable+fun Navigation(settingsViewModel: SettingsViewModel) {+    val settings = settingsViewModel.state+    val start = if (settings.onboarded) Route.Home else Route.Onboarding+    val backStack = rememberNavBackStack<Route>(start)++    // Onboarding ends because the settings now hold a TMDB key, not because anything+    // navigated - so the stack follows the flag rather than the other way round. reset()+    // rather than add(): there is no going back to onboarding once a key exists.+    LaunchedEffect(settings.onboarded) {+        if (backStack.last() != start) backStack.reset(start)+    }++    MainNavigation(backStack) {+        entry<Route.Onboarding> {+            OnboardingScreen(+                draftKey = settings.draftKey,+                saving = settings.saving,+                onDraftChange = settingsViewModel::onDraftChange,+                onSave = settingsViewModel::saveKey,+            )+        }+        entry<Route.Home> {+            val vm: HomeViewModel = viewModel()+            HomeScreen(+                state = vm.state,+                onRefresh = { vm.refresh() },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+                onOpenSearch = { backStack.add(Route.Search) },+                onOpenMovies = { backStack.add(Route.Movies) },+                onOpenSeries = { backStack.add(Route.Series) },+                onOpenLists = { backStack.add(Route.Lists) },+                onOpenContinue = { backStack.add(Route.ContinueWatching) },+                onOpenAddons = { backStack.add(Route.Addons) },+            )+        }+        entry<Route.Movies> {+            val vm: BrowseViewModel = viewModel()+            LaunchedEffect(Unit) { vm.loadMovies() }+            MediaGridScreen(+                title = "Movies",+                loading = vm.movies.loading,+                items = vm.movies.items,+                onBack = { backStack.pop() },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+            )+        }+        entry<Route.Series> {+            val vm: BrowseViewModel = viewModel()+            LaunchedEffect(Unit) { vm.loadSeries() }+            MediaGridScreen(+                title = "Series",+                loading = vm.series.loading,+                items = vm.series.items,+                onBack = { backStack.pop() },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+            )+        }+        entry<Route.Search> {+            val vm: SearchViewModel = viewModel()+            SearchScreen(+                state = vm.state,+                onQueryChange = vm::onQueryChange,+                onBack = { backStack.pop() },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+            )+        }+        entry<Route.Detail> { route ->+            val vm: DetailViewModel = viewModel()+            val type = mediaTypeOf(route.mediaType)+            LaunchedEffect(route.tmdbId, route.mediaType) { vm.load(type, route.tmdbId) }+            DetailScreen(+                state = vm.state,+                onBack = { backStack.pop() },+                onSeasonChange = { season -> vm.selectSeason(type, route.tmdbId, season) },+                onToggleWatchlist = vm::toggleWatchlist,+                onPlay = { season, episode ->+                    backStack.add(Route.Watch(route.mediaType, route.tmdbId, season, episode))+                },+                onResolve = { season, episode -> vm.resolve(type, route.tmdbId, season, episode) },+                onAddNote = { body, score -> vm.addNote(type, route.tmdbId, body, score) },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+                onOpenAddons = { backStack.add(Route.Addons) },+            )+        }+        entry<Route.Watch>(metadata = FullscreenPage()) { route ->+            val vm: DetailViewModel = viewModel()+            val type = mediaTypeOf(route.mediaType)+            var startPositionMs by remember(route.tmdbId, route.season, route.episode) {+                mutableLongStateOf(0L)+            }+            LaunchedEffect(route.tmdbId, route.season, route.episode) {+                vm.load(type, route.tmdbId)+                vm.loadServers()+                startPositionMs = vm.startPosition(type, route.tmdbId, route.season, route.episode)+                vm.resolve(type, route.tmdbId, route.season, route.episode)+            }+            WatchScreen(+                state = vm.state.copy(startPositionMs = startPositionMs),+                mediaType = type,+                season = route.season,+                episode = route.episode,+                onBack = { backStack.pop() },+                onRetry = { vm.resolve(type, route.tmdbId, route.season, route.episode) },+                onOpenAddons = { backStack.add(Route.Addons) },+                onSelectServer = { server ->+                    vm.selectServer(type, route.tmdbId, route.season, route.episode, server)+                },+                onSavePosition = { positionMs, durationMs ->+                    val detail = vm.state.detail ?: return@WatchScreen+                    vm.savePosition(+                        type, route.tmdbId, detail.title, detail.posterPath,+                        route.season, route.episode, positionMs, durationMs,+                    )+                },+            )+        }+        entry<Route.Lists> {+            val vm: ListsViewModel = viewModel()+            ListsScreen(+                onBack = { backStack.pop() },+                onOpenDetail = { item ->+                    backStack.add(Route.Detail(item.mediaType.name.lowercase(), item.tmdbId))+                },+            )+        }+        entry<Route.ContinueWatching> {+            ContinueWatchingScreen(+                onBack = { backStack.pop() },+                onResume = { entry ->+                    backStack.add(Route.Watch(entry.mediaType, entry.tmdbId, entry.season, entry.episode))+                },+            )+        }+        entry<Route.PlayerSettings> {+            PlayerSettingsScreen(onBack = { backStack.pop() })+        }+        entry<Route.Addons> {+            val vm: AddonsViewModel = viewModel()+            AddonsScreen(+                onBack = { backStack.pop() },+                onOpenDetail = { dbId -> backStack.add(Route.AddonDetail(dbId)) },+            )+        }+        entry<Route.AddonDetail> { route ->+            AddonDetailScreen(+                addonDbId = route.addonDbId,+                onBack = { backStack.pop() },+            )+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/Route.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/Route.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/Route.ktnew file mode 100644index 0000000000..e21df03695--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/Route.kt@@ -0,0 +1,43 @@+package com.vayunmathur.uniflix++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Onboarding : Route++    @Serializable+    data object Home : Route++    @Serializable+    data object Movies : Route++    @Serializable+    data object Series : Route++    @Serializable+    data object Search : Route++    @Serializable+    data class Detail(val mediaType: String, val tmdbId: Int) : Route++    @Serializable+    data class Watch(val mediaType: String, val tmdbId: Int, val season: Int = 0, val episode: Int = 0) : Route++    @Serializable+    data object Lists : Route++    @Serializable+    data object ContinueWatching : Route++    @Serializable+    data object PlayerSettings : Route++    @Serializable+    data object Addons : Route++    @Serializable+    data class AddonDetail(val addonDbId: Long) : Route+}
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.ktnew file mode 100644index 0000000000..6985e92a9a--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonEntity.kt@@ -0,0 +1,63 @@+package com.vayunmathur.uniflix.data++import androidx.room3.Dao+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.Upsert+import kotlinx.coroutines.flow.Flow++/** One installed URL addon: its manifest identity, placement, and last-known health. */+@Entity+data class AddonEntity(+    @PrimaryKey(autoGenerate = true) val dbId: Long = 0L,+    val manifestUrl: String,+    val baseUrl: String,+    val addonId: String,+    val name: String,+    val version: String = "",+    val enabled: Boolean = true,+    /** Lower resolves first; ties broken by install order. */+    val priority: Int = 0,+    /** Per-addon settings JSON (opaque key-values, edited in the addon detail screen). */+    val configJson: String = "{}",+    /** Last fetch/resolve failure, shown as a badge; null when healthy. */+    val lastError: String? = null,+    val updatedAt: Long = 0L,+)++@Dao+interface AddonDao {+    @Query("SELECT * FROM AddonEntity ORDER BY priority ASC, dbId ASC")+    fun observeAllOrdered(): Flow<List<AddonEntity>>++    @Query("SELECT * FROM AddonEntity WHERE enabled = 1 ORDER BY priority ASC, dbId ASC")+    fun observeEnabledOrdered(): Flow<List<AddonEntity>>++    @Query("SELECT * FROM AddonEntity WHERE dbId = :dbId")+    suspend fun getById(dbId: Long): AddonEntity?++    @Query("SELECT * FROM AddonEntity WHERE manifestUrl = :manifestUrl")+    suspend fun getByManifestUrl(manifestUrl: String): AddonEntity?++    @Query("SELECT COUNT(*) FROM AddonEntity")+    suspend fun count(): Int++    @Upsert+    suspend fun upsert(value: AddonEntity): Long++    @Query("DELETE FROM AddonEntity WHERE dbId = :dbId")+    suspend fun deleteById(dbId: Long)++    @Query("UPDATE AddonEntity SET enabled = :enabled WHERE dbId = :dbId")+    suspend fun setEnabled(dbId: Long, enabled: Boolean)++    @Query("UPDATE AddonEntity SET priority = :priority WHERE dbId = :dbId")+    suspend fun setPriority(dbId: Long, priority: Int)++    @Query("UPDATE AddonEntity SET lastError = :error WHERE dbId = :dbId")+    suspend fun setError(dbId: Long, error: String?)++    @Query("UPDATE AddonEntity SET configJson = :config WHERE dbId = :dbId")+    suspend fun setConfig(dbId: Long, config: String)+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonPrefs.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonPrefs.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonPrefs.ktnew file mode 100644index 0000000000..94f7fe53f9--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonPrefs.kt@@ -0,0 +1,29 @@+package com.vayunmathur.uniflix.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.uniflixAddonStore by preferencesDataStore(name = "uniflix_addons")++/**+ * Addon selection state. Ordering lives in Room ([AddonEntity.priority]);+ * only the default addon id lives here (null = first enabled wins).+ */+class AddonPrefs(private val context: Context) {+    val defaultAddonDbId: Flow<Long?> =+        context.uniflixAddonStore.data.map { it[KEY_DEFAULT_ADDON] }++    suspend fun setDefaultAddonDbId(dbId: Long?) {+        context.uniflixAddonStore.edit {+            if (dbId == null) it.remove(KEY_DEFAULT_ADDON) else it[KEY_DEFAULT_ADDON] = dbId+        }+    }++    companion object {+        private val KEY_DEFAULT_ADDON = longPreferencesKey("default_addon_db_id")+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonStreamProvider.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonStreamProvider.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonStreamProvider.ktnew file mode 100644index 0000000000..60b6ff7d6f--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/AddonStreamProvider.kt@@ -0,0 +1,139 @@+package com.vayunmathur.uniflix.data++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.uniflix.domain.AddonManifest+import com.vayunmathur.uniflix.domain.AddonStreamsResponse+import com.vayunmathur.uniflix.domain.ManifestError+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.StreamProvider+import com.vayunmathur.uniflix.domain.VideoSource+import com.vayunmathur.uniflix.domain.addonResourceType+import com.vayunmathur.uniflix.domain.addonStreamId+import kotlinx.serialization.json.Json++private const val ADDON_TIMEOUT_MS = 15_000L+private const val ERROR_PREVIEW_CHARS = 120++/**+ * A user-installed URL addon (Stremio-style) as a [StreamProvider].+ *+ * Third parties publish a `manifest.json` over HTTPS; Uniflix fetches it once+ * at install/refresh (see [fetchManifest]) and resolves streams via+ * `GET {base}/stream/{type}/{id}.json`. No fork of Uniflix is needed to add one.+ *+ * The provider holds only the base URL + display name, so playback never+ * re-fetches the manifest — validation happens once at install time.+ */+class AddonStreamProvider(+    val baseUrl: String,+    val displayName: String,+) : StreamProvider() {+    override val name: String get() = displayName+    override val supports4k: Boolean = false++    private val json = Json { ignoreUnknownKeys = true }++    override suspend fun resolve(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int,+        episode: Int,+        server: String?,+    ): VideoSource =+        fetchStreams(tmdbId, mediaType, season, episode).firstOrNull()+            ?: error("Addon '$displayName' has no streams for this title")++    override suspend fun alternates(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int,+        episode: Int,+    ): List<VideoSource> =+        fetchStreams(tmdbId, mediaType, season, episode).drop(1)++    private suspend fun fetchStreams(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int,+        episode: Int,+    ): List<VideoSource> {+        val url = "$baseUrl/stream/${addonResourceType(mediaType)}/${addonStreamId(tmdbId, mediaType, season, episode)}.json"+        val resp = runCatching {+            NetworkClient.execute(url, connectTimeoutMs = ADDON_TIMEOUT_MS)+        }.getOrElse {+            error("Addon '$displayName' unreachable: ${it.message}")+        }+        if (!resp.isSuccess) {+            error("Addon '$displayName' returned ${resp.status}: ${resp.text.take(ERROR_PREVIEW_CHARS)}")+        }+        val parsed = runCatching {+            json.decodeFromString(AddonStreamsResponse.serializer(), resp.text)+        }.getOrElse {+            error("Addon '$displayName' returned malformed streams: ${it.message}")+        }+        return parsed.streams.mapNotNull { it.toVideoSource(displayName) }+    }++    companion object {+        private val manifestJson = Json { ignoreUnknownKeys = true }++        /** Fetches and validates the manifest at [manifestUrl] (bare base or full `.../manifest.json`). */+        suspend fun fetchManifest(manifestUrl: String): Pair<String, AddonManifest> {+            val base = normalizeBaseUrl(manifestUrl)+            val resp = runCatching {+                NetworkClient.execute("$base/manifest.json", connectTimeoutMs = ADDON_TIMEOUT_MS)+            }.getOrElse {+                throw ManifestError.Network("Could not reach $manifestUrl: ${it.message}")+            }+            if (!resp.isSuccess) {+                throw ManifestError.Network("Manifest request failed: ${resp.status}")+            }+            val manifest = runCatching {+                manifestJson.decodeFromString(AddonManifest.serializer(), resp.text).validate()+            }.getOrElse {+                if (it is ManifestError) throw it+                throw ManifestError.Parse("Not a stream addon manifest: ${it.message}", it)+            }+            return base to manifest+        }++        /**+         * Normalizes user input to a bare base URL. Accepts a full manifest URL+         * or a bare host; enforces HTTPS except loopback/private (dev addons).+         */+        fun normalizeBaseUrl(input: String): String {+            val trimmed = input.trim().trimEnd('/')+            val withoutManifest = trimmed.removeSuffix("/manifest.json")+            val withScheme = if ("://" in withoutManifest) withoutManifest else "https://$withoutManifest"+            val uri = runCatching { java.net.URI(withScheme) }.getOrNull()+                ?: throw ManifestError.Parse("Not a valid addon URL: $input")+            val scheme = uri.scheme?.lowercase()+            val host = uri.host?.lowercase()+                ?: throw ManifestError.Parse("Not a valid addon URL: $input")+            if (scheme == "http" && !isLoopbackOrPrivate(host)) {+                throw ManifestError.InsecureUrl(input.trim())+            }+            if (scheme != "http" && scheme != "https") {+                throw ManifestError.Parse("Addon URL must be http(s): $input")+            }+            return "$scheme://$host${if (uri.port != -1) ":${uri.port}" else ""}${uri.path.trimEnd('/')}"+        }++        private fun isLoopbackOrPrivate(host: String): Boolean {+            if (host == "localhost" || host.endsWith(".localhost")) return true+            // Literal IPs only: resolving a DNS name here would do network I/O+            // on the caller's thread (main, from the manager UI). Non-IP http+            // hosts stay rejected as insecure — use https or a literal IP.+            if (!isLiteralIp(host)) return false+            val addr = runCatching { java.net.InetAddress.getByName(host) }.getOrNull() ?: return false+            return addr.isLoopbackAddress || addr.isSiteLocalAddress+        }++        private fun isLiteralIp(host: String): Boolean {+            val cleaned = host.removePrefix("[").removeSuffix("]")+            if (cleaned.contains(':')) return true // IPv6 literal+            val parts = cleaned.split('.')+            return parts.size == 4 && parts.all { it.toIntOrNull() in 0..255 }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.ktnew file mode 100644index 0000000000..6709df0a1d--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbApi.kt@@ -0,0 +1,189 @@+package com.vayunmathur.uniflix.data++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.uniflix.domain.Episode+import com.vayunmathur.uniflix.domain.MediaDetail+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.SeasonSummary+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** Public TMDB v3 catalog client. Key is injected per call, never stored here. */+class TmdbApi {+    private val json = Json { ignoreUnknownKeys = true }++    private fun url(path: String, apiKey: String, extra: String = ""): String {+        val params = "language=en-US&include_adult=false&api_key=$apiKey"+        val suffix = if (extra.isEmpty()) "" else "&$extra"+        return "$BASE$path?$params$suffix"+    }++    private suspend fun getItems(requestUrl: String): List<MediaItem> {+        val resp = NetworkClient.execute(requestUrl)+        if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")+        return json.decodeFromString(TmdbList.serializer(), resp.text).results.map { it.toMediaItem() }+    }++    suspend fun trendingMovies(apiKey: String): List<MediaItem> =+        getItems(url("/trending/movie/day", apiKey))++    suspend fun trendingTv(apiKey: String): List<MediaItem> =+        getItems(url("/trending/tv/day", apiKey))++    suspend fun topRatedMovies(apiKey: String): List<MediaItem> =+        getItems(url("/movie/top_rated", apiKey, "page=1"))++    suspend fun topRatedTv(apiKey: String): List<MediaItem> =+        getItems(url("/tv/top_rated", apiKey, "page=1"))++    suspend fun discoverMovies(apiKey: String): List<MediaItem> =+        getItems(url("/discover/movie", apiKey, "page=1"))++    suspend fun discoverTv(apiKey: String): List<MediaItem> =+        getItems(url("/discover/tv", apiKey, "page=1"))++    suspend fun search(apiKey: String, query: String): List<MediaItem> {+        val encoded = java.net.URLEncoder.encode(query, Charsets.UTF_8.name())+        return getItems(url("/search/multi", apiKey, "query=$encoded&page=1"))+    }++    suspend fun movieDetail(apiKey: String, tmdbId: Int): MediaDetail {+        val requestUrl = url(+            "/movie/$tmdbId",+            apiKey,+            "append_to_response=release_dates,images,credits,videos,external_ids",+        )+        val resp = NetworkClient.execute(requestUrl)+        if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")+        val dto = json.decodeFromString(TmdbMovieDetail.serializer(), resp.text)+        val recs = runCatching { movieRecommendations(apiKey, tmdbId) }.getOrDefault(emptyList())+        return MediaDetail(+            tmdbId = dto.id,+            mediaType = MediaType.MOVIE,+            title = dto.title,+            year = dto.releaseDate?.take(4)?.toIntOrNull(),+            overview = dto.overview,+            posterPath = dto.posterPath,+            backdropPath = dto.backdropPath,+            voteAverage = dto.voteAverage,+            runtimeMinutes = dto.runtime,+            recommendations = recs,+        )+    }++    suspend fun tvDetail(apiKey: String, tmdbId: Int): MediaDetail {+        val requestUrl = url(+            "/tv/$tmdbId",+            apiKey,+            "append_to_response=content_ratings,images,credits,seasons,external_ids",+        )+        val resp = NetworkClient.execute(requestUrl)+        if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")+        val dto = json.decodeFromString(TmdbTvDetail.serializer(), resp.text)+        return MediaDetail(+            tmdbId = dto.id,+            mediaType = MediaType.TV,+            title = dto.name,+            year = dto.firstAirDate?.take(4)?.toIntOrNull(),+            overview = dto.overview,+            posterPath = dto.posterPath,+            backdropPath = dto.backdropPath,+            voteAverage = dto.voteAverage,+            seasons = dto.seasons.map {+                SeasonSummary(it.seasonNumber, it.name, it.episodeCount, it.posterPath)+            },+        )+    }++    suspend fun seasonEpisodes(apiKey: String, tmdbId: Int, season: Int): List<Episode> {+        val resp = NetworkClient.execute(url("/tv/$tmdbId/season/$season", apiKey))+        if (!resp.isSuccess) error("TMDB request failed: ${resp.status}")+        return json.decodeFromString(TmdbSeason.serializer(), resp.text).episodes.map {+            Episode(season, it.episodeNumber, it.name, it.overview, it.stillPath)+        }+    }++    private suspend fun movieRecommendations(apiKey: String, tmdbId: Int): List<MediaItem> =+        getItems(url("/movie/$tmdbId/recommendations", apiKey, "page=1"))++    companion object {+        private const val BASE = "https://api.themoviedb.org/3"+    }+}++@Serializable+private data class TmdbList(val results: List<TmdbItem> = emptyList())++@Serializable+private data class TmdbItem(+    val id: Int,+    @SerialName("media_type") val mediaType: String? = null,+    val title: String? = null,+    val name: String? = null,+    @SerialName("release_date") val releaseDate: String? = null,+    @SerialName("first_air_date") val firstAirDate: String? = null,+    val overview: String = "",+    @SerialName("poster_path") val posterPath: String? = null,+    @SerialName("backdrop_path") val backdropPath: String? = null,+    @SerialName("vote_average") val voteAverage: Double = 0.0,+) {+    fun toMediaItem(): MediaItem {+        val type = if (mediaType == "tv") MediaType.TV else MediaType.MOVIE+        val date = releaseDate ?: firstAirDate+        return MediaItem(+            tmdbId = id,+            mediaType = type,+            title = title ?: name ?: "",+            year = date?.take(4)?.toIntOrNull(),+            overview = overview,+            posterPath = posterPath,+            backdropPath = backdropPath,+            voteAverage = voteAverage,+        )+    }+}++@Serializable+private data class TmdbMovieDetail(+    val id: Int,+    val title: String,+    @SerialName("release_date") val releaseDate: String? = null,+    val overview: String = "",+    @SerialName("poster_path") val posterPath: String? = null,+    @SerialName("backdrop_path") val backdropPath: String? = null,+    @SerialName("vote_average") val voteAverage: Double = 0.0,+    val runtime: Int? = null,+)++@Serializable+private data class TmdbTvDetail(+    val id: Int,+    val name: String,+    @SerialName("first_air_date") val firstAirDate: String? = null,+    val overview: String = "",+    @SerialName("poster_path") val posterPath: String? = null,+    @SerialName("backdrop_path") val backdropPath: String? = null,+    @SerialName("vote_average") val voteAverage: Double = 0.0,+    val seasons: List<TmdbSeasonSummary> = emptyList(),+)++@Serializable+private data class TmdbSeasonSummary(+    @SerialName("season_number") val seasonNumber: Int,+    val name: String,+    @SerialName("episode_count") val episodeCount: Int = 0,+    @SerialName("poster_path") val posterPath: String? = null,+)++@Serializable+private data class TmdbSeason(val episodes: List<TmdbEpisode> = emptyList())++@Serializable+private data class TmdbEpisode(+    @SerialName("episode_number") val episodeNumber: Int,+    val name: String,+    val overview: String = "",+    @SerialName("still_path") val stillPath: String? = null,+)
uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.ktnew file mode 100644index 0000000000..e472316c76--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbImageUrl.kt@@ -0,0 +1,15 @@+package com.vayunmathur.uniflix.data++/** Direct TMDB image CDN URLs — no proxy, no key. Sizes: w185/w342 cards, w500 search, original hero. */+object TmdbImageUrl {+    private const val BASE = "https://image.tmdb.org/t/p/"++    fun poster(path: String?, size: String = "w342"): String? =+        path?.let { "$BASE$size$it" }++    fun backdrop(path: String?): String? =+        path?.let { "${BASE}original$it" }++    fun still(path: String?, size: String = "w185"): String? =+        path?.let { "$BASE$size$it" }+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbKeyStore.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbKeyStore.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbKeyStore.ktnew file mode 100644index 0000000000..5d3352e69c--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/TmdbKeyStore.kt@@ -0,0 +1,23 @@+package com.vayunmathur.uniflix.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.uniflixDataStore by preferencesDataStore(name = "uniflix_config")++/** TMDB API key storage. No default — the user supplies their own key at onboarding. */+class TmdbKeyStore(private val context: Context) {+    val apiKey: Flow<String> = context.uniflixDataStore.data.map { it[KEY_TMDB] ?: "" }++    suspend fun setApiKey(key: String) {+        context.uniflixDataStore.edit { it[KEY_TMDB] = key.trim() }+    }++    companion object {+        private val KEY_TMDB = stringPreferencesKey("tmdb_api_key")+    }+}
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.ktnew file mode 100644index 0000000000..b16e10090f--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt@@ -0,0 +1,179 @@+package com.vayunmathur.uniflix.data++import androidx.room3.ColumnTypeConverters+import androidx.room3.Dao+import androidx.room3.Database+import androidx.room3.Delete+import androidx.room3.Entity+import androidx.room3.PrimaryKey+import androidx.room3.Query+import androidx.room3.RoomDatabase+import androidx.room3.Upsert+import androidx.room3.migration.Migration+import androidx.sqlite.SQLiteConnection+import androidx.sqlite.execSQL+import com.vayunmathur.library.util.DefaultConverters+import kotlinx.coroutines.flow.Flow++/** A TMDB title saved to the watchlist. */+@Entity+data class WatchlistEntry(+    @PrimaryKey val key: String,+    val tmdbId: Int,+    val mediaType: String,+    val title: String,+    val posterPath: String?,+    val addedAt: Long,+)++/** Resume position per title (per episode for series). */+@Entity+data class ContinueWatchingEntry(+    @PrimaryKey val key: String,+    val tmdbId: Int,+    val mediaType: String,+    val title: String,+    val posterPath: String?,+    val season: Int = 0,+    val episode: Int = 0,+    val positionMs: Long = 0L,+    val durationMs: Long = 0L,+    val updatedAt: Long = 0L,+)++/** A user-created list. */+@Entity+data class UserList(+    @PrimaryKey(autoGenerate = true) val id: Long = 0L,+    val name: String,+    val createdAt: Long,+)++/** A TMDB title filed in a user list. */+@Entity+data class UserListItem(+    @PrimaryKey(autoGenerate = true) val id: Long = 0L,+    val listId: Long,+    val tmdbId: Int,+    val mediaType: String,+    val title: String,+    val posterPath: String?,+    val position: Int = 0,+)++/** A local note/comment on a title. */+@Entity+data class TitleNote(+    @PrimaryKey(autoGenerate = true) val id: Long = 0L,+    val tmdbId: Int,+    val mediaType: String,+    val body: String,+    val score: Int = 0,+    val createdAt: Long = 0L,+)++@Dao+interface WatchlistDao {+    @Query("SELECT * FROM WatchlistEntry ORDER BY addedAt DESC")+    fun getAllFlow(): Flow<List<WatchlistEntry>>++    @Query("SELECT * FROM WatchlistEntry WHERE `key` = :key")+    suspend fun getByKey(key: String): WatchlistEntry?++    @Upsert+    suspend fun upsert(value: WatchlistEntry)++    @Query("DELETE FROM WatchlistEntry WHERE `key` = :key")+    suspend fun deleteByKey(key: String)+}++@Dao+interface ContinueWatchingDao {+    @Query("SELECT * FROM ContinueWatchingEntry ORDER BY updatedAt DESC")+    fun getAllFlow(): Flow<List<ContinueWatchingEntry>>++    @Query("SELECT positionMs FROM ContinueWatchingEntry WHERE `key` = :key")+    suspend fun getPosition(key: String): Long?++    @Upsert+    suspend fun upsert(value: ContinueWatchingEntry)++    @Query("DELETE FROM ContinueWatchingEntry WHERE `key` = :key")+    suspend fun deleteByKey(key: String)+}++@Dao+interface UserListDao {+    @Query("SELECT * FROM UserList ORDER BY createdAt ASC")+    fun getListsFlow(): Flow<List<UserList>>++    @Query("SELECT * FROM UserListItem WHERE listId = :listId ORDER BY position ASC")+    fun getItemsFlow(listId: Long): Flow<List<UserListItem>>++    @Upsert+    suspend fun upsertList(value: UserList): Long++    @Upsert+    suspend fun upsertItem(value: UserListItem): Long++    @Delete+    suspend fun deleteList(value: UserList)++    @Delete+    suspend fun deleteItem(value: UserListItem)++    @Query("SELECT * FROM TitleNote WHERE tmdbId = :tmdbId AND mediaType = :mediaType ORDER BY createdAt DESC")+    fun getNotesFlow(tmdbId: Int, mediaType: String): Flow<List<TitleNote>>++    @Upsert+    suspend fun upsertNote(value: TitleNote): Long++    @Delete+    suspend fun deleteNote(value: TitleNote)+}++/** Local-only watch state: watchlist, resume positions, lists, notes. No server sync. */+@ColumnTypeConverters(DefaultConverters::class)+@Database(+    entities = [+        WatchlistEntry::class,+        ContinueWatchingEntry::class,+        UserList::class,+        UserListItem::class,+        TitleNote::class,+        AddonEntity::class,+    ],+    version = 2,+    exportSchema = false,+)+abstract class UniflixDatabase : RoomDatabase() {+    abstract fun watchlistDao(): WatchlistDao+    abstract fun continueWatchingDao(): ContinueWatchingDao+    abstract fun userListDao(): UserListDao+    abstract fun addonDao(): AddonDao++    companion object : com.vayunmathur.library.util.DatabaseMigrations {+        override val migrations = listOf(+            object : Migration(1, 2) {+                override suspend fun migrate(connection: SQLiteConnection) {+                    // v1 shipped only on personal/dev devices; addons are new in the+                    // public app, so the table starts empty on every upgrade.+                    connection.execSQL(+                        "CREATE TABLE IF NOT EXISTS AddonEntity (" ++                            "dbId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++                            "manifestUrl TEXT NOT NULL, " ++                            "baseUrl TEXT NOT NULL, " ++                            "addonId TEXT NOT NULL, " ++                            "name TEXT NOT NULL, " ++                            "version TEXT NOT NULL, " ++                            "enabled INTEGER NOT NULL, " ++                            "priority INTEGER NOT NULL, " ++                            "configJson TEXT NOT NULL, " ++                            "lastError TEXT, " ++                            "updatedAt INTEGER NOT NULL)"+                    )+                }+            },+        )+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.ktnew file mode 100644index 0000000000..6a25f56fd8--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt@@ -0,0 +1,77 @@+package com.vayunmathur.uniflix.data++import android.content.Context+import com.vayunmathur.library.room.RoomRepository+import kotlinx.coroutines.flow.Flow++/**+ * Single source of truth for Uniflix persisted state.+ *+ * Owns the one [UniflixDatabase] instance (via [RoomRepository]); ViewModels+ * read/write through here so they share one live view of the data.+ */+class UniflixRepository private constructor(context: Context) :+    RoomRepository<UniflixDatabase>(+        context,+        UniflixDatabase::class,+        "uniflix-db",+        migrations = UniflixDatabase.migrations,+    ) {++    private val watchlistDao: WatchlistDao get() = db.watchlistDao()+    private val continueDao: ContinueWatchingDao get() = db.continueWatchingDao()+    private val listDao: UserListDao get() = db.userListDao()+    private val addonDao: AddonDao get() = db.addonDao()++    val watchlist: Flow<List<WatchlistEntry>> get() = watchlistDao.getAllFlow()+    val continueWatching: Flow<List<ContinueWatchingEntry>> get() = continueDao.getAllFlow()+    val userLists: Flow<List<UserList>> get() = listDao.getListsFlow()++    fun listItems(listId: Long): Flow<List<UserListItem>> = listDao.getItemsFlow(listId)+    fun notesFor(tmdbId: Int, mediaType: String): Flow<List<TitleNote>> =+        listDao.getNotesFlow(tmdbId, mediaType)++    suspend fun isWatchlisted(key: String): Boolean = watchlistDao.getByKey(key) != null+    suspend fun upsertWatchlist(value: WatchlistEntry) = watchlistDao.upsert(value)+    suspend fun removeWatchlist(key: String) = watchlistDao.deleteByKey(key)++    suspend fun savePosition(value: ContinueWatchingEntry) = continueDao.upsert(value)+    suspend fun positionFor(key: String): Long = continueDao.getPosition(key) ?: 0L+    suspend fun clearPosition(key: String) = continueDao.deleteByKey(key)++    suspend fun upsertList(value: UserList): Long = listDao.upsertList(value)+    suspend fun upsertListItem(value: UserListItem): Long = listDao.upsertItem(value)+    suspend fun deleteList(value: UserList) = listDao.deleteList(value)+    suspend fun deleteListItem(value: UserListItem) = listDao.deleteItem(value)++    suspend fun upsertNote(value: TitleNote): Long = listDao.upsertNote(value)+    suspend fun deleteNote(value: TitleNote) = listDao.deleteNote(value)++    val addons: Flow<List<AddonEntity>> get() = addonDao.observeAllOrdered()+    val enabledAddons: Flow<List<AddonEntity>> get() = addonDao.observeEnabledOrdered()++    suspend fun upsertAddon(value: AddonEntity): Long = addonDao.upsert(value)+    suspend fun addonById(dbId: Long): AddonEntity? = addonDao.getById(dbId)+    suspend fun addonByManifestUrl(manifestUrl: String): AddonEntity? =+        addonDao.getByManifestUrl(manifestUrl)+    suspend fun addonCount(): Int = addonDao.count()+    suspend fun deleteAddon(dbId: Long) = addonDao.deleteById(dbId)+    suspend fun setAddonEnabled(dbId: Long, enabled: Boolean) = addonDao.setEnabled(dbId, enabled)+    suspend fun setAddonPriority(dbId: Long, priority: Int) = addonDao.setPriority(dbId, priority)+    suspend fun setAddonError(dbId: Long, error: String?) = addonDao.setError(dbId, error)+    suspend fun setAddonConfig(dbId: Long, config: String) = addonDao.setConfig(dbId, config)++    companion object {+        @Volatile+        private var instance: UniflixRepository? = null++        fun get(context: Context): UniflixRepository =+            instance ?: synchronized(this) {+                instance ?: UniflixRepository(context).also { instance = it }+            }+    }+}++/** Stable join key for a title (optionally a specific episode). */+fun watchKey(tmdbId: Int, mediaType: String, season: Int = 0, episode: Int = 0): String =+    "$mediaType:$tmdbId:$season:$episode"
uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonManifest.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonManifest.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonManifest.ktnew file mode 100644index 0000000000..0e6e4040d7--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonManifest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.uniflix.domain++import kotlinx.serialization.KSerializer+import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.descriptors.SerialDescriptor+import kotlinx.serialization.encoding.Decoder+import kotlinx.serialization.encoding.Encoder+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonDecoder+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.decodeFromJsonElement+import kotlinx.serialization.json.jsonPrimitive++/** Failures when adding or refreshing a URL addon, surfaced per-addon in the manager UI. */+sealed class ManifestError(message: String, cause: Throwable? = null) : Exception(message, cause) {+    /** Manifest is valid JSON but cannot supply streams (no stream resource / wrong types). */+    class Unsupported(message: String) : ManifestError(message)++    /** The manifest URL could not be fetched (DNS, timeout, non-2xx). */+    class Network(message: String) : ManifestError(message)++    /** The manifest URL returned something that is not a Stremio manifest. */+    class Parse(message: String, cause: Throwable? = null) : ManifestError(message, cause)++    /** Plain-http addon outside loopback/private networks — addons carry stream URLs, so no cleartext. */+    class InsecureUrl(url: String) : ManifestError("Refusing non-HTTPS addon URL: $url")+}++/** One entry of a Stremio manifest `resources` array (string or object form). */+@Serializable+data class AddonResource(+    val name: String,+    val types: List<String> = emptyList(),+    val idPrefixes: List<String> = emptyList(),+)++/** Accepts Stremio's string-or-object resource forms: `"stream"` or `{"name":"stream",...}`. */+object ResourceListSerializer : KSerializer<List<AddonResource>> {+    private val delegate = ListSerializer(AddonResource.serializer())++    override val descriptor: SerialDescriptor = delegate.descriptor++    override fun deserialize(decoder: Decoder): List<AddonResource> {+        require(decoder is JsonDecoder) { "Addon resources require a JSON manifest" }+        val array = decoder.decodeJsonElement() as? JsonArray ?: return emptyList()+        return array.mapNotNull { element ->+            when (element) {+                is JsonPrimitive -> element.jsonPrimitive.content.takeIf { it.isNotBlank() }+                    ?.let { AddonResource(name = it) }+                is JsonObject -> runCatching {+                    decoder.json.decodeFromJsonElement(AddonResource.serializer(), element)+                }.getOrNull()+                else -> null+            }+        }+    }++    override fun serialize(encoder: Encoder, value: List<AddonResource>) {+        delegate.serialize(encoder, value)+    }+}++/**+ * Subset of the Stremio addon manifest Uniflix supports: identity + stream+ * resources for movies/series. Catalog, meta, and subtitles resources are ignored.+ */+@Serializable+data class AddonManifest(+    val id: String,+    val name: String,+    val version: String = "",+    val description: String = "",+    @Serializable(with = ResourceListSerializer::class)+    val resources: List<AddonResource> = emptyList(),+    val types: List<String> = emptyList(),+    val idPrefixes: List<String> = emptyList(),+) {+    /**+     * Rejects manifests that cannot supply Uniflix streams. Returns this on+     * success so callers can parse-and-validate in one expression.+     */+    fun validate(): AddonManifest {+        if (resources.none { it.name == "stream" }) {+            error("Addon '$name' does not offer streams")+        }+        val offered = (types + resources.flatMap { it.types }).map { it.lowercase() }.toSet()+        if (offered.isNotEmpty() && "movie" !in offered && "series" !in offered) {+            error("Addon '$name' serves $offered, not movies or series")+        }+        return this+    }++    private fun error(message: String): Nothing = throw ManifestError.Unsupported(message)+}
uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonModels.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonModels.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonModels.ktnew file mode 100644index 0000000000..fc6e7c69f8--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/AddonModels.kt@@ -0,0 +1,59 @@+package com.vayunmathur.uniflix.domain++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/** Stremio stream URL form Uniflix requests: `tmdb:{id}` for movies, `tmdb:{id}:{s}:{e}` for episodes. */+fun addonStreamId(tmdbId: Int, mediaType: MediaType, season: Int = 0, episode: Int = 0): String =+    if (mediaType == MediaType.TV) "tmdb:$tmdbId:$season:$episode" else "tmdb:$tmdbId"++/** Stremio resource type for a catalog title. */+fun addonResourceType(mediaType: MediaType): String =+    if (mediaType == MediaType.TV) "series" else "movie"++/** One stream offered by an addon for `GET {base}/stream/{type}/{id}.json`. */+@Serializable+data class AddonStream(+    val url: String,+    val name: String? = null,+    val title: String? = null,+    val behaviorHints: AddonBehaviorHints? = null,+    val subtitles: List<AddonSubtitle> = emptyList(),+) {+    /** Maps onto the player-facing [VideoSource]; drops blank URLs (addon bug, not fatal). */+    fun toVideoSource(fallbackTitle: String): VideoSource? {+        if (url.isBlank()) return null+        return VideoSource(+            streamUrl = url,+            title = name?.takeIf { it.isNotBlank() } ?: fallbackTitle,+            subtitles = subtitles.mapNotNull { it.toSubtitleTrack() },+        )+    }+}++@Serializable+data class AddonBehaviorHints(+    @SerialName("notWebReady") val notWebReady: Boolean = false,+)++@Serializable+data class AddonSubtitle(+    val url: String,+    val lang: String = "",+    val id: String? = null,+) {+    fun toSubtitleTrack(): SubtitleTrack? {+        if (url.isBlank()) return null+        return SubtitleTrack(+            language = lang.ifBlank { id ?: "en" },+            displayName = id ?: lang,+            url = url,+        )+    }+}++/** Envelope of `GET {base}/stream/{type}/{id}.json`. */+@Serializable+data class AddonStreamsResponse(+    val streams: List<AddonStream> = emptyList(),+)
uniflix/src/main/java/com/vayunmathur/uniflix/domain/MediaModels.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/MediaModels.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/MediaModels.ktnew file mode 100644index 0000000000..74a802eb79--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/MediaModels.kt@@ -0,0 +1,68 @@+package com.vayunmathur.uniflix.domain++import kotlinx.serialization.Serializable++/** Movie or series, as keyed across catalog, artwork, and local watch state. */+enum class MediaType { MOVIE, TV }++/** A catalog row: id + artwork paths, resolved to CDN URLs by TmdbImageUrl. */+@Serializable+data class MediaItem(+    val tmdbId: Int,+    val mediaType: MediaType,+    val title: String,+    val year: Int? = null,+    val overview: String = "",+    val posterPath: String? = null,+    val backdropPath: String? = null,+    val voteAverage: Double = 0.0,+)++/** Full detail for the detail screen, mapped from the TMDB append_to_response payload. */+@Serializable+data class MediaDetail(+    val tmdbId: Int,+    val mediaType: MediaType,+    val title: String,+    val year: Int? = null,+    val overview: String = "",+    val posterPath: String? = null,+    val backdropPath: String? = null,+    val voteAverage: Double = 0.0,+    val runtimeMinutes: Int? = null,+    val seasons: List<SeasonSummary> = emptyList(),+    val recommendations: List<MediaItem> = emptyList(),+)++@Serializable+data class SeasonSummary(+    val seasonNumber: Int,+    val name: String,+    val episodeCount: Int,+    val stillPath: String? = null,+)++@Serializable+data class Episode(+    val seasonNumber: Int,+    val episodeNumber: Int,+    val name: String,+    val overview: String = "",+    val stillPath: String? = null,+)++/** A playable stream plus its subtitle tracks, supplied by a StreamProvider. */+@Serializable+data class VideoSource(+    val streamUrl: String,+    val title: String,+    val subtitles: List<SubtitleTrack> = emptyList(),+)++/** One subtitle track, fetched by the player from its own URL. */+@Serializable+data class SubtitleTrack(+    val language: String,+    val displayName: String,+    val url: String,+)
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.ktnew file mode 100644index 0000000000..a4b3649132--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/PluginRegistry.kt@@ -0,0 +1,106 @@+package com.vayunmathur.uniflix.domain++/** Outcome of resolving a title through the installed addon set. */+sealed interface ResolutionResult {+    /** A playable source, with the addon that supplied it. */+    data class Success(val source: VideoSource, val addonId: String) : ResolutionResult++    /** No addons installed or none enabled — UI links to the addon manager. */+    data object NoPluginsEnabled : ResolutionResult++    /** Every enabled addon failed; per-addon messages for the error badge. */+    data class AllFailed(val errorsByAddon: Map<String, String>) : ResolutionResult+}++/**+ * Resolution order over installed addons: the default first, then the rest by+ * priority. Pure (no Android) so fallback order is unit-testable.+ *+ * Each entry pairs the addon's stable id with its [StreamProvider]; the+ * registry tries them in order and records per-addon failures.+ */+class PluginRegistry(+    private val providers: List<Pair<String, StreamProvider>>,+) {+    val isEmpty: Boolean get() = providers.isEmpty()++    suspend fun resolve(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int = 0,+        episode: Int = 0,+        server: String? = null,+    ): ResolutionResult {+        if (providers.isEmpty()) return ResolutionResult.NoPluginsEnabled+        val errors = linkedMapOf<String, String>()+        for ((addonId, provider) in providers) {+            val source = runCatching {+                provider.resolve(tmdbId, mediaType, season, episode, server)+            }.getOrElse {+                errors[addonId] = it.message ?: "Unknown error"+                null+            } ?: continue+            return ResolutionResult.Success(source, addonId)+        }+        return ResolutionResult.AllFailed(errors)+    }++    suspend fun alternates(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int = 0,+        episode: Int = 0,+        maxTotal: Int = 20,+    ): List<VideoSource> {+        val out = mutableListOf<VideoSource>()+        for ((_, provider) in providers) {+            if (out.size >= maxTotal) break+            val rest = runCatching {+                provider.alternates(tmdbId, mediaType, season, episode)+            }.getOrDefault(emptyList())+            out += rest.take(maxTotal - out.size)+        }+        return out+    }++    suspend fun servers(): List<String> {+        val out = linkedSetOf<String>()+        for ((_, provider) in providers) {+            runCatching { out += provider.servers() }+        }+        return out.toList()+    }++    companion object {+        /**+         * Orders enabled addon entities: the default id first, then priority.+         * Providers are built per-entity by [build]; unbuildable entries (bad+         * manifest cache) are skipped, not fatal.+         */+        fun ordered(+            entities: List<InstalledAddon>,+            defaultDbId: Long?,+            build: (InstalledAddon) -> StreamProvider?,+        ): PluginRegistry {+            val sorted = entities.sortedWith(+                compareBy<InstalledAddon> { if (it.dbId == defaultDbId) 0 else 1 }+                    .thenBy { it.priority }+                    .thenBy { it.dbId },+            )+            return PluginRegistry(sorted.mapNotNull { entity ->+                val provider = runCatching { build(entity) }.getOrNull() ?: return@mapNotNull null+                entity.addonId to provider+            })+        }+    }+}++/** Minimal installed-addon view the registry needs (Room entity maps to this). */+data class InstalledAddon(+    val dbId: Long,+    val addonId: String,+    val baseUrl: String,+    val name: String,+    val version: String = "",+    val priority: Int = 0,+)
uniflix/src/main/java/com/vayunmathur/uniflix/domain/StreamProvider.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/domain/StreamProvider.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/StreamProvider.ktnew file mode 100644index 0000000000..669ca79072--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/domain/StreamProvider.kt@@ -0,0 +1,42 @@+package com.vayunmathur.uniflix.domain++/**+ * Resolves a catalog id to a playable source: HLS URL, title, and subtitles.+ *+ * Deliberately abstract: catalog browsing (TMDB) is implemented in this module,+ * but stream resolution is not. Subclass this with your own source later — the+ * player consumes only [VideoSource], never any provider-specific grant shape.+ */+abstract class StreamProvider {+    /** Human label shown in the server picker (e.g. "Nebula"). */+    abstract val name: String++    /** Whether this provider advertises 4K renditions. */+    abstract val supports4k: Boolean++    /**+     * Resolve [tmdbId] (+ season/episode for series) to a playable [VideoSource].+     * Throw on failure; the Watch screen surfaces the message.+     *+     * [server] pins resolution to one server (from [servers]); null lets the+     * provider pick its default.+     */+    abstract suspend fun resolve(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int = 0,+        episode: Int = 0,+        server: String? = null,+    ): VideoSource++    /** Extra providers offered as fallback in the picker, if any. */+    open suspend fun alternates(+        tmdbId: Int,+        mediaType: MediaType,+        season: Int = 0,+        episode: Int = 0,+    ): List<VideoSource> = emptyList()++    /** Healthy server names, for the in-player server picker. Empty when unsupported. */+    open suspend fun servers(): List<String> = emptyList()+}
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.ktnew file mode 100644index 0000000000..32d3f2ae44--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AddonsViewModel.kt@@ -0,0 +1,169 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.log.Log+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.UniflixRepository+import com.vayunmathur.uniflix.domain.ManifestError+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/** One addon row in the manager: entity plus whether it is the default. */+data class AddonRow(+    val entity: AddonEntity,+    val isDefault: Boolean,+)++private const val TAG = "AddonsViewModel"++/** Addon manager state: install by URL, enable/disable, default, priority, refresh. */+class AddonsViewModel(app: Application) : AndroidViewModel(app) {+    private val repository = UniflixRepository.get(app)+    private val prefs = AddonPrefs(app)++    var adding by mutableStateOf(false)+        private set+    var refreshing by mutableStateOf(false)+        private set++    val addons = combine(repository.addons, prefs.defaultAddonDbId) { entities, defaultId ->+        entities.map { AddonRow(it, it.dbId == defaultId) }+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    /** Fetches the manifest at [url], validates it, and stores the addon. */+    fun addByUrl(url: String) {+        if (url.isBlank()) return+        viewModelScope.launch {+            adding = true+            runCatching {+                val (base, manifest) = AddonStreamProvider.fetchManifest(url)+                val existing = repository.addonByManifestUrl("$base/manifest.json")+                val count = repository.addonCount()+                repository.upsertAddon(+                    (existing ?: AddonEntity(+                        manifestUrl = "$base/manifest.json",+                        baseUrl = base,+                        addonId = manifest.id,+                        name = manifest.name,+                        priority = count,+                    )).copy(+                        baseUrl = base,+                        addonId = manifest.id,+                        name = manifest.name,+                        version = manifest.version,+                        lastError = null,+                        updatedAt = System.currentTimeMillis(),+                    ),+                )+                AppMessages.show("Added ${manifest.name}")+            }.onFailure {+                val message = it.message ?: "Could not add addon"+                Log.error(TAG, "Add addon failed: $message", it)+                AppMessages.show(message)+            }+            adding = false+        }+    }++    fun remove(row: AddonRow) {+        viewModelScope.launch {+            repository.deleteAddon(row.entity.dbId)+            if (row.isDefault) prefs.setDefaultAddonDbId(null)+        }+    }++    fun setEnabled(row: AddonRow, enabled: Boolean) {+        viewModelScope.launch {+            repository.setAddonEnabled(row.entity.dbId, enabled)+        }+    }++    fun setDefault(row: AddonRow) {+        viewModelScope.launch {+            prefs.setDefaultAddonDbId(row.entity.dbId)+        }+    }++    fun clearDefault() {+        viewModelScope.launch { prefs.setDefaultAddonDbId(null) }+    }++    /** Swaps priorities with the neighbor above (lower number resolves first). */+    fun moveUp(rows: List<AddonRow>, row: AddonRow) {+        val index = rows.indexOfFirst { it.entity.dbId == row.entity.dbId }+        if (index <= 0) return+        swap(rows[index - 1], row)+    }++    /** Swaps priorities with the neighbor below. */+    fun moveDown(rows: List<AddonRow>, row: AddonRow) {+        val index = rows.indexOfFirst { it.entity.dbId == row.entity.dbId }+        if (index < 0 || index >= rows.lastIndex) return+        swap(row, rows[index + 1])+    }++    private fun swap(upper: AddonRow, lower: AddonRow) {+        viewModelScope.launch {+            repository.setAddonPriority(upper.entity.dbId, lower.entity.priority)+            repository.setAddonPriority(lower.entity.dbId, upper.entity.priority)+        }+    }++    /** Re-fetches the manifest; updates identity, clears or sets [AddonEntity.lastError]. */+    fun refreshManifest(row: AddonRow) {+        viewModelScope.launch {+            refreshing = true+            runCatching {+                val (base, manifest) = AddonStreamProvider.fetchManifest(row.entity.manifestUrl)+                repository.upsertAddon(+                    row.entity.copy(+                        baseUrl = base,+                        addonId = manifest.id,+                        name = manifest.name,+                        version = manifest.version,+                        lastError = null,+                        updatedAt = System.currentTimeMillis(),+                    ),+                )+                AppMessages.show("Refreshed ${manifest.name}")+            }.onFailure {+                val message = it.message ?: "Refresh failed"+                repository.setAddonError(row.entity.dbId, message)+                AppMessages.show(message)+            }+            refreshing = false+        }+    }++    /** Re-resolves identity without changing priority/enabled; reports reachability. */+    fun testAddon(row: AddonRow) {+        viewModelScope.launch {+            runCatching {+                AddonStreamProvider.fetchManifest(row.entity.manifestUrl)+                repository.setAddonError(row.entity.dbId, null)+                AppMessages.show("${row.entity.name} is reachable")+            }.onFailure {+                val message = it.message ?: "Addon unreachable"+                repository.setAddonError(row.entity.dbId, message)+                if (it !is ManifestError) Log.error(TAG, "Test addon 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/BrowseViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/BrowseViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/BrowseViewModel.ktnew file mode 100644index 0000000000..00eeebb426--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/BrowseViewModel.kt@@ -0,0 +1,58 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.uniflix.data.TmdbApi+import com.vayunmathur.uniflix.data.TmdbKeyStore+import com.vayunmathur.uniflix.domain.MediaItem+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/** Discover grid state, shared shape for the Movies and Series hubs. */+data class BrowseUiState(+    val loading: Boolean = false,+    val items: List<MediaItem> = emptyList(),+)++class BrowseViewModel(app: Application) : AndroidViewModel(app) {+    private val api = TmdbApi()+    private val keys = TmdbKeyStore(app)++    var movies by mutableStateOf(BrowseUiState())+        private set+    var series by mutableStateOf(BrowseUiState())+        private set++    fun loadMovies() {+        viewModelScope.launch {+            val key = keys.apiKey.first()+            if (key.isBlank()) return@launch+            movies = movies.copy(loading = true)+            runCatching {+                movies = BrowseUiState(items = api.discoverMovies(key))+            }.onFailure {+                movies = movies.copy(loading = false)+                AppMessages.show("Movies failed to load: ${it.message}")+            }+        }+    }++    fun loadSeries() {+        viewModelScope.launch {+            val key = keys.apiKey.first()+            if (key.isBlank()) return@launch+            series = series.copy(loading = true)+            runCatching {+                series = BrowseUiState(items = api.discoverTv(key))+            }.onFailure {+                series = series.copy(loading = false)+                AppMessages.show("Series failed to load: ${it.message}")+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..1826d54af6--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/DetailViewModel.kt@@ -0,0 +1,280 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+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.ContinueWatchingEntry+import com.vayunmathur.uniflix.data.TitleNote+import com.vayunmathur.uniflix.data.TmdbApi+import com.vayunmathur.uniflix.data.TmdbKeyStore+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.InstalledAddon+import com.vayunmathur.uniflix.domain.MediaDetail+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.domain.PluginRegistry+import com.vayunmathur.uniflix.domain.ResolutionResult+import com.vayunmathur.uniflix.domain.StreamProvider+import com.vayunmathur.uniflix.domain.VideoSource+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/**+ * Builds the live [PluginRegistry] from installed addons. Public+ * implementations stay pure-HTTP; the personal overlay swaps this factory to+ * also register its native provider.+ */+fun interface RegistryFactory {+    suspend fun current(repository: UniflixRepository, prefs: AddonPrefs): PluginRegistry++    companion object {+        val HttpAddons = 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,+                    )+                },+                defaultDbId = defaultId,+                // Manifests were validated at install/refresh time; playback+                // uses only the stored base URL + name, no network fetch here.+                build = { installed ->+                    AddonStreamProvider(baseUrl = installed.baseUrl, displayName = installed.name)+                },+            )+        }+    }+}++/** Detail: TMDB detail + seasons, watchlist toggle, provider resolution, local notes. */+data class DetailUiState(+    val loading: Boolean = false,+    val detail: MediaDetail? = null,+    val episodes: List<Episode> = emptyList(),+    val selectedSeason: Int = 1,+    val watchlisted: Boolean = false,+    val source: VideoSource? = null,+    val resolving: Boolean = false,+    val providerMissing: Boolean = false,+    /** Healthy servers for the in-player server picker. */+    val servers: List<String> = emptyList(),+    /** Server pinned by the picker; null means the provider's default. */+    val selectedServer: String? = null,+    /** Last resolve failure, surfaced in the player instead of a bare spinner. */+    val resolveError: String? = null,+    /** Saved position to start from; Navigation fills this before resolve. */+    val startPositionMs: Long = 0L,+)++class DetailViewModel(+    app: Application,+    private val registryFactory: RegistryFactory = RegistryFactory.HttpAddons,+) : AndroidViewModel(app) {+    private val api = TmdbApi()+    private val keys = TmdbKeyStore(app)+    private val repository = UniflixRepository.get(app)+    private val addonPrefs = AddonPrefs(app)++    companion object {+        private const val TAG = "DetailViewModel"+    }++    /** Back-compat hook for tests: bypasses installed addons with a fixed set. */+    var streamProviders: List<StreamProvider>? = null++    var state by mutableStateOf(DetailUiState())+        private set++    fun notesFor(tmdbId: Int, mediaType: MediaType) =+        repository.notesFor(tmdbId, mediaType.name.lowercase())++    fun load(mediaType: MediaType, tmdbId: Int) {+        viewModelScope.launch {+            val key = keys.apiKey.first()+            if (key.isBlank()) return@launch+            state = state.copy(loading = true)+            runCatching {+                val detail = when (mediaType) {+                    MediaType.MOVIE -> api.movieDetail(key, tmdbId)+                    MediaType.TV -> api.tvDetail(key, tmdbId)+                }+                val watchlisted = repository.isWatchlisted(+                    watchKey(tmdbId, mediaType.name.lowercase()),+                )+                val episodes = if (mediaType == MediaType.TV) {+                    val season = detail.seasons.firstOrNull { it.seasonNumber > 0 }?.seasonNumber ?: 1+                    api.seasonEpisodes(key, tmdbId, season)+                } else {+                    emptyList()+                }+                state = state.copy(+                    loading = false,+                    detail = detail,+                    episodes = episodes,+                    selectedSeason = episodes.firstOrNull()?.seasonNumber ?: 1,+                    watchlisted = watchlisted,+                )+            }.onFailure {+                state = state.copy(loading = false)+                Log.error(TAG, "Detail failed to load: ${it.message}", it)+                AppMessages.show("Detail failed to load: ${it.message}")+            }+        }+    }++    fun selectSeason(mediaType: MediaType, tmdbId: Int, season: Int) {+        viewModelScope.launch {+            val key = keys.apiKey.first()+            if (key.isBlank()) return@launch+            runCatching {+                state = state.copy(selectedSeason = season, episodes = api.seasonEpisodes(key, tmdbId, season))+            }.onFailure {+                AppMessages.show("Season failed to load: ${it.message}")+                Log.error(TAG, "Season failed to load: ${it.message}", it)+            }+        }+    }++    fun toggleWatchlist() {+        val detail = state.detail ?: return+        viewModelScope.launch {+            val key = watchKey(detail.tmdbId, detail.mediaType.name.lowercase())+            if (state.watchlisted) {+                repository.removeWatchlist(key)+                state = state.copy(watchlisted = false)+            } else {+                repository.upsertWatchlist(+                    WatchlistEntry(+                        key = key,+                        tmdbId = detail.tmdbId,+                        mediaType = detail.mediaType.name.lowercase(),+                        title = detail.title,+                        posterPath = detail.posterPath,+                        addedAt = System.currentTimeMillis(),+                    ),+                )+                state = state.copy(watchlisted = true)+            }+        }+    }++    /** Resolve via installed addons: default first, then priority fallbacks. */+    fun resolve(mediaType: MediaType, tmdbId: Int, season: Int = 0, episode: Int = 0) {+        viewModelScope.launch {+            state = state.copy(resolving = true, resolveError = null, providerMissing = false)+            val registry = currentRegistry()+            when (val result = registry.resolve(tmdbId, mediaType, season, episode, state.selectedServer)) {+                is ResolutionResult.Success -> {+                    state = state.copy(resolving = false, source = result.source)+                }+                ResolutionResult.NoPluginsEnabled -> {+                    state = state.copy(resolving = false, providerMissing = true)+                }+                is ResolutionResult.AllFailed -> {+                    val message = result.errorsByAddon.values.firstOrNull() ?: "Unknown error"+                    state = state.copy(resolving = false, resolveError = message)+                    Log.error(TAG, "Stream failed to resolve: $message")+                    AppMessages.show("Stream failed to resolve: $message")+                }+            }+        }+    }++    /** Healthy servers for the in-player server picker. */+    fun loadServers() {+        viewModelScope.launch {+            runCatching {+                state = state.copy(servers = currentRegistry().servers())+            }.onFailure {+                Log.error(TAG, "Servers failed to load: ${it.message}", it)+            }+        }+    }++    private suspend fun currentRegistry(): PluginRegistry {+        val override = streamProviders+        if (override != null) {+            return PluginRegistry(override.mapIndexed { index, provider -> "test-$index" to provider })+        }+        return registryFactory.current(repository, addonPrefs)+    }++    /** Saved resume position for this title/episode, for the player to start from. */+    suspend fun startPosition(mediaType: MediaType, tmdbId: Int, season: Int, episode: Int): Long {+        return runCatching {+            repository.positionFor(watchKey(tmdbId, mediaType.name.lowercase(), season, episode))+        }.getOrDefault(0L)+    }++    /** Pin a server and re-resolve the current title against it. */+    fun selectServer(mediaType: MediaType, tmdbId: Int, season: Int, episode: Int, server: String) {+        if (state.selectedServer == server) return+        state = state.copy(selectedServer = server, source = null)+        resolve(mediaType, tmdbId, season, episode)+    }++    fun addNote(mediaType: MediaType, tmdbId: Int, body: String, score: Int) {+        if (body.isBlank()) return+        viewModelScope.launch {+            repository.upsertNote(+                TitleNote(+                    tmdbId = tmdbId,+                    mediaType = mediaType.name.lowercase(),+                    body = body.trim(),+                    score = score,+                    createdAt = System.currentTimeMillis(),+                ),+            )+        }+    }++    fun deleteNote(note: TitleNote) {+        viewModelScope.launch { repository.deleteNote(note) }+    }++    fun savePosition(+        mediaType: MediaType,+        tmdbId: Int,+        title: String,+        posterPath: String?,+        season: Int,+        episode: Int,+        positionMs: Long,+        durationMs: Long,+    ) {+        viewModelScope.launch {+            repository.savePosition(+                ContinueWatchingEntry(+                    key = watchKey(tmdbId, mediaType.name.lowercase(), season, episode),+                    tmdbId = tmdbId,+                    mediaType = mediaType.name.lowercase(),+                    title = title,+                    posterPath = posterPath,+                    season = season,+                    episode = episode,+                    positionMs = positionMs,+                    durationMs = durationMs,+                    updatedAt = System.currentTimeMillis(),+                ),+            )+        }+    }++    fun userLists() = repository.userLists+}
uniflix/src/main/java/com/vayunmathur/uniflix/platform/HomeViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/HomeViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/HomeViewModel.ktnew file mode 100644index 0000000000..2bfd6218f8--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/HomeViewModel.kt@@ -0,0 +1,81 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.uniflix.data.TmdbApi+import com.vayunmathur.uniflix.data.TmdbKeyStore+import com.vayunmathur.uniflix.data.UniflixRepository+import com.vayunmathur.uniflix.domain.MediaItem+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.launchIn+import kotlinx.coroutines.flow.onEach+import kotlinx.coroutines.launch++/** Home rows: trending + top-rated, gated on a configured TMDB key. */+data class HomeUiState(+    val hasKey: Boolean = false,+    val loading: Boolean = false,+    val trendingMovies: List<MediaItem> = emptyList(),+    val trendingTv: List<MediaItem> = emptyList(),+    val topMovies: List<MediaItem> = emptyList(),+    val topTv: List<MediaItem> = emptyList(),+)++class HomeViewModel(app: Application) : AndroidViewModel(app) {+    private val api = TmdbApi()+    private val keys = TmdbKeyStore(app)+    val repository = UniflixRepository.get(app)++    var state by mutableStateOf(HomeUiState())+        private set++    init {+        keys.apiKey+            .onEach { key ->+                state = state.copy(hasKey = key.isNotBlank())+                if (key.isNotBlank()) refresh(key)+            }+            .launchIn(viewModelScope)+    }++    fun refresh(apiKey: String = "") {+        viewModelScope.launch {+            val key = apiKey.ifEmpty { keys.apiKey.first() }+            if (key.isBlank()) {+                state = state.copy(hasKey = false)+                return@launch+            }+            state = state.copy(loading = true, hasKey = true)+            runCatching {+                val movies = api.trendingMovies(key)+                val tv = api.trendingTv(key)+                val topM = api.topRatedMovies(key)+                val topT = api.topRatedTv(key)+                state = state.copy(+                    loading = false,+                    trendingMovies = movies,+                    trendingTv = tv,+                    topMovies = topM,+                    topTv = topT,+                )+            }.onFailure {+                state = state.copy(loading = false)+                AppMessages.show("Catalog failed to load: ${it.message}")+            }+        }+    }++    /** Continue-watching row source, newest first. */+    val continueWatching get() = repository.continueWatching++    /** Watchlist row source, newest first. */+    val watchlist get() = repository.watchlist++    fun watchlistSnapshot() = combine(repository.watchlist, repository.continueWatching) { w, _ -> w }+}
uniflix/src/main/java/com/vayunmathur/uniflix/platform/ListsViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/ListsViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/ListsViewModel.ktnew file mode 100644index 0000000000..1dc564b2b1--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/ListsViewModel.kt@@ -0,0 +1,51 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import android.content.Context+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.uniflix.data.UniflixRepository+import com.vayunmathur.uniflix.data.UserList+import com.vayunmathur.uniflix.data.UserListItem+import kotlinx.coroutines.launch++/** Local lists hub: create lists, add/remove items. */+class ListsViewModel(app: Application) : AndroidViewModel(app) {+    private val repository = UniflixRepository.get(app)++    val lists get() = repository.userLists+    fun items(listId: Long) = repository.listItems(listId)++    fun createList(name: String) {+        if (name.isBlank()) return+        viewModelScope.launch {+            repository.upsertList(UserList(name = name.trim(), createdAt = System.currentTimeMillis()))+        }+    }++    fun addItem(listId: Long, tmdbId: Int, mediaType: String, title: String, posterPath: String?) {+        viewModelScope.launch {+            repository.upsertListItem(+                UserListItem(+                    listId = listId,+                    tmdbId = tmdbId,+                    mediaType = mediaType,+                    title = title,+                    posterPath = posterPath,+                ),+            )+        }+    }++    fun deleteList(list: UserList) {+        viewModelScope.launch { repository.deleteList(list) }+    }++    fun deleteItem(item: UserListItem) {+        viewModelScope.launch { repository.deleteListItem(item) }+    }++    companion object {+        fun listsFor(context: Context) = UniflixRepository.get(context).userLists+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/platform/SearchViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SearchViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SearchViewModel.ktnew file mode 100644index 0000000000..f6b0885231--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SearchViewModel.kt@@ -0,0 +1,53 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.uniflix.data.TmdbApi+import com.vayunmathur.uniflix.data.TmdbKeyStore+import com.vayunmathur.uniflix.domain.MediaItem+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/** Multi-search state with a short debounce. */+data class SearchUiState(+    val query: String = "",+    val loading: Boolean = false,+    val results: List<MediaItem> = emptyList(),+)++class SearchViewModel(app: Application) : AndroidViewModel(app) {+    private val api = TmdbApi()+    private val keys = TmdbKeyStore(app)+    private var searchJob: Job? = null++    var state by mutableStateOf(SearchUiState())+        private set++    fun onQueryChange(value: String) {+        state = state.copy(query = value)+        searchJob?.cancel()+        if (value.isBlank()) {+            state = state.copy(results = emptyList(), loading = false)+            return+        }+        searchJob = viewModelScope.launch {+            delay(400)+            val key = keys.apiKey.first()+            if (key.isBlank()) return@launch+            state = state.copy(loading = true)+            runCatching {+                state = state.copy(loading = false, results = api.search(key, value))+            }.onFailure {+                state = state.copy(loading = false)+                AppMessages.show("Search failed: ${it.message}")+            }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/platform/SettingsViewModel.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SettingsViewModel.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SettingsViewModel.ktnew file mode 100644index 0000000000..486570a0d4--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/SettingsViewModel.kt@@ -0,0 +1,52 @@+package com.vayunmathur.uniflix.platform++import android.app.Application+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.uniflix.data.TmdbKeyStore+import kotlinx.coroutines.flow.launchIn+import kotlinx.coroutines.flow.onEach+import kotlinx.coroutines.launch++/** Onboarding + settings state: the user-supplied TMDB API key. */+data class SettingsUiState(+    val apiKey: String = "",+    val draftKey: String = "",+    val saving: Boolean = false,+) {+    val onboarded: Boolean get() = apiKey.isNotBlank()+}++class SettingsViewModel(app: Application) : AndroidViewModel(app) {+    private val store = TmdbKeyStore(app)++    var state by mutableStateOf(SettingsUiState())+        private set++    init {+        store.apiKey+            .onEach { key ->+                state = state.copy(+                    apiKey = key,+                    draftKey = if (state.draftKey.isEmpty()) key else state.draftKey,+                )+            }+            .launchIn(viewModelScope)+    }++    fun onDraftChange(value: String) {+        state = state.copy(draftKey = value)+    }++    fun saveKey() {+        if (state.draftKey.isBlank()) return+        viewModelScope.launch {+            state = state.copy(saving = true)+            store.setApiKey(state.draftKey)+            state = state.copy(saving = false)+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.ktnew file mode 100644index 0000000000..1358bd82c9--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonCard.kt@@ -0,0 +1,77 @@+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconArrowDownward+import com.vayunmathur.library.ui.IconArrowUpward+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.IconStar+import com.vayunmathur.library.ui.IconStarBorder+import com.vayunmathur.library.ui.IconWarning+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.uniflix.platform.AddonRow++/** One installed addon: identity, toggles, ordering, health, and actions. */+@Composable+fun AddonCard(+    row: AddonRow,+    onToggle: () -> Unit,+    onSetDefault: () -> Unit,+    onClearDefault: () -> Unit,+    onMoveUp: () -> Unit,+    onMoveDown: () -> Unit,+    onRemove: () -> Unit,+    onRefresh: () -> Unit,+    onOpenDetail: () -> Unit,+) {+    val entity = row.entity+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            Row(+                modifier = Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.SpaceBetween,+                verticalAlignment = Alignment.CenterVertically,+            ) {+                Column(Modifier.weight(1f)) {+                    Text(entity.name, style = MaterialTheme.typography.titleMedium)+                    if (entity.version.isNotBlank()) {+                        Text("v${entity.version}", style = MaterialTheme.typography.bodySmall)+                    }+                }+                IconButton(onClick = { if (row.isDefault) onClearDefault() else onSetDefault() }) {+                    if (row.isDefault) IconStar() else IconStarBorder()+                }+                Switch(checked = entity.enabled, onCheckedChange = { onToggle() })+            }+            entity.lastError?.let { error ->+                Row(+                    horizontalArrangement = Arrangement.spacedBy(8.dp),+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    IconWarning()+                    Text(error, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))+                }+            }+            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+                IconButton(onClick = onMoveUp) { IconArrowUpward() }+                IconButton(onClick = onMoveDown) { IconArrowDownward() }+                IconButton(onClick = onRefresh) { IconRefresh() }+                IconButton(onClick = onRemove) { IconDelete() }+                TextButton(onClick = onOpenDetail) { Text("Details") }+            }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonDetailScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonDetailScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonDetailScreen.ktnew file mode 100644index 0000000000..374f0c74cc--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonDetailScreen.kt@@ -0,0 +1,100 @@+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+import androidx.compose.foundation.verticalScroll+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.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.platform.AddonsViewModel++/**+ * Per-addon detail: manifest identity, health, enable/default toggles, test ++ * refresh actions, and the opaque per-addon settings JSON.+ */+@Composable+fun AddonDetailScreen(addonDbId: Long, onBack: () -> Unit) {+    val vm: AddonsViewModel = viewModel()+    val rows by vm.addons.collectAsState()+    val row = rows.firstOrNull { it.entity.dbId == addonDbId }++    AppScaffold(+        title = row?.entity?.name ?: "Addon",+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            if (row == null) {+                Text("Addon not found.", modifier = Modifier.padding(16.dp))+                return@DesktopMaxWidthContainer+            }+            val entity = row.entity+            var configDraft by remember(entity.configJson) { mutableStateOf(entity.configJson) }+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(12.dp),+            ) {+                Text("Manifest: ${entity.manifestUrl}", style = MaterialTheme.typography.bodySmall)+                if (entity.version.isNotBlank()) {+                    Text("Version: ${entity.version}")+                }+                entity.lastError?.let { Text("Last error: $it") }+                Row(+                    modifier = Modifier.fillMaxWidth(),+                    horizontalArrangement = Arrangement.SpaceBetween,+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    Text("Enabled")+                    Switch(checked = entity.enabled, onCheckedChange = { vm.setEnabled(row, !entity.enabled) })+                }+                Row(+                    modifier = Modifier.fillMaxWidth(),+                    horizontalArrangement = Arrangement.SpaceBetween,+                    verticalAlignment = Alignment.CenterVertically,+                ) {+                    Text("Default addon")+                    Switch(+                        checked = row.isDefault,+                        onCheckedChange = { if (row.isDefault) vm.clearDefault() else vm.setDefault(row) },+                    )+                }+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    Button(onClick = { vm.testAddon(row) }) { Text("Test") }+                    OutlinedButton(onClick = { vm.refreshManifest(row) }) { Text("Refresh manifest") }+                }+                Text("Addon settings (JSON)", style = MaterialTheme.typography.titleMedium)+                OutlinedTextField(+                    value = configDraft,+                    onValueChange = { configDraft = it },+                    modifier = Modifier.fillMaxWidth(),+                    minLines = 3,+                )+                Button(+                    onClick = { vm.updateConfig(entity.dbId, configDraft) },+                    enabled = configDraft != entity.configJson,+                ) { Text("Save settings") }+                OutlinedButton(onClick = { vm.remove(row); onBack() }) { Text("Remove addon") }+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..dba1cd06ee--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsContent.kt@@ -0,0 +1,85 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.platform.AddonRow++/**+ * Stateless addon-manager body: list + empty state. Split from [AddonsScreen]+ * so store-listing previews render without a ViewModel or database.+ */+@Composable+fun AddonsContent(+    rows: List<AddonRow>,+    adding: Boolean,+    refreshing: Boolean,+    onBack: () -> Unit,+    onAddClick: () -> Unit,+    onToggle: (AddonRow) -> Unit,+    onSetDefault: (AddonRow) -> Unit,+    onClearDefault: () -> Unit,+    onMoveUp: (AddonRow) -> Unit,+    onMoveDown: (AddonRow) -> Unit,+    onRemove: (AddonRow) -> Unit,+    onRefresh: (AddonRow) -> Unit,+    onOpenDetail: (addonDbId: Long) -> Unit,+) {+    AppScaffold(+        title = "Stream addons",+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+        actions = {+            IconButton(onClick = onAddClick) { IconAdd() }+        },+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(12.dp),+            ) {+                Text(+                    "Addons supply streams. Uniflix ships none — paste an addon URL to watch.",+                    style = MaterialTheme.typography.bodyMedium,+                )+                if (rows.isEmpty()) {+                    Text(+                        "No stream addons yet. Add one to enable playback.",+                        style = MaterialTheme.typography.bodyMedium,+                    )+                    Button(onClick = onAddClick, enabled = !adding) { Text("Add addon") }+                    return@Column+                }+                rows.forEach { row ->+                    AddonCard(+                        row = row,+                        onToggle = { onToggle(row) },+                        onSetDefault = { onSetDefault(row) },+                        onClearDefault = onClearDefault,+                        onMoveUp = { onMoveUp(row) },+                        onMoveDown = { onMoveDown(row) },+                        onRemove = { onRemove(row) },+                        onRefresh = { onRefresh(row) },+                        onOpenDetail = { onOpenDetail(row.entity.dbId) },+                    )+                }+                if (refreshing) CircularProgressIndicator()+            }+        }+    }+}
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.ktnew file mode 100644index 0000000000..5271586174--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/AddonsScreen.kt@@ -0,0 +1,50 @@+package com.vayunmathur.uniflix.ui++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.setValue+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.uniflix.platform.AddonsViewModel+import com.vayunmathur.uniflix.ui.dialogs.AddAddonDialog++/**+ * Addon manager: installed URL addons with enable toggle, default star,+ * priority ordering, error badges, and add-by-URL. State lives here; the+ * stateless [AddonsContent] body renders previews without a ViewModel.+ */+@Composable+fun AddonsScreen(onBack: () -> Unit, onOpenDetail: (addonDbId: Long) -> Unit) {+    val vm: AddonsViewModel = viewModel()+    val rows by vm.addons.collectAsState()+    var showAddDialog by remember { mutableStateOf(false) }++    AddonsContent(+        rows = rows,+        adding = vm.adding,+        refreshing = vm.refreshing,+        onBack = onBack,+        onAddClick = { showAddDialog = true },+        onToggle = { row -> vm.setEnabled(row, !row.entity.enabled) },+        onSetDefault = { row -> vm.setDefault(row) },+        onClearDefault = { vm.clearDefault() },+        onMoveUp = { row -> vm.moveUp(rows, row) },+        onMoveDown = { row -> vm.moveDown(rows, row) },+        onRemove = { row -> vm.remove(row) },+        onRefresh = { row -> vm.refreshManifest(row) },+        onOpenDetail = onOpenDetail,+    )++    if (showAddDialog) {+        AddAddonDialog(+            adding = vm.adding,+            onDismiss = { showAddDialog = false },+            onConfirm = { url ->+                vm.addByUrl(url)+                showAddDialog = false+            },+        )+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/ContinueWatchingScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ContinueWatchingScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ContinueWatchingScreen.ktnew file mode 100644index 0000000000..deae2069d2--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ContinueWatchingScreen.kt@@ -0,0 +1,63 @@+package com.vayunmathur.uniflix.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.data.ContinueWatchingEntry+import com.vayunmathur.uniflix.data.UniflixRepository+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType++/** Resume rail: saved positions, newest first. */+@Composable+fun ContinueWatchingScreen(onBack: () -> Unit, onResume: (ContinueWatchingEntry) -> Unit) {+    val context = LocalContext.current+    val repository = remember(context) { UniflixRepository.get(context) }+    val entries by repository.continueWatching.collectAsState(initial = emptyList())++    AppScaffold(+        title = "Continue watching",+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(8.dp),+            ) {+                if (entries.isEmpty()) {+                    Text("Nothing in progress yet.")+                    return@Column+                }+                entries.forEach { entry ->+                    val mediaItem = MediaItem(+                        tmdbId = entry.tmdbId,+                        mediaType = if (entry.mediaType == "tv") MediaType.TV else MediaType.MOVIE,+                        title = entry.title,+                        posterPath = entry.posterPath,+                    )+                    MediaCard(+                        item = mediaItem,+                        onOpen = {+                            onResume(entry)+                        },+                    )+                }+            }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/DetailScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/DetailScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/DetailScreen.ktnew file mode 100644index 0000000000..f0f37818fb--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/DetailScreen.kt@@ -0,0 +1,169 @@+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+import androidx.compose.foundation.verticalScroll+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.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.data.TmdbImageUrl+import com.vayunmathur.uniflix.data.UniflixRepository+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.DetailUiState++/** Detail: hero art, overview, seasons/episodes, watchlist, resolve, notes. */+@Composable+fun DetailScreen(+    state: DetailUiState,+    onBack: () -> Unit,+    onSeasonChange: (Int) -> Unit,+    onToggleWatchlist: () -> Unit,+    onPlay: (season: Int, episode: Int) -> Unit,+    onResolve: (season: Int, episode: Int) -> Unit,+    onAddNote: (String, Int) -> Unit,+    onOpenDetail: (MediaItem) -> Unit,+    onOpenAddons: () -> Unit,+) {+    val detail = state.detail+    AppScaffold(+        title = detail?.title ?: "Detail",+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            if (state.loading && detail == null) {+                CircularProgressIndicator(modifier = Modifier.padding(16.dp))+                return@DesktopMaxWidthContainer+            }+            if (detail == null) {+                Text("Detail failed to load.", modifier = Modifier.padding(16.dp))+                return@DesktopMaxWidthContainer+            }+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(12.dp),+            ) {+                AsyncImage(+                    model = TmdbImageUrl.backdrop(detail.backdropPath),+                    contentDescription = detail.title,+                    modifier = Modifier.fillMaxWidth(),+                    contentScale = ContentScale.FillWidth,+                )+                Text(detail.overview, style = MaterialTheme.typography.bodyMedium)+                detail.year?.let { Text("Year: $it") }+                detail.runtimeMinutes?.let { Text("Runtime: $it min") }+                OutlinedButton(onClick = onToggleWatchlist, modifier = Modifier.fillMaxWidth()) {+                    Text(if (state.watchlisted) "Remove from watchlist" else "Add to watchlist")+                }+                if (detail.mediaType == MediaType.TV) {+                    Text("Seasons", style = MaterialTheme.typography.titleMedium)+                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                        detail.seasons.filter { it.seasonNumber > 0 }.forEach { season ->+                            OutlinedButton(+                                onClick = { onSeasonChange(season.seasonNumber) },+                            ) { Text("${season.seasonNumber}") }+                        }+                    }+                    state.episodes.forEach { episode ->+                        Card(modifier = Modifier.fillMaxWidth()) {+                            Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                                Text("E${episode.episodeNumber} · ${episode.name}")+                                Button(onClick = {+                                    onResolve(episode.seasonNumber, episode.episodeNumber)+                                    onPlay(episode.seasonNumber, episode.episodeNumber)+                                }) { Text("Play") }+                            }+                        }+                    }+                } else {+                    Button(+                        onClick = {+                            onResolve(0, 0)+                            onPlay(0, 0)+                        },+                        modifier = Modifier.fillMaxWidth(),+                    ) { Text(if (state.resolving) "Resolving…" else "Play") }+                }+                if (state.providerMissing) {+                    Card(modifier = Modifier.fillMaxWidth()) {+                        Column(+                            Modifier.padding(12.dp),+                            verticalArrangement = Arrangement.spacedBy(8.dp),+                        ) {+                            Text(+                                "No stream addons installed — playback needs at least one addon.",+                                style = MaterialTheme.typography.bodyMedium,+                            )+                            Button(onClick = onOpenAddons) { Text("Open addon manager") }+                        }+                    }+                }+                state.resolveError?.let { error ->+                    Text("Resolve failed: $error", style = MaterialTheme.typography.bodySmall)+                }+                state.source?.let { source ->+                    Text("Resolved: ${source.title}", style = MaterialTheme.typography.bodySmall)+                }+                MediaRow("More like this", detail.recommendations, onOpenDetail)+                NoteSection(+                    tmdbId = detail.tmdbId,+                    mediaType = detail.mediaType,+                    onAddNote = onAddNote,+                )+            }+        }+    }+}++@Composable+private fun NoteSection(+    tmdbId: Int,+    mediaType: MediaType,+    onAddNote: (String, Int) -> Unit,+) {+    val context = LocalContext.current+    val repository = remember(context) { UniflixRepository.get(context) }+    val notes by repository.notesFor(tmdbId, mediaType.name.lowercase()).collectAsState(initial = emptyList())+    var draft by remember { mutableStateOf("") }+    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+        Text("Notes", style = MaterialTheme.typography.titleMedium)+        OutlinedTextField(+            value = draft,+            onValueChange = { draft = it },+            label = { Text("Add a note") },+            modifier = Modifier.fillMaxWidth(),+        )+        Button(onClick = {+            onAddNote(draft, 0)+            draft = ""+        }, enabled = draft.isNotBlank()) { Text("Save note") }+        notes.forEach { note ->+            Card(modifier = Modifier.fillMaxWidth()) {+                Text(note.body, modifier = Modifier.padding(12.dp))+            }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/HomeScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/HomeScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/HomeScreen.ktnew file mode 100644index 0000000000..fce31996e1--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/HomeScreen.kt@@ -0,0 +1,73 @@+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+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconList+import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.IconWidgets+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.platform.HomeUiState++/** Home: trending/top-rated rows plus hub shortcuts. */+@Composable+fun HomeScreen(+    state: HomeUiState,+    onRefresh: () -> Unit,+    onOpenDetail: (MediaItem) -> Unit,+    onOpenSearch: () -> Unit,+    onOpenMovies: () -> Unit,+    onOpenSeries: () -> Unit,+    onOpenLists: () -> Unit,+    onOpenContinue: () -> Unit,+    onOpenAddons: () -> Unit,+) {+    AppScaffold(+        title = "Uniflix",+        scrollBehavior = appBarScrollBehavior(),+        actions = {+            IconButton(onClick = onOpenSearch) { IconSearch() }+            IconButton(onClick = onOpenAddons) { IconWidgets() }+        },+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(16.dp),+            ) {+                if (!state.hasKey) {+                    Text("Add your TMDB API key in Settings to browse.")+                    return@Column+                }+                if (state.loading) {+                    CircularProgressIndicator()+                }+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    Button(onClick = onOpenMovies) { Text("Movies") }+                    Button(onClick = onOpenSeries) { Text("Series") }+                    IconButton(onClick = onOpenLists) { IconList() }+                    IconButton(onClick = onOpenContinue) { IconHistory() }+                }+                MediaRow("Trending movies", state.trendingMovies, onOpenDetail)+                MediaRow("Trending series", state.trendingTv, onOpenDetail)+                MediaRow("Top-rated movies", state.topMovies, onOpenDetail)+                MediaRow("Top-rated series", state.topTv, onOpenDetail)+            }+        }+    }+}
uniflix/src/main/java/com/vayunmathur/uniflix/ui/ListsScreen.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ListsScreen.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ListsScreen.ktnew file mode 100644index 0000000000..06823eb271--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/ui/ListsScreen.kt@@ -0,0 +1,95 @@+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+import androidx.compose.foundation.verticalScroll+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.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.uniflix.domain.MediaItem+import com.vayunmathur.uniflix.domain.MediaType+import com.vayunmathur.uniflix.platform.ListsViewModel++/** Local user lists hub: create lists, file titles, remove. */+@Composable+fun ListsScreen(onBack: () -> Unit, onOpenDetail: (MediaItem) -> Unit) {+    val vm: ListsViewModel = viewModel()+    val lists by vm.lists.collectAsState(initial = emptyList())+    var draft by remember { mutableStateOf("") }++    AppScaffold(+        title = "Lists",+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        DesktopMaxWidthContainer(Modifier.padding(padding)) {+            Column(+                modifier = Modifier.fillMaxWidth().padding(16.dp).verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(12.dp),+            ) {+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    OutlinedTextField(+                        value = draft,+                        onValueChange = { draft = it },+                        label = { Text("New list") },+                        modifier = Modifier.weight(1f),+                        singleLine = true,+                    )+                    Button(onClick = {+                        vm.createList(draft)+                        draft = ""+                    }, enabled = draft.isNotBlank()) { Text("Add") }+                }+                lists.forEach { list ->+                    Card(modifier = Modifier.fillMaxWidth()) {+                        Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                            Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {+                                

Diff truncated.