StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Polish TV UX and refresh project docs
David Nashashca3780703c96
diff --git a/.gitignore b/.gitignoreindex e733babe..36d5d68f 100644--- a/.gitignore+++ b/.gitignore@@ -19,7 +19,12 @@ captures/.externalNativeBuild.cxxlocal.properties+*.local.propertieskeystore.properties+secrets.properties+secret.properties+.env+.env.*keystore/release-signing-info.local.txt*.jksdiff --git a/README.md b/README.mdindex 3f12fdb3..b4a552e9 100644--- a/README.md+++ b/README.md@@ -1,51 +1,51 @@# StreamVault-StreamVault is an Android TV IPTV player built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.+StreamVault is a TV-first IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.-It is designed for large catalogs, remote-friendly navigation, and a polished TV-first playback experience. The app supports common IPTV provider formats, full library browsing, TV playback, and modern Android TV integrations.+It is designed for large playlists, remote-friendly browsing, fast provider switching, and a polished living-room playback experience. StreamVault supports both `M3U` playlists and `Xtream Codes`, with dedicated flows for `Live TV`, `Movies`, and `Series`.-## What It Does+## Highlights-- Connects to IPTV providers using `M3U` playlists or `Xtream Codes`-- Syncs and organizes `Live TV`, `Movies`, and `Series`-- Provides a dedicated Android TV experience with Leanback launcher support-- Plays streams with Media3-based playback controls and track selection+- Android TV-first interface with D-pad-friendly focus, navigation, and playback flows+- Live TV with favorites, recent channels, custom groups, pinned categories, and fast channel browsing+- Movie and series libraries with detailed metadata screens, resume support, and category navigation+- Multi-view split-screen playback for watching multiple channels at once+- Full EPG support with now-playing data and provider archive or catch-up support when available+- Strong parental controls with PIN-protected categories and automatic adult-category detection+- Global search across live channels, movies, and series+- Launcher and TV integrations including Android TV entry points and TV input support-## Supported Features+## Feature Set-- Provider setup for `M3U` and `Xtream Codes`-- Live TV with categories, channel search, favorites,custom categories and recent channels-- Movies and series libraries with category browsing and search-- Full EPG and now-playing data-- Global search across live channels, movies, and series-- Favorites and custom favorite groups-- Continue watching and playback history-- Multi-view playback for watching multiple streams-- Parental controls with PIN-protected categories-- Subtitle, audio-track, playback-speed, and video-track controls+- Provider onboarding for `M3U` playlists and `Xtream Codes`+- Resilient sync pipeline for live, movie, series, and EPG data+- TV-optimized search inputs and provider setup forms+- Favorites, recent history, continue watching, and playback history+- Custom favorite groups and personalized live-TV organization+- Multi-view audio focus management and split-screen planning+- Subtitle, audio-track, aspect-ratio, playback-speed, and video-track controls- Cast integration-- Android TV home integrations such as launcher entry points and TV input support+- Provider-scoped settings and category visibility or protection preferences## Screenshots-Add screenshots to `docs/images/` and update this section when assets are available.--Suggested files:+Placeholder images are included in `docs/images/` so the repository renders cleanly until final screenshots are captured.-- `docs/images/dashboard.png`-- `docs/images/live-tv.png`-- `docs/images/player.png`-- `docs/images/movies.png`-- `docs/images/series.png`-- `docs/images/search.png`-- `docs/images/multiview.png`+++++++## Project Structure-- `app/` Android app UI, navigation, DI, Android TV integrations-- `data/` Room database, sync, parsers, repositories, provider implementations-- `domain/` models, repository contracts, use cases, managers+- `app/` Android app UI, navigation, dependency injection, and Android TV integrations+- `data/` Room database, sync, parsing, provider implementations, and repositories+- `domain/` models, repository contracts, managers, and use cases- `player/` playback abstraction and Media3 player implementation+- `docs/` architecture notes and image assets## Build@@ -53,16 +53,18 @@ Requirements:- Android Studio- Android SDK-- JDK 17 or compatible Gradle-supported JDK+- JDK 17 or another Gradle-supported JDK 17 runtimeUseful commands:```bash./gradlew assembleDebug+./gradlew assembleRelease./gradlew testDebugUnitTest```## Notes- StreamVault is an IPTV client, not a content provider.-- You are responsible for using playlist sources and streams you are authorized to access.+- Use only playlists, streams, and guide sources you are authorized to access.+- Local configuration and signing files are intentionally excluded from git.diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex afc64d7c..0f169c68 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -21,6 +21,7 @@android:allowBackup="false"android:banner="@drawable/app_banner"android:icon="@mipmap/ic_launcher_vault"+ android:roundIcon="@mipmap/ic_launcher_vault"android:label="StreamVault"android:networkSecurityConfig="@xml/network_security_config"android:usesCleartextTraffic="false"@@ -31,6 +32,7 @@android:name=".MainActivity"android:exported="true"android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|smallestScreenSize"+ android:launchMode="singleTask"android:supportsPictureInPicture="true"android:screenOrientation="landscape"android:windowSoftInputMode="adjustResize">diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 44ef7e92..a500a994 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -49,7 +49,8 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_21_22,StreamVaultDatabase.MIGRATION_22_23,StreamVaultDatabase.MIGRATION_23_24,- StreamVaultDatabase.MIGRATION_24_25+ StreamVaultDatabase.MIGRATION_24_25,+ StreamVaultDatabase.MIGRATION_25_26)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -69,6 +70,7 @@ object DatabaseModule {@Provides fun providePlaybackHistoryDao(db: StreamVaultDatabase): PlaybackHistoryDao = db.playbackHistoryDao()@Provides fun provideSyncMetadataDao(db: StreamVaultDatabase): SyncMetadataDao = db.syncMetadataDao()@Provides fun provideMovieCategoryHydrationDao(db: StreamVaultDatabase): MovieCategoryHydrationDao = db.movieCategoryHydrationDao()+ @Provides fun provideSeriesCategoryHydrationDao(db: StreamVaultDatabase): SeriesCategoryHydrationDao = db.seriesCategoryHydrationDao()@Provides fun provideEpgSourceDao(db: StreamVaultDatabase): EpgSourceDao = db.epgSourceDao()@Provides fun provideProviderEpgSourceDao(db: StreamVaultDatabase): ProviderEpgSourceDao = db.providerEpgSourceDao()@Provides fun provideEpgChannelDao(db: StreamVaultDatabase): EpgChannelDao = db.epgChannelDao()diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex 91f8cd5a..b4ad37e9 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -49,6 +49,9 @@ abstract class RepositoryModule {@Binds @Singletonabstract fun bindPlaybackHistoryRepository(impl: PlaybackHistoryRepositoryImpl): PlaybackHistoryRepository+ @Binds @Singleton+ abstract fun bindExternalRatingsRepository(impl: ExternalRatingsRepositoryImpl): ExternalRatingsRepository+@Binds @Singletonabstract fun bindSyncMetadataRepository(impl: SyncMetadataRepositoryImpl): SyncMetadataRepositorydiff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex daf53749..19765c0b 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -293,6 +293,17 @@ fun AppNavigation(mainActivity: MainActivity) {))},+ onFavoriteChannelClick = { channel ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = com.streamvault.domain.model.VirtualCategoryIds.FAVORITES,+ providerId = channel.providerId,+ isVirtual = true,+ returnRoute = Routes.HOME+ )+ )+ },onMovieClick = { movie ->navController.navigateIfResumed(Routes.movieDetail(movie.id, Routes.HOME))},diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.ktindex b18e09f8..222e2d51 100644--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt@@ -14,15 +14,19 @@ import androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Star+import androidx.compose.material3.Iconimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue+import androidx.lifecycle.compose.collectAsStateWithLifecycleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob@@ -191,7 +195,7 @@ fun ChannelCard(isReorderMode: Boolean = false,isDragging: Boolean = false) {- val nowMs by ChannelProgressTicker.nowMs.collectAsState()+ val nowMs by ChannelProgressTicker.nowMs.collectAsStateWithLifecycle()val channelCardShape = LocalAppShapes.current.smallval channelDescription = buildString {append(@@ -299,7 +303,12 @@ fun ChannelCard(verticalAlignment = Alignment.CenterVertically) {if (channel.isFavorite) {- StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentAmber, contentColor = Color.Black, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)+ Icon(+ imageVector = Icons.Filled.Star,+ contentDescription = null,+ tint = AccentAmber,+ modifier = Modifier.size(14.dp)+ )}if (channel.errorCount > 0) {StatusPill(label = stringResource(R.string.badge_error), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)@@ -412,8 +421,19 @@ fun MovieCard(}if (movie.isFavorite) {- Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {- StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)+ Box(+ modifier = Modifier+ .align(Alignment.TopEnd)+ .padding(6.dp)+ .background(Color.Black.copy(alpha = 0.55f), RoundedCornerShape(4.dp))+ .padding(4.dp)+ ) {+ Icon(+ imageVector = Icons.Filled.Star,+ contentDescription = null,+ tint = AccentAmber,+ modifier = Modifier.size(12.dp)+ )}}}@@ -511,8 +531,19 @@ fun SeriesCard(}if (series.isFavorite) {- Box(modifier = Modifier.align(Alignment.TopEnd).padding(8.dp)) {- StatusPill(label = stringResource(R.string.badge_fav), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)+ Box(+ modifier = Modifier+ .align(Alignment.TopEnd)+ .padding(6.dp)+ .background(Color.Black.copy(alpha = 0.55f), RoundedCornerShape(4.dp))+ .padding(4.dp)+ ) {+ Icon(+ imageVector = Icons.Filled.Star,+ contentDescription = null,+ tint = AccentAmber,+ modifier = Modifier.size(12.dp)+ )}}}diff --git a/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt b/app/src/main/java/com/streamvault/app/ui/components/SearchInput.ktindex 7311ed97..cc858fb3 100644--- a/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/SearchInput.kt@@ -9,6 +9,8 @@ import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequesterimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardActions@@ -17,9 +19,11 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Closeimport androidx.compose.material.icons.filled.Searchimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.ExperimentalComposeUiApi@@ -31,26 +35,33 @@ import androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.platform.LocalFocusManagerimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.semantics.stateDescription+import androidx.compose.ui.text.TextRangeimport androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.unit.dpimport androidx.tv.material3.Iconimport androidx.tv.material3.MaterialThemeimport androidx.tv.material3.Text+import com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.ui.interaction.mouseClickableimport com.streamvault.app.ui.theme.FocusBorderimport com.streamvault.app.ui.theme.OnSurfaceimport com.streamvault.app.ui.theme.OnSurfaceDimimport com.streamvault.app.ui.theme.Primaryimport com.streamvault.app.ui.theme.SurfaceElevatedimport com.streamvault.app.ui.theme.SurfaceHighlight+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch/*** A TV-optimized search input field.- * Handles focus delegation to the inner text field and shows the keyboard automatically.+ * The shell is focusable for D-pad navigation and only enters edit mode on click/select.*/@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)@Composable@@ -64,9 +75,77 @@ fun SearchInput(onSearch: () -> Unit = {},enabled: Boolean = true) {- var isFocused by remember { mutableStateOf(false) }+ val isTelevisionDevice = rememberIsTelevisionDevice()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var textFieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }val focusManager = LocalFocusManager.currentval keyboardController = LocalSoftwareKeyboardController.current+ val inputFocusRequester = remember { FocusRequester() }+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ val coroutineScope = rememberCoroutineScope()+ val isFocused = enabled && (hasContainerFocus || hasInputFocus)++ fun requestBringIntoView(delayMillis: Long = 0L) {+ coroutineScope.launch {+ if (delayMillis > 0) {+ delay(delayMillis)+ }+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ fun activateInput() {+ if (!enabled) {+ return+ }+ if (!isTelevisionDevice) {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView()+ requestBringIntoView(180)+ return+ }+ acceptsInput = true+ pendingInputActivation = true+ requestBringIntoView()+ }++ LaunchedEffect(value) {+ if (value != textFieldValue.text) {+ val coercedSelectionStart = textFieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = textFieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = textFieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ textFieldValue = textFieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {+ return@LaunchedEffect+ }+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView(120)+ pendingInputActivation = false+ }val borderColor = if (isFocused) FocusBorder else OnSurfaceDim.copy(alpha = 0.5f)val backgroundColor = if (isFocused) SurfaceHighlight else SurfaceElevated@@ -76,6 +155,8 @@ fun SearchInput(modifier = modifier.fillMaxWidth().height(40.dp)+ .focusRequester(focusRequester)+ .bringIntoViewRequester(bringIntoViewRequester).background(backgroundColor, RoundedCornerShape(8.dp)).border(borderWidth, borderColor, RoundedCornerShape(8.dp)).semantics(mergeDescendants = true) {@@ -83,15 +164,16 @@ fun SearchInput(stateDescription = value.ifBlank { placeholder }}.onFocusChanged {- isFocused = enabled && it.hasFocus+ hasContainerFocus = enabled && it.isFocused}.focusProperties {canFocus = enabled- onEnter = { focusRequester }+ }+ .mouseClickable(enabled = enabled, focusRequester = focusRequester) {+ activateInput()}.clickable(enabled = enabled) {- focusRequester.requestFocus()- keyboardController?.show()+ activateInput()}.focusable(enabled = enabled).padding(horizontal = 12.dp),@@ -108,21 +190,68 @@ fun SearchInput(}BasicTextField(- value = value,- onValueChange = onValueChange,+ value = textFieldValue,+ onValueChange = { updatedValue ->+ textFieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },modifier = Modifier.fillMaxWidth()- .focusRequester(focusRequester),+ .focusRequester(inputFocusRequester)+ .focusProperties {+ canFocus = enabled && (!isTelevisionDevice || acceptsInput)+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onFocusChanged {+ hasInputFocus = enabled && it.hasFocus+ if (it.hasFocus) {+ requestBringIntoView(120)+ } else {+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = textFieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ val nextCursor = (cursor + 1).coerceAtMost(textFieldValue.text.length)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ },textStyle = MaterialTheme.typography.bodySmall.copy(color = OnSurface),singleLine = true,cursorBrush = SolidColor(Primary),enabled = enabled,+ readOnly = isTelevisionDevice && !acceptsInput,keyboardOptions = KeyboardOptions(imeAction = imeAction),keyboardActions = KeyboardActions(onSearch = {onSearch()+ acceptsInput = falsekeyboardController?.hide()- focusManager.moveFocus(FocusDirection.Down)+ val movedFocus = focusManager.moveFocus(FocusDirection.Down)+ if (!movedFocus) {+ focusRequester.requestFocus()+ }}))@@ -139,9 +268,9 @@ fun SearchInput(modifier = Modifier.padding(start = 6.dp).clickable(enabled = enabled && value.isNotBlank()) {+ textFieldValue = TextFieldValue(text = "", selection = TextRange(0))onValueChange("")- focusRequester.requestFocus()- keyboardController?.show()+ activateInput()})}diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.ktindex e8444900..20dc3ca4 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt@@ -122,7 +122,8 @@ fun AddToGroupDialog(modifier = Modifier.weight(1f))IconButton(- onClick = safeDismiss+ onClick = safeDismiss,+ modifier = Modifier.mouseClickable(onClick = safeDismiss)) {Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_group_close_cd))}diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.ktindex 35fa27ef..c4083272 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt@@ -41,6 +41,8 @@ fun CategoryOptionsDialog(category: Category,onDismissRequest: () -> Unit,onSetAsDefault: (() -> Unit)? = null,+ isPinned: Boolean = false,+ onTogglePinned: (() -> Unit)? = null,onRename: (() -> Unit)? = null,onHide: (() -> Unit)? = null,onToggleLock: (() -> Unit)? = null,@@ -57,7 +59,11 @@ fun CategoryOptionsDialog(Dialog(onDismissRequest = safeDismiss,- properties = DialogProperties(usePlatformDefaultWidth = false)+ properties = DialogProperties(+ dismissOnBackPress = canInteract,+ dismissOnClickOutside = canInteract,+ usePlatformDefaultWidth = false+ )) {BoxWithConstraints(modifier = Modifier.fillMaxWidth(),@@ -104,6 +110,19 @@ fun CategoryOptionsDialog()}+ if (onTogglePinned != null) {+ PremiumDialogAction(+ label = stringResource(+ if (isPinned) R.string.category_options_unpin else R.string.category_options_pin+ ),+ onClick = {+ if (canInteract) {+ onTogglePinned()+ }+ }+ )+ }+if (onRename != null) {PremiumDialogAction(label = stringResource(R.string.category_options_rename),diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.ktindex 3b30dfdd..8a26d823 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt@@ -1,4 +1,4 @@-package com.streamvault.app.ui.components.dialogs+package com.streamvault.app.ui.components.dialogsimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementdiff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.ktindex d6f32610..7b5163bf 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt@@ -58,15 +58,22 @@ fun PinDialog(// Auto-submit when all 4 digits enteredLaunchedEffect(pin) {if (pin.length == 4) {+ val submittedPin = pindelay(200)- onPinEntered(pin)- pin = ""+ if (pin == submittedPin) {+ onPinEntered(submittedPin)+ pin = ""+ }}}Dialog(- onDismissRequest = { if (canInteract) onDismissRequest() },- properties = DialogProperties(usePlatformDefaultWidth = false)+ onDismissRequest = onDismissRequest,+ properties = DialogProperties(+ dismissOnBackPress = canInteract,+ dismissOnClickOutside = canInteract,+ usePlatformDefaultWidth = false+ )) {val dialogContent: @Composable (Modifier) -> Unit = { resolvedModifier ->Box(diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.ktindex 23c9e1b9..14219adb 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt@@ -50,8 +50,12 @@ fun PremiumDialog(val isTelevisionDevice = rememberIsTelevisionDevice()LaunchedEffect(Unit) { delay(500); canInteract = true }Dialog(- onDismissRequest = { if (canInteract) onDismissRequest() },- properties = DialogProperties(usePlatformDefaultWidth = false)+ onDismissRequest = onDismissRequest,+ properties = DialogProperties(+ dismissOnBackPress = canInteract,+ dismissOnClickOutside = canInteract,+ usePlatformDefaultWidth = false+ )) {if (isTelevisionDevice) {Surface(diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.ktindex 2fdf83af..64b5e89d 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt@@ -1,4 +1,4 @@-package com.streamvault.app.ui.components.dialogs+package com.streamvault.app.ui.components.dialogsimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.text.KeyboardActionsdiff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.ktindex ac782402..be08906c 100644--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt@@ -4,6 +4,10 @@ import androidx.compose.animation.core.animateFloatAsStateimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.size+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Star+import androidx.compose.material3.Iconimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row@@ -18,11 +22,11 @@ import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue+import androidx.lifecycle.compose.collectAsStateWithLifecycleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob@@ -96,7 +100,7 @@ fun LiveChannelRowCard(val logoPadding = if (isDense) 5.dp else if (isUltraCompact) 6.dp else 8.dpval contentSpacing = if (isUltraCompact) 8.dp else 10.dpval badgeSpacing = if (isUltraCompact) 3.dp else 4.dp- val nowMs by LiveChannelRowTicker.nowMs.collectAsState()+ val nowMs by LiveChannelRowTicker.nowMs.collectAsStateWithLifecycle()Box(modifier = modifier@@ -245,6 +249,7 @@ fun LiveChannelRowSurface(.fillMaxWidth().mouseClickable(focusRequester = focusRequester,+ onLongClick = onLongClick,onClick = {sounds.playSelect()onClick()@@ -315,6 +320,22 @@ fun LiveChannelRowSurface()}}+ if (!isLocked && !isReorderMode && channel.isFavorite) {+ Box(+ modifier = Modifier+ .align(Alignment.TopEnd)+ .padding(10.dp)+ .background(Color.Black.copy(alpha = 0.55f), RoundedCornerShape(4.dp))+ .padding(4.dp)+ ) {+ Icon(+ imageVector = Icons.Filled.Star,+ contentDescription = null,+ tint = AppColors.Warning,+ modifier = Modifier.size(11.dp)+ )+ }+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/ExternalRatingsStrip.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/ExternalRatingsStrip.ktnew file mode 100644index 00000000..d99a7a42--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/ExternalRatingsStrip.kt@@ -0,0 +1,147 @@+package com.streamvault.app.ui.components.shell++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.design.AppColors+import com.streamvault.domain.model.ExternalRatingValue+import com.streamvault.domain.model.ExternalRatings++@Composable+fun ExternalRatingsStrip(+ ratings: ExternalRatings,+ isLoading: Boolean,+ modifier: Modifier = Modifier+) {+ if (!isLoading && !ratings.hasAnyAvailableValue()) {+ return+ }++ Column(+ modifier = modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = stringResource(R.string.vod_external_ratings_heading),+ style = MaterialTheme.typography.titleMedium,+ color = AppColors.TextSecondary+ )++ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RatingBadgeCard(+ token = "IMDb",+ title = stringResource(R.string.vod_rating_imdb),+ value = ratings.imdb,+ isLoading = isLoading,+ tokenBackground = Color(0xFFF5C449),+ tokenContent = Color(0xFF111111)+ )+ RatingBadgeCard(+ token = "RT",+ title = stringResource(R.string.vod_rating_rotten_tomatoes),+ value = ratings.rottenTomatoes,+ isLoading = isLoading,+ tokenBackground = Color(0xFFE24E41),+ tokenContent = Color.White+ )+ RatingBadgeCard(+ token = "MC",+ title = stringResource(R.string.vod_rating_metacritic),+ value = ratings.metacritic,+ isLoading = isLoading,+ tokenBackground = Color(0xFFD6E04B),+ tokenContent = Color(0xFF111111)+ )+ RatingBadgeCard(+ token = "TMDb",+ title = stringResource(R.string.vod_rating_tmdb),+ value = ratings.tmdb,+ isLoading = isLoading,+ tokenBackground = Color(0xFF17C7A2),+ tokenContent = Color(0xFF072720)+ )+ }+ }+}++private fun ExternalRatings.hasAnyAvailableValue(): Boolean {+ return imdb.available || rottenTomatoes.available || metacritic.available || tmdb.available+}++@Composable+private fun RatingBadgeCard(+ token: String,+ title: String,+ value: ExternalRatingValue,+ isLoading: Boolean,+ tokenBackground: Color,+ tokenContent: Color+) {+ val displayValue = if (isLoading) "..." else value.displayValue+ val containerColor = if (value.available || isLoading) {+ AppColors.SurfaceElevated+ } else {+ AppColors.Surface+ }++ Column(+ modifier = Modifier+ .widthIn(min = 92.dp)+ .background(containerColor, RoundedCornerShape(18.dp))+ .border(1.dp, AppColors.Outline, RoundedCornerShape(18.dp))+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Box(+ modifier = Modifier+ .background(tokenBackground, RoundedCornerShape(8.dp))+ .padding(horizontal = 8.dp, vertical = 3.dp)+ ) {+ Text(+ text = token,+ color = tokenContent,+ style = MaterialTheme.typography.labelMedium,+ fontWeight = FontWeight.Bold+ )+ }+ Text(+ text = title,+ color = AppColors.TextTertiary,+ style = MaterialTheme.typography.labelMedium,+ maxLines = 1+ )+ }++ Text(+ text = displayValue,+ color = if (value.available || isLoading) AppColors.TextPrimary else AppColors.TextSecondary,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold+ )+ }+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.ktindex 824d9409..ba0795d9 100644--- a/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/VodChrome.kt@@ -285,12 +285,14 @@ fun VodCategoryPickerDialog(color = Primary)}- Spacer(modifier = Modifier.width(8.dp))- Text(- text = category.count.toString(),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )+ if (category.count > 0) {+ Spacer(modifier = Modifier.width(8.dp))+ Text(+ text = category.count.toString(),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.ktindex 79c72531..faf479e3 100644--- a/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/VodClassicBrowser.kt@@ -113,12 +113,14 @@ fun VodClassicSplitLayout(color = AppColors.BrandStrong)}- Spacer(modifier = Modifier.width(12.dp))- Text(- text = category.count.toString(),- style = MaterialTheme.typography.bodySmall,- color = AppColors.TextSecondary- )+ if (category.count > 0) {+ Spacer(modifier = Modifier.width(12.dp))+ Text(+ text = category.count.toString(),+ style = MaterialTheme.typography.bodySmall,+ color = AppColors.TextSecondary+ )+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.ktindex aca5fdf1..537f0fd6 100644--- a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt+++ b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt@@ -44,6 +44,7 @@ fun TvClickableSurface() {Surface(onClick = onClick,+ onLongClick = onLongClick,modifier = modifier.mouseClickable(onClick = onClick, enabled = enabled, onLongClick = onLongClick),enabled = enabled,shape = shape,diff --git a/app/src/main/java/com/streamvault/app/ui/model/LiveTvQuickFilterVisibilityMode.kt b/app/src/main/java/com/streamvault/app/ui/model/LiveTvQuickFilterVisibilityMode.ktnew file mode 100644index 00000000..62a85a57--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/model/LiveTvQuickFilterVisibilityMode.kt@@ -0,0 +1,13 @@+package com.streamvault.app.ui.model++enum class LiveTvQuickFilterVisibilityMode(val storageValue: String) {+ HIDE("hide"),+ SHOW_WHEN_FILTERS_AVAILABLE("available"),+ ALWAYS_VISIBLE("always");++ companion object {+ fun fromStorage(value: String?): LiveTvQuickFilterVisibilityMode =+ entries.firstOrNull { it.storageValue.equals(value, ignoreCase = true) }+ ?: ALWAYS_VISIBLE+ }+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.ktindex 81f7feec..2ab40b8c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt@@ -86,6 +86,7 @@ fun DashboardScreen(onNavigate: (String) -> Unit,onAddProvider: () -> Unit,onChannelClick: (Channel) -> Unit,+ onFavoriteChannelClick: (Channel) -> Unit,onMovieClick: (Movie) -> Unit,onSeriesClick: (Series) -> Unit,onPlaybackHistoryClick: (PlaybackHistory) -> Unit,@@ -154,7 +155,7 @@ fun DashboardScreen(title = stringResource(R.string.dashboard_favorite_channels),channels = uiState.favoriteChannels,onSeeAll = { onNavigate(Routes.liveTv(com.streamvault.domain.model.VirtualCategoryIds.FAVORITES)) },- onChannelClick = onChannelClick+ onChannelClick = onFavoriteChannelClick)DashboardHomeSection.RECENT_CHANNELS -> CategoryRow(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.ktindex 9beb874b..d2b91a2a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt@@ -32,6 +32,8 @@ import androidx.compose.foundation.lazy.LazyRowimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequesterimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScroll@@ -52,16 +54,20 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalFocusManagerimport androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.platform.LocalViewimport androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRangeimport androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.Dp@@ -84,6 +90,7 @@ import com.streamvault.app.ui.components.ChannelLogoBadgeimport com.streamvault.app.navigation.Routesimport com.streamvault.app.ui.components.SelectionChipimport com.streamvault.app.ui.components.SelectionChipRow+import kotlinx.coroutines.launchimport com.streamvault.app.ui.components.dialogs.PinDialogimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffold@@ -754,36 +761,71 @@ private fun GuideSearchField(onSearch: ((String) -> Unit)? = null,onActivated: (() -> Unit)? = null) {- var isFocused by remember { mutableStateOf(false) }+ val isTelevisionDevice = rememberIsTelevisionDevice()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var textFieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }val focusManager = LocalFocusManager.currentval keyboardController = LocalSoftwareKeyboardController.currentval view = LocalView.currentval context = LocalContext.current+ val coroutineScope = rememberCoroutineScope()+ val inputFocusRequester = remember { FocusRequester() }+ val bringIntoViewRequester = remember { BringIntoViewRequester() }var pendingKeyboardRequest by remember { mutableStateOf(0) }val inputMethodManager = remember(context) {context.getSystemService(InputMethodManager::class.java)}+ val isFocused = hasContainerFocus || hasInputFocus++ fun requestBringIntoView(delayMillis: Long = 0L) {+ coroutineScope.launch {+ if (delayMillis > 0) {+ kotlinx.coroutines.delay(delayMillis)+ }+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }fun requestKeyboard() {+ if (!isTelevisionDevice) {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ view.post {+ val focusedView = view.findFocus() ?: view+ focusedView.requestFocus()+ keyboardController?.show()+ inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)+ }+ onActivated?.invoke()+ requestBringIntoView()+ requestBringIntoView(180)+ return+ }+ acceptsInput = truependingKeyboardRequest += 1onActivated?.invoke()+ requestBringIntoView()}LaunchedEffect(autoRequestFocus) {if (autoRequestFocus) {- requestKeyboard()+ focusRequester.requestFocus()}}LaunchedEffect(refocusToken) {if (refocusToken > 0) {- requestKeyboard()+ focusRequester.requestFocus()}}LaunchedEffect(pendingKeyboardRequest) {- if (pendingKeyboardRequest <= 0) return@LaunchedEffect- focusRequester.requestFocus()+ if (!isTelevisionDevice || pendingKeyboardRequest <= 0) return@LaunchedEffect+ inputFocusRequester.requestFocus()kotlinx.coroutines.delay(80)view.post {val focusedView = view.findFocus() ?: view@@ -791,16 +833,27 @@ private fun GuideSearchField(keyboardController?.show()inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)}- }-- LaunchedEffect(isFocused) {- if (!isFocused) return@LaunchedEffect- kotlinx.coroutines.delay(50)- view.post {- val focusedView = view.findFocus() ?: view- focusedView.requestFocus()- keyboardController?.show()- inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)+ requestBringIntoView(120)+ }++ LaunchedEffect(value) {+ if (value != textFieldValue.text) {+ val coercedSelectionStart = textFieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = textFieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = textFieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ textFieldValue = textFieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )}}@@ -808,7 +861,11 @@ private fun GuideSearchField(onClick = {requestKeyboard()},- modifier = modifier.height(40.dp),+ modifier = modifier+ .height(40.dp)+ .focusRequester(focusRequester)+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusChanged { hasContainerFocus = it.isFocused },colors = ClickableSurfaceDefaults.colors(containerColor = if (isFocused) SurfaceHighlight else SurfaceElevated,focusedContainerColor = SurfaceHighlight,@@ -849,25 +906,64 @@ private fun GuideSearchField()}BasicTextField(- value = value,- onValueChange = onValueChange,+ value = textFieldValue,+ onValueChange = { updatedValue ->+ textFieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },modifier = Modifier.fillMaxWidth()- .focusRequester(focusRequester)+ .focusRequester(inputFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = textFieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ val nextCursor = (cursor + 1).coerceAtMost(textFieldValue.text.length)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }.onFocusChanged {- isFocused = it.isFocusedif (it.isFocused) {- onActivated?.invoke()+ hasInputFocus = true+ requestBringIntoView(120)+ } else {+ hasInputFocus = false+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()}},textStyle = MaterialTheme.typography.bodySmall.copy(color = OnSurface),singleLine = true,cursorBrush = SolidColor(Primary),+ readOnly = isTelevisionDevice && !acceptsInput,keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),keyboardActions = KeyboardActions(onSearch = {focusManager.clearFocus(force = true)+ acceptsInput = falsekeyboardController?.hide()- onSearch?.invoke(value.trim())+ onSearch?.invoke(textFieldValue.text.trim())}))}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.ktindex 0f8cb443..d47c7b92 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt@@ -180,6 +180,12 @@ class EpgViewModel @Inject constructor(fun selectCategory(categoryId: Long) {if (selectedCategoryId.value == categoryId) return+ baseGuideSnapshot.value?.providerId?.let { providerId ->+ parentalControlManager.retainUnlockedCategory(+ providerId = providerId,+ categoryId = categoryId.takeIf { it > 0L && it != ChannelRepository.ALL_CHANNELS_ID }+ )+ }selectedCategoryId.value = categoryId}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.ktindex 69376dd0..e2ee87b5 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt@@ -2,7 +2,9 @@ package com.streamvault.app.ui.screens.homeimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.Canvasimport androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.rememberLazyListState@@ -17,6 +19,8 @@ import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport com.streamvault.app.ui.components.SearchInput+import com.streamvault.app.ui.components.SelectionChip+import com.streamvault.app.ui.components.SelectionChipRowimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.FocusRequester@@ -41,6 +45,8 @@ import androidx.compose.material3.LinearProgressIndicatorimport com.streamvault.app.device.rememberIsTelevisionDeviceimport androidx.compose.animation.Crossfadeimport androidx.compose.animation.core.tween+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.compose.LifecycleEventEffectimport com.streamvault.app.ui.components.CategoryRowimport com.streamvault.app.ui.components.ChannelCardimport com.streamvault.app.ui.components.shell.ContentMetadataStrip@@ -49,13 +55,16 @@ import com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.components.dialogs.CategoryOptionsDialogimport com.streamvault.app.ui.components.dialogs.PinDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButtonimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.dialogs.RenameGroupDialogimport com.streamvault.app.ui.components.ReorderTopBarimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffoldimport com.streamvault.app.ui.design.FocusRestoreHost+import com.streamvault.app.ui.design.requestFocusSafelyimport androidx.activity.compose.BackHandler+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.app.ui.theme.*import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channel@@ -84,7 +93,7 @@ private enum class FocusRestoreTarget {CHANNEL}-private const val HOME_CATEGORY_SEARCH_RESULT_LIMIT = 250+private const val HOME_ALL_FILTER_KEY = "__all_categories__"@Composableprivate fun HomeLoadingPane(@@ -166,10 +175,10 @@ fun HomeScreen(val snackbarHostState = remember { SnackbarHostState() }// Split screen state- val splitSlots by multiViewViewModel.slotsFlow.collectAsStateWithLifecycle()- val hasSplitChannels = splitSlots.any { it != null }+ val hasSplitChannels = uiState.multiviewChannelCount > 0var showSplitManagerDialog by rememberSaveable { mutableStateOf(false) }var pendingSplitPlannerChannel by remember { mutableStateOf<Channel?>(null) }+ var showAddQuickFilterDialog by rememberSaveable { mutableStateOf(false) }// Parental Control Statevar showPinDialog by rememberSaveable { mutableStateOf(false) }@@ -191,13 +200,25 @@ fun HomeScreen(}}+ LifecycleEventEffect(Lifecycle.Event.ON_STOP) {+ viewModel.clearPreview()+ }++ DisposableEffect(viewModel) {+ onDispose {+ viewModel.clearPreview()+ }+ }+val hasOverlay = showPinDialog || showSplitManagerDialog || pendingSplitPlannerChannel != null ||+ showAddQuickFilterDialog ||uiState.showDialog || uiState.showDeleteGroupDialog ||uiState.showRenameGroupDialog || uiState.selectedCategoryForOptions != null ||isReorderModeBackHandler(enabled = hasOverlay) {when {+ showAddQuickFilterDialog -> showAddQuickFilterDialog = falseshowPinDialog -> {showPinDialog = falsepinError = null@@ -285,6 +306,10 @@ fun HomeScreen(viewModel.dismissCategoryOptions()}},+ isPinned = category.id in uiState.pinnedCategoryIds,+ onTogglePinned = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {+ { viewModel.toggleCategoryPinned(category) }+ } else null,onHide = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {{ viewModel.hideCategory(category) }} else null,@@ -307,6 +332,44 @@ fun HomeScreen()}+ if (showAddQuickFilterDialog) {+ var pendingFilter by rememberSaveable { mutableStateOf("") }+ PremiumDialog(+ title = stringResource(R.string.home_quick_filters_add_title),+ subtitle = stringResource(R.string.home_quick_filters_add_subtitle),+ onDismissRequest = { showAddQuickFilterDialog = false },+ widthFraction = 0.42f,+ content = {+ SearchInput(+ value = pendingFilter,+ onValueChange = { pendingFilter = it },+ placeholder = stringResource(R.string.home_quick_filters_add_placeholder),+ modifier = Modifier.fillMaxWidth()+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.home_quick_filters_add_action),+ enabled = pendingFilter.isNotBlank(),+ onClick = {+ val normalized = pendingFilter.trim()+ val isDuplicate = uiState.savedCategoryFilters.any {+ it.equals(normalized, ignoreCase = true)+ }+ viewModel.addLiveTvCategoryFilter(pendingFilter)+ if (normalized.isNotBlank() && !isDuplicate) {+ showAddQuickFilterDialog = false+ }+ }+ )+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = { showAddQuickFilterDialog = false }+ )+ }+ )+ }+Box(modifier = Modifier.fillMaxSize()) {AppScreenScaffold(currentRoute = currentRoute,@@ -362,7 +425,6 @@ fun HomeScreen(uiState.categorySearchQuery.isEmpty() ||it.name.contains(uiState.categorySearchQuery, ignoreCase = true)}- .take(HOME_CATEGORY_SEARCH_RESULT_LIMIT).toList()}val isCategoryLocked: (Category) -> Boolean = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {@@ -413,6 +475,42 @@ fun HomeScreen(var preferredRestoreTarget by rememberSaveable { mutableStateOf(FocusRestoreTarget.CHANNEL.name) }var pendingRestoreTarget by remember { mutableStateOf<FocusRestoreTarget?>(null) }var focusRestoreNonce by rememberSaveable { mutableStateOf(0) }+ var pendingCategoryContentJumpCategoryId by rememberSaveable { mutableStateOf<Long?>(null) }++ fun requestChannelFocus(channelId: Long?): Boolean {+ val resolvedChannelId = channelId ?: return false+ return channelFocusRequesters[resolvedChannelId]+ ?.requestFocusSafely(tag = "HomeScreen", target = "Channel $resolvedChannelId")+ ?: false+ }++ fun requestCategoryFocus(categoryId: Long?): Boolean {+ val resolvedCategoryId = categoryId ?: return false+ return categoryFocusRequesters[resolvedCategoryId]+ ?.requestFocusSafely(tag = "HomeScreen", target = "Category $resolvedCategoryId")+ ?: false+ }++ fun requestChannelFocusFromCategory(): Boolean {+ if (uiState.filteredChannels.isEmpty()) return false+ val preferredChannelId = lastFocusedChannelId+ ?.takeIf { channelId -> uiState.filteredChannels.any { it.id == channelId } }+ ?: uiState.filteredChannels.first().id+ lastFocusedChannelId = preferredChannelId+ preferredRestoreTarget = FocusRestoreTarget.CHANNEL.name+ pendingRestoreTarget = FocusRestoreTarget.CHANNEL+ focusRestoreNonce+++ val focusedImmediately = requestChannelFocus(preferredChannelId)+ scope.launch {+ kotlinx.coroutines.delay(60)+ val focused = requestChannelFocus(preferredChannelId)+ if (!focused) {+ pendingRestoreTarget = FocusRestoreTarget.CHANNEL+ focusRestoreNonce+++ }+ }+ return focusedImmediately+ }val displayedCategory = uiState.selectedCategory?.takeIf { !isCategoryLocked(it) }val hasBlockedCategorySearch =@@ -430,6 +528,25 @@ fun HomeScreen(channelFocusRequesters.keys.retainAll(validIds)}+ LaunchedEffect(+ uiState.isLoading,+ uiState.filteredChannels,+ uiState.selectedCategory?.id,+ pendingCategoryContentJumpCategoryId+ ) {+ val pendingCategoryId = pendingCategoryContentJumpCategoryId ?: return@LaunchedEffect+ if (uiState.selectedCategory?.id != pendingCategoryId) {+ pendingCategoryContentJumpCategoryId = null+ return@LaunchedEffect+ }+ if (uiState.isLoading) return@LaunchedEffect++ if (uiState.filteredChannels.isNotEmpty()) {+ requestChannelFocusFromCategory()+ }+ pendingCategoryContentJumpCategoryId = null+ }+LaunchedEffect(uiState.categories, uiState.selectedCategory?.id, uiState.parentalControlLevel, isReorderMode) {if (isReorderMode) return@LaunchedEffectval selectedCategory = uiState.selectedCategory ?: return@LaunchedEffect@@ -445,6 +562,7 @@ fun HomeScreen(LaunchedEffect(uiState.showDialog,showPinDialog,+ showAddQuickFilterDialog,uiState.showDeleteGroupDialog,uiState.selectedCategoryForOptions,uiState.showRenameGroupDialog,@@ -455,6 +573,7 @@ fun HomeScreen(val modalClosed =!uiState.showDialog &&!showPinDialog &&+ !showAddQuickFilterDialog &&!uiState.showDeleteGroupDialog &&!uiState.showRenameGroupDialog &&!showSplitManagerDialog &&@@ -487,37 +606,23 @@ fun HomeScreen(val restoreTarget = pendingRestoreTarget ?: return@LaunchedEffectkotlinx.coroutines.delay(80)val restored = when (restoreTarget) {- FocusRestoreTarget.CHANNEL -> {- val channelId = lastFocusedChannelId- channelId != null && runCatching {- channelFocusRequesters[channelId]?.requestFocus()- }.isSuccess- }- FocusRestoreTarget.CATEGORY -> {- val categoryId = lastFocusedCategoryId- categoryId != null && runCatching {- categoryFocusRequesters[categoryId]?.requestFocus()- }.isSuccess- }+ FocusRestoreTarget.CHANNEL -> requestChannelFocus(lastFocusedChannelId)+ FocusRestoreTarget.CATEGORY -> requestCategoryFocus(lastFocusedCategoryId)}if (!restored) {when (restoreTarget) {FocusRestoreTarget.CHANNEL -> {val fallbackChannelId = uiState.filteredChannels.firstOrNull()?.idif (fallbackChannelId != null) {- runCatching { channelFocusRequesters[fallbackChannelId]?.requestFocus() }+ requestChannelFocus(fallbackChannelId)} else {val fallbackCategoryId = uiState.categories.firstOrNull()?.id- fallbackCategoryId?.let {- runCatching { categoryFocusRequesters[it]?.requestFocus() }- }+ requestCategoryFocus(fallbackCategoryId)}}FocusRestoreTarget.CATEGORY -> {val fallbackCategoryId = uiState.categories.firstOrNull()?.id- fallbackCategoryId?.let {- runCatching { categoryFocusRequesters[it]?.requestFocus() }- }+ requestCategoryFocus(fallbackCategoryId)}}}@@ -562,6 +667,9 @@ fun HomeScreen() {// Sticky Header PartColumn(modifier = Modifier.padding(horizontal = 10.dp)) {+ var showQuickFiltersDrawer by rememberSaveable(uiState.savedCategoryFilters) {+ mutableStateOf(false)+ }Text(text = stringResource(R.string.home_categories_title),style = MaterialTheme.typography.titleMedium,@@ -580,6 +688,138 @@ fun HomeScreen(modifier = Modifier.padding(bottom = 10.dp),enabled = !isReorderMode)+ val shouldShowQuickFiltersControl = when (uiState.liveTvQuickFilterVisibilityMode) {+ LiveTvQuickFilterVisibilityMode.HIDE -> false+ LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> uiState.savedCategoryFilters.isNotEmpty()+ LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> true+ }+ if (shouldShowQuickFiltersControl) {+ val activeSavedFilter = uiState.activeCategoryFilter+ val filterSubtitle = when {+ uiState.categorySearchQuery.isBlank() -> {+ stringResource(R.string.home_quick_filters_showing_all)+ }+ activeSavedFilter != null -> {+ stringResource(+ R.string.home_quick_filters_active,+ activeSavedFilter+ )+ }+ else -> {+ stringResource(+ R.string.home_quick_filters_manual_search,+ uiState.categorySearchQuery+ )+ }+ }+ TvClickableSurface(+ onClick = { if (!isReorderMode) showQuickFiltersDrawer = !showQuickFiltersDrawer },+ enabled = !isReorderMode,+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 10.dp),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = SurfaceHighlight.copy(alpha = 0.9f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, Primary.copy(alpha = 0.85f)),+ shape = RoundedCornerShape(12.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.home_quick_filters_button),+ style = MaterialTheme.typography.labelLarge,+ color = OnSurface+ )+ Text(+ text = if (showQuickFiltersDrawer) {+ stringResource(R.string.home_quick_filters_hide)+ } else {+ stringResource(R.string.home_quick_filters_show)+ },+ style = MaterialTheme.typography.labelMedium,+ color = Primary+ )+ }+ Text(+ text = filterSubtitle,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ if (showQuickFiltersDrawer) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 8.dp),+ horizontalArrangement = Arrangement.End+ ) {+ TvButton(+ onClick = { showAddQuickFilterDialog = true },+ enabled = !isReorderMode+ ) {+ Text(stringResource(R.string.home_quick_filters_add_chip))+ }+ }+ if (uiState.savedCategoryFilters.isNotEmpty() || uiState.categorySearchQuery.isNotBlank()) {+ SelectionChipRow(+ title = stringResource(R.string.home_quick_filters_title),+ chips = buildList {+ add(+ SelectionChip(+ key = HOME_ALL_FILTER_KEY,+ label = stringResource(R.string.home_quick_filters_all)+ )+ )+ addAll(+ uiState.savedCategoryFilters.map { filter ->+ SelectionChip(key = filter, label = filter)+ }+ )+ },+ selectedKey = uiState.activeCategoryFilter ?: HOME_ALL_FILTER_KEY.takeIf {+ uiState.categorySearchQuery.isBlank()+ },+ onChipSelected = { filter ->+ if (!isReorderMode) {+ if (filter == HOME_ALL_FILTER_KEY) {+ viewModel.clearCategorySearchQuery()+ } else {+ viewModel.applySavedCategoryFilter(filter)+ }+ showQuickFiltersDrawer = false+ }+ },+ modifier = Modifier.padding(bottom = 10.dp),+ contentPadding = PaddingValues(horizontal = 0.dp)+ )+ } else {+ Text(+ text = stringResource(R.string.home_quick_filters_empty),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ modifier = Modifier.padding(start = 4.dp, bottom = 10.dp)+ )+ }+ }+ }}LazyColumn(@@ -630,7 +870,7 @@ fun HomeScreen(fontWeight = FontWeight.Medium)Text(- text = stringResource(R.string.label_slots_count, splitSlots.count { it != null }),+ text = stringResource(R.string.label_slots_count, uiState.multiviewChannelCount),style = androidx.compose.ui.text.TextStyle(fontSize = 9.sp,color = Color(0xFF81C784)@@ -654,6 +894,7 @@ fun HomeScreen(category = category,isSelected = category.id == uiState.selectedCategory?.id,isLocked = isLocked,+ isPinned = category.id in uiState.pinnedCategoryIds,focusRequester = categoryFocusRequester,onClick = {if (isReorderMode) return@CategoryItem@@ -669,28 +910,26 @@ fun HomeScreen(preferredRestoreTarget = FocusRestoreTarget.CATEGORY.nameviewModel.showCategoryOptions(category)},- onJumpToSearch = { categorySearchFocusRequester.requestFocus() },+ onJumpToSearch = {+ runCatching { categorySearchFocusRequester.requestFocus() }.isSuccess+ },onJumpToContent = {- if (uiState.filteredChannels.isNotEmpty()) {- val preferredChannelId = lastFocusedChannelId- ?.takeIf { channelId -> uiState.filteredChannels.any { it.id == channelId } }- ?: uiState.filteredChannels.first().id- lastFocusedChannelId = preferredChannelId- preferredRestoreTarget = FocusRestoreTarget.CHANNEL.name- pendingRestoreTarget = FocusRestoreTarget.CHANNEL- focusRestoreNonce++- scope.launch {- kotlinx.coroutines.delay(60)- val focused = runCatching {- channelFocusRequesters[preferredChannelId]?.requestFocus()- }.getOrNull() != null- if (!focused) {- pendingRestoreTarget = FocusRestoreTarget.CHANNEL- focusRestoreNonce++- }- }+ if (isLocked) {+ pendingCategoryContentJumpCategoryId = null+ false+ } else if (uiState.selectedCategory?.id != category.id) {+ pendingCategoryContentJumpCategoryId = category.id+ viewModel.selectCategory(category)+ true+ } else if (uiState.isLoading) {+ pendingCategoryContentJumpCategoryId = category.id+ true+ } else if (uiState.filteredChannels.isNotEmpty()) {+ pendingCategoryContentJumpCategoryId = null+ requestChannelFocusFromCategory()} else {- runCatching { channelSearchFocusRequester.requestFocus() }+ pendingCategoryContentJumpCategoryId = null+ false}},onFocused = { lastFocusedCategoryId = category.id }@@ -774,7 +1013,7 @@ fun HomeScreen()if (hasSplitChannels) {StatusPill(- label = stringResource(R.string.split_count_format, stringResource(R.string.live_shell_split), splitSlots.count { it != null })+ label = stringResource(R.string.split_count_format, stringResource(R.string.live_shell_split), uiState.multiviewChannelCount))}}@@ -889,6 +1128,27 @@ fun HomeScreen(}}+ LaunchedEffect(isReorderMode, draggingChannel?.id, uiState.filteredChannels) {+ if (!isReorderMode) return@LaunchedEffect+ val draggingChannelId = draggingChannel?.id ?: return@LaunchedEffect+ val draggedIndex = uiState.filteredChannels.indexOfFirst { it.id == draggingChannelId }+ if (draggedIndex < 0) return@LaunchedEffect++ val visibleItems = channelListState.layoutInfo.visibleItemsInfo+ val firstVisibleIndex = visibleItems.firstOrNull()?.index+ val lastVisibleIndex = visibleItems.lastOrNull()?.index++ if (+ firstVisibleIndex != null &&+ lastVisibleIndex != null &&+ (draggedIndex <= firstVisibleIndex || draggedIndex >= lastVisibleIndex)+ ) {+ channelListState.scrollToItem(draggedIndex)+ }++ runCatching { channelFocusRequesters[draggingChannelId]?.requestFocus() }+ }+LaunchedEffect(channelListState, uiState.filteredChannels, lastFocusedChannelId) {snapshotFlow {channelListState.layoutInfo.visibleItemsInfo.mapNotNull { item ->@@ -1282,11 +1542,12 @@ private fun CategoryItem(category: Category,isSelected: Boolean,isLocked: Boolean = false,+ isPinned: Boolean = false,focusRequester: FocusRequester,onClick: () -> Unit,onLongClick: (() -> Unit)? = null,- onJumpToSearch: () -> Unit,- onJumpToContent: () -> Unit,+ onJumpToSearch: () -> Boolean,+ onJumpToContent: () -> Boolean,onFocused: () -> Unit) {var isFocused by remember { mutableStateOf(false) }@@ -1307,11 +1568,9 @@ private fun CategoryItem(when (event.nativeKeyEvent.keyCode) {android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {onJumpToSearch()- true}android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {onJumpToContent()- true}else -> false}@@ -1336,6 +1595,12 @@ private fun CategoryItem(verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.SpaceBetween) {+ if (isPinned) {+ PinnedCategoryGlyph(+ tint = if (isFocused) OnBackground else if (isSelected) Primary else OnSurfaceDim,+ modifier = Modifier.padding(end = 8.dp)+ )+ }Text(text = category.name,style = MaterialTheme.typography.bodyMedium,@@ -1364,6 +1629,35 @@ private fun CategoryItem(}}+@Composable+private fun PinnedCategoryGlyph(+ tint: Color,+ modifier: Modifier = Modifier+) {+ Canvas(modifier = modifier.size(12.dp)) {+ val headRadius = size.minDimension * 0.18f+ val centerX = size.width * 0.45f+ val headCenterY = size.height * 0.26f+ drawCircle(+ color = tint,+ radius = headRadius,+ center = androidx.compose.ui.geometry.Offset(centerX, headCenterY)+ )+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(centerX, headCenterY + headRadius * 0.6f),+ end = androidx.compose.ui.geometry.Offset(centerX, size.height * 0.8f),+ strokeWidth = size.minDimension * 0.12f+ )+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.38f),+ end = androidx.compose.ui.geometry.Offset(size.width * 0.72f, size.height * 0.38f),+ strokeWidth = size.minDimension * 0.14f+ )+ }+}+// SearchInput moved to its own component file@Composablediff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktindex b266eafe..4cc37c11 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt@@ -4,9 +4,11 @@ import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.di.AuxiliaryPlayerEngineimport com.streamvault.app.tvinput.TvInputChannelSyncManager+import com.streamvault.app.ui.screens.multiview.MultiViewManagerimport com.streamvault.app.ui.model.applyProviderCategoryDisplayPreferencesimport com.streamvault.app.ui.model.guideLookupKeyimport com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.sync.SyncManagerimport com.streamvault.domain.manager.ParentalControlManager@@ -64,6 +66,7 @@ class HomeViewModel @Inject constructor(private val parentalControlManager: ParentalControlManager,private val syncManager: SyncManager,private val tvInputChannelSyncManager: TvInputChannelSyncManager,+ private val multiViewManager: MultiViewManager,@AuxiliaryPlayerEngineprivate val playerEngineProvider: InjectProvider<PlayerEngine>) : ViewModel() {@@ -91,6 +94,11 @@ class HomeViewModel @Inject constructor(init {loadAllProviders()+ viewModelScope.launch {+ multiViewManager.slots.collect { slots ->+ _uiState.update { it.copy(multiviewChannelCount = slots.count { it != null }) }+ }+ }viewModelScope.launch {providerRepository.getActiveProvider().filterNotNull()@@ -208,6 +216,29 @@ class HomeViewModel @Inject constructor(}}+ viewModelScope.launch {+ preferencesRepository.liveTvCategoryFilters.collectLatest { filters ->+ _uiState.update { state ->+ val activeFilter = state.activeCategoryFilter+ ?.takeIf { selected -> filters.any { it.equals(selected, ignoreCase = true) } }+ ?: filters.firstOrNull { it == state.categorySearchQuery }+ state.copy(+ savedCategoryFilters = filters,+ activeCategoryFilter = activeFilter+ )+ }+ }+ }++ viewModelScope.launch {+ preferencesRepository.liveTvQuickFilterVisibility+ .map(LiveTvQuickFilterVisibilityMode::fromStorage)+ .distinctUntilChanged()+ .collectLatest { mode ->+ _uiState.update { it.copy(liveTvQuickFilterVisibilityMode = mode) }+ }+ }+viewModelScope.launch {_uiState.map { it.provider?.id }.distinctUntilChanged()@@ -255,7 +286,8 @@ class HomeViewModel @Inject constructor(preferencesRepository.defaultCategoryId,preferencesRepository.getLastLiveCategoryId(providerId),preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),- preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE)+ preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE),+ preferencesRepository.getPinnedCategoryIds(providerId, ContentType.LIVE)) { values ->val providerCats = values[0] as List<Category>val customCats = values[1] as List<Category>@@ -263,6 +295,7 @@ class HomeViewModel @Inject constructor(val lastVisitedCategoryId = values[3] as Long?val hiddenCategoryIds = values[4] as Set<Long>val sortMode = values[5] as CategorySortMode+ val pinnedCategoryIds = values[6] as Set<Long>val recentCategory = Category(id = VirtualCategoryIds.RECENT,name = "Recent",@@ -283,6 +316,8 @@ class HomeViewModel @Inject constructor(hiddenCategoryIds = hiddenCategoryIds,sortMode = sortMode)+ val pinnedProviderCategories = visibleProviderCategories.filter { it.id in pinnedCategoryIds }+ val unpinnedProviderCategories = visibleProviderCategories.filterNot { it.id in pinnedCategoryIds }val orderedCategories = buildList {val favoritesCategory = customCats.find { it.id == VirtualCategoryIds.FAVORITES }@@ -292,13 +327,15 @@ class HomeViewModel @Inject constructor(add(recentCategory)addAll(customCats.filter { it.id != VirtualCategoryIds.FAVORITES })add(allChannelsCategory)- addAll(visibleProviderCategories)+ addAll(pinnedProviderCategories)+ addAll(unpinnedProviderCategories)}CategorySelectionContext(categories = orderedCategories,defaultCategoryId = defaultId,- lastVisitedCategoryId = lastVisitedCategoryId+ lastVisitedCategoryId = lastVisitedCategoryId,+ pinnedCategoryIds = pinnedCategoryIds)}.collect { selectionContext ->val categories = selectionContext.categories@@ -311,7 +348,8 @@ class HomeViewModel @Inject constructor(it.copy(categories = categories,lastVisitedCategory = lastVisitedCategory,- isCategoriesLoading = false+ isCategoriesLoading = false,+ pinnedCategoryIds = selectionContext.pinnedCategoryIds)}@@ -365,10 +403,19 @@ class HomeViewModel @Inject constructor(fun selectCategory(category: Category) {if (_uiState.value.selectedCategory?.id == category.id) return+ _uiState.value.provider?.id?.let { providerId ->+ parentalControlManager.retainUnlockedCategory(+ providerId = providerId,+ categoryId = category.id.takeIf { !category.isVirtual && it > 0L }+ )+ }clearPreview()+ _localChannels.value = emptyList()_uiState.update {it.copy(selectedCategory = category,+ filteredChannels = emptyList(),+ hasChannels = false,isLoading = true,errorMessage = null)@@ -493,7 +540,70 @@ class HomeViewModel @Inject constructor(fun updateCategorySearchQuery(query: String) {if (_uiState.value.isChannelReorderMode) return- _uiState.update { it.copy(categorySearchQuery = query) }+ _uiState.update { state ->+ state.copy(+ categorySearchQuery = query,+ activeCategoryFilter = state.savedCategoryFilters.firstOrNull {+ it.equals(query, ignoreCase = true)+ }+ )+ }+ }++ fun applySavedCategoryFilter(filter: String) {+ if (_uiState.value.isChannelReorderMode) return+ _uiState.update { state ->+ val shouldClear = state.activeCategoryFilter == filter && state.categorySearchQuery == filter+ state.copy(+ categorySearchQuery = if (shouldClear) "" else filter,+ activeCategoryFilter = if (shouldClear) null else filter+ )+ }+ }++ fun clearCategorySearchQuery() {+ if (_uiState.value.isChannelReorderMode) return+ _uiState.update {+ it.copy(+ categorySearchQuery = "",+ activeCategoryFilter = null+ )+ }+ }++ fun addLiveTvCategoryFilter(filter: String) {+ viewModelScope.launch {+ val normalized = filter.trim()+ when {+ normalized.isBlank() -> {+ _uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_live_tv_quick_filter_blank))+ }+ }+ _uiState.value.savedCategoryFilters.any { existing ->+ existing.equals(normalized, ignoreCase = true)+ } -> {+ _uiState.update {+ it.copy(+ userMessage = appContext.getString(+ R.string.settings_live_tv_quick_filter_duplicate,+ normalized+ )+ )+ }+ }+ preferencesRepository.addLiveTvCategoryFilter(normalized) -> {+ _uiState.update {+ it.copy(+ userMessage = appContext.getString(+ R.string.settings_live_tv_quick_filter_added,+ normalized+ )+ )+ }+ }+ }+ }}fun clearVisibleChannelsForFilteredCategories() {@@ -1014,6 +1124,29 @@ class HomeViewModel @Inject constructor(}}+ fun toggleCategoryPinned(category: Category) {+ if (category.isVirtual || category.id == ChannelRepository.ALL_CHANNELS_ID) return+ val providerId = _uiState.value.provider?.id ?: return+ val shouldPin = category.id !in _uiState.value.pinnedCategoryIds+ viewModelScope.launch {+ preferencesRepository.setCategoryPinned(+ providerId = providerId,+ type = ContentType.LIVE,+ categoryId = category.id,+ pinned = shouldPin+ )+ dismissCategoryOptions()+ _uiState.update {+ it.copy(+ userMessage = appContext.getString(+ if (shouldPin) R.string.category_pinned else R.string.category_unpinned,+ category.name+ )+ )+ }+ }+ }+fun enterChannelReorderMode(category: Category) {dismissCategoryOptions()viewModelScope.launch {@@ -1160,6 +1293,9 @@ data class HomeUiState(val isCategoriesLoading: Boolean = true,val isSyncing: Boolean = false,val categorySearchQuery: String = "",+ val savedCategoryFilters: List<String> = emptyList(),+ val activeCategoryFilter: String? = null,+ val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,val channelSearchQuery: String = "",val showDialog: Boolean = false,val selectedChannelForDialog: Channel? = null,@@ -1172,6 +1308,7 @@ data class HomeUiState(val groupToDelete: Category? = null,val parentalControlLevel: Int = 0,val unlockedCategoryIds: Set<Long> = emptySet(),+ val pinnedCategoryIds: Set<Long> = emptySet(),val selectedCategoryForOptions: Category? = null,val isChannelReorderMode: Boolean = false,val reorderCategory: Category? = null,@@ -1180,11 +1317,13 @@ data class HomeUiState(val previewPlayerEngine: PlayerEngine? = null,val isPreviewLoading: Boolean = false,val previewErrorMessage: String? = null,- val errorMessage: String? = null+ val errorMessage: String? = null,+ val multiviewChannelCount: Int = 0)private data class CategorySelectionContext(val categories: List<Category>,val defaultCategoryId: Long?,- val lastVisitedCategoryId: Long?+ val lastVisitedCategoryId: Long?,+ val pinnedCategoryIds: Set<Long>)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.ktindex 6fe0b030..3366b4dd 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt@@ -46,10 +46,12 @@ import com.streamvault.app.Rimport com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.components.shell.ContentMetadataStrip+import com.streamvault.app.ui.components.shell.ExternalRatingsStripimport com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.model.formatVodRatingLabel+import com.streamvault.domain.model.ExternalRatingsimport com.streamvault.domain.model.Movieimport com.streamvault.app.ui.interaction.TvClickableSurfaceimport com.streamvault.app.ui.interaction.TvButton@@ -94,6 +96,8 @@ fun MovieDetailScreen(MovieDetailContent(movie = movie,hasResume = uiState.hasResume,+ externalRatings = uiState.externalRatings,+ isLoadingExternalRatings = uiState.isLoadingExternalRatings,onPlay = { onPlay(movie) },onBack = onBack)@@ -105,6 +109,8 @@ fun MovieDetailScreen(private fun MovieDetailContent(movie: Movie,hasResume: Boolean,+ externalRatings: ExternalRatings,+ isLoadingExternalRatings: Boolean,onPlay: () -> Unit,onBack: () -> Unit) {@@ -185,6 +191,8 @@ private fun MovieDetailContent(MovieDetailHeroText(movie = movie,hasResume = hasResume,+ externalRatings = externalRatings,+ isLoadingExternalRatings = isLoadingExternalRatings,onPlay = onPlay,playButtonFocusRequester = playButtonFocusRequester,onPlayTrailer = {@@ -203,6 +211,8 @@ private fun MovieDetailContent(MovieDetailHeroText(movie = movie,hasResume = hasResume,+ externalRatings = externalRatings,+ isLoadingExternalRatings = isLoadingExternalRatings,onPlay = onPlay,playButtonFocusRequester = playButtonFocusRequester,onPlayTrailer = {@@ -244,6 +254,8 @@ private fun MoviePoster(private fun MovieDetailHeroText(movie: Movie,hasResume: Boolean,+ externalRatings: ExternalRatings,+ isLoadingExternalRatings: Boolean,onPlay: () -> Unit,playButtonFocusRequester: FocusRequester,onPlayTrailer: () -> Unit,@@ -284,6 +296,11 @@ private fun MovieDetailHeroText())+ ExternalRatingsStrip(+ ratings = externalRatings,+ isLoading = isLoadingExternalRatings+ )+MovieFactGrid(movie = movie)Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.ktindex 8527ab25..9b4bd12e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt@@ -4,9 +4,12 @@ import androidx.lifecycle.SavedStateHandleimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.streamvault.app.util.isPlaybackComplete+import com.streamvault.domain.model.ExternalRatings+import com.streamvault.domain.model.ExternalRatingsLookupimport com.streamvault.domain.model.Movieimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.repository.ExternalRatingsRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepository@@ -24,7 +27,8 @@ class MovieDetailViewModel @Inject constructor(savedStateHandle: SavedStateHandle,private val movieRepository: MovieRepository,private val providerRepository: ProviderRepository,- private val playbackHistoryRepository: PlaybackHistoryRepository+ private val playbackHistoryRepository: PlaybackHistoryRepository,+ private val externalRatingsRepository: ExternalRatingsRepository) : ViewModel() {private val movieId: Long = checkNotNull(@@ -69,6 +73,8 @@ class MovieDetailViewModel @Inject constructor(hasResume = hasResume,resumePositionMs = if (hasResume) resumePositionMs else 0L)+ }.also {+ loadExternalRatings(result.data)}is Result.Error -> _uiState.update {it.copy(isLoading = false, error = result.message)@@ -79,6 +85,33 @@ class MovieDetailViewModel @Inject constructor(}}}++ private fun loadExternalRatings(movie: Movie) {+ viewModelScope.launch {+ _uiState.update { it.copy(isLoadingExternalRatings = true) }+ val ratingsResult = externalRatingsRepository.getRatings(+ ExternalRatingsLookup(+ contentType = ContentType.MOVIE,+ title = movie.name,+ releaseYear = movie.year ?: movie.releaseDate,+ tmdbId = movie.tmdbId+ )+ )+ _uiState.update { currentState ->+ when (ratingsResult) {+ is Result.Success -> currentState.copy(+ isLoadingExternalRatings = false,+ externalRatings = ratingsResult.data+ )+ is Result.Error -> currentState.copy(+ isLoadingExternalRatings = false,+ externalRatings = ExternalRatings.unavailable()+ )+ is Result.Loading -> currentState+ }+ }+ }+ }}data class MovieDetailUiState(@@ -86,5 +119,7 @@ data class MovieDetailUiState(val movie: Movie? = null,val error: String? = null,val hasResume: Boolean = false,- val resumePositionMs: Long = 0L+ val resumePositionMs: Long = 0L,+ val isLoadingExternalRatings: Boolean = false,+ val externalRatings: ExternalRatings = ExternalRatings.unavailable())diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.ktindex dfc28af3..b613d514 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt@@ -173,7 +173,7 @@ fun MoviesScreen(subtitle = uiState.errorMessage ?: "")}- } else if (uiState.moviesByCategory.isEmpty()) {+ } else if (uiState.moviesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {AppMessageState(title = stringResource(R.string.movies_no_found),@@ -220,6 +220,7 @@ fun MoviesScreen(viewModel.selectFullLibraryBrowse()},onLoadMore = viewModel::loadMoreSelectedCategory,+ onLoadMorePreviewRows = viewModel::loadMorePreviewRows,onDismissReorder = viewModel::exitCategoryReorderMode)}@@ -309,6 +310,7 @@ private fun MoviesVodContent(onOpenTopRated: () -> Unit,onOpenFresh: () -> Unit,onLoadMore: () -> Unit,+ onLoadMorePreviewRows: () -> Unit,onDismissReorder: () -> Unit) {val screenWidth = LocalConfiguration.current.screenWidthDp.dp@@ -587,7 +589,7 @@ private fun MoviesVodContent(val catEntries = uiState.moviesByCategory.entries.filter { (name, items) ->name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()- }.take(8).toList()+ }.toList()items(catEntries, key = { it.key }) { entry ->val categoryName = entry.keyval movies = entry.value@@ -610,6 +612,25 @@ private fun MoviesVodContent()}}+ if (uiState.isLoadingPreviewRows) {+ item(key = "preview_loading") {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 24.dp),+ contentAlignment = Alignment.Center+ ) {+ CircularProgressIndicator(color = Color.White, modifier = Modifier.size(32.dp))+ }+ }+ }+ if (uiState.hasMorePreviewRows && !uiState.isLoadingPreviewRows && catEntries.isNotEmpty()) {+ item(key = "load_more_preview_trigger") {+ LaunchedEffect(catEntries.size) {+ onLoadMorePreviewRows()+ }+ }+ }}return}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.ktindex e6979c7f..2e2ec97f 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt@@ -91,6 +91,14 @@ class MoviesViewModel @Inject constructor(private val _selectedCategoryLoadLimit = MutableStateFlow(VodBrowseDefaults.SELECTED_CATEGORY_PAGE_SIZE)private val _selectedLibraryFilterType = MutableStateFlow(LibraryFilterType.ALL)private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)+ private val _previewBatchSize = MutableStateFlow(8)+ private var activeProviderId: Long? = null++ private data class PreviewLoadResult(+ val snapshot: MovieCatalogSnapshot,+ val isLoadingPreviewRows: Boolean,+ val hasMorePreviewRows: Boolean+ )init {viewModelScope.launch {@@ -98,6 +106,7 @@ class MoviesViewModel @Inject constructor(providerRepository.getActiveProvider().filterNotNull().flatMapLatest { provider ->+ activeProviderId = provider.idcombine(favoriteRepository.getAllFavorites(ContentType.MOVIE),getCustomCategories(ContentType.MOVIE),@@ -143,32 +152,57 @@ class MoviesViewModel @Inject constructor(}}.flatMapLatest { params ->- flow {- emit(- if (params.query.isBlank()) {- buildPreviewCatalog(params)- } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {- buildSearchCatalog(- movies = emptyList(),- allFavorites = params.allFavorites,- customCategories = params.customCategories,- providerCategories = params.providerCategories,- hiddenCategoryIds = params.hiddenCategoryIds- ).copy(libraryCount = 0)+ _previewBatchSize.value = 8+ _previewBatchSize.flatMapLatest { batchSize ->+ if (params.query.isBlank()) {+ val categoryIds = params.providerCategories.take(batchSize).map { it.id }+ if (categoryIds.isEmpty()) {+ flow {+ emit(PreviewLoadResult(buildPreviewCatalog(params, emptyMap()), false, false))+ }} else {+ movieRepository.getCategoryPreviewRows(+ providerId = params.providerId,+ categoryIds = categoryIds,+ limitPerCategory = VodBrowseDefaults.PREVIEW_ROW_LIMIT+ ).map { providerPreviews ->+ val isLoading = categoryIds.all { id -> providerPreviews[id].isNullOrEmpty() }+ val hasMore = params.providerCategories.size > batchSize+ PreviewLoadResult(buildPreviewCatalog(params, providerPreviews), isLoading, hasMore)+ }+ }+ } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {+ flow {+ emit(PreviewLoadResult(+ buildSearchCatalog(+ movies = emptyList(),+ allFavorites = params.allFavorites,+ customCategories = params.customCategories,+ providerCategories = params.providerCategories,+ hiddenCategoryIds = params.hiddenCategoryIds+ ).copy(libraryCount = 0),+ false, false+ ))+ }+ } else {+ flow {val searchResults = movieRepository.searchMovies(params.providerId, params.query).first()- buildSearchCatalog(- movies = searchResults,- allFavorites = params.allFavorites,- customCategories = params.customCategories,- providerCategories = params.providerCategories,- hiddenCategoryIds = params.hiddenCategoryIds- ).copy(libraryCount = searchResults.size)+ emit(PreviewLoadResult(+ buildSearchCatalog(+ movies = searchResults,+ allFavorites = params.allFavorites,+ customCategories = params.customCategories,+ providerCategories = params.providerCategories,+ hiddenCategoryIds = params.hiddenCategoryIds+ ).copy(libraryCount = searchResults.size),+ false, false+ ))}- )+ }}}- .collect { snapshot ->+ .collect { result ->+ val snapshot = result.snapshotval isReordering = _uiState.value.isReorderModeval currentSelected = _uiState.value.selectedCategoryval preserveSelectedCategory = currentSelected != null && _searchQuery.value.isNotBlank()@@ -191,6 +225,8 @@ class MoviesViewModel @Inject constructor(canLoadMoreSelectedCategory = if (resolvedSelected == null) false else it.canLoadMoreSelectedCategory,filteredMovies = if (isReordering) it.filteredMovies else emptyList(),isLoading = false,+ isLoadingPreviewRows = result.isLoadingPreviewRows,+ hasMorePreviewRows = result.hasMorePreviewRows,errorMessage = null)}@@ -402,6 +438,12 @@ class MoviesViewModel @Inject constructor(}fun selectCategory(categoryName: String?) {+ activeProviderId?.let { providerId ->+ parentalControlManager.retainUnlockedCategory(+ providerId = providerId,+ categoryId = resolveProviderCategoryId(categoryName)+ )+ }selectVodCategory(categoryName = categoryName,selectedCategoryLoadLimit = _selectedCategoryLoadLimit,@@ -433,6 +475,12 @@ class MoviesViewModel @Inject constructor()}+ fun loadMorePreviewRows() {+ if (_uiState.value.hasMorePreviewRows && !_uiState.value.isLoadingPreviewRows) {+ _previewBatchSize.update { it + 8 }+ }+ }+fun setSearchQuery(query: String) {setVodSearchQuery(query, _searchQuery, _uiState) { updatedQuery ->copy(searchQuery = updatedQuery)@@ -621,6 +669,11 @@ class MoviesViewModel @Inject constructor(_uiState.update { it.copy(selectedCategoryForOptions = null) }}+ private fun resolveProviderCategoryId(categoryName: String?): Long? =+ _uiState.value.providerCategories+ .firstOrNull { it.name == categoryName && !it.isVirtual && it.id > 0L }+ ?.id+fun hideCategory(category: Category) {if (category.isVirtual) returnviewModelScope.launch {@@ -787,10 +840,10 @@ class MoviesViewModel @Inject constructor(}private suspend fun buildPreviewCatalog(- params: MovieCatalogParams+ params: MovieCatalogParams,+ providerPreviews: Map<Long?, List<Movie>>): MovieCatalogSnapshot {val snapshot = buildVodPreviewCatalog(- providerId = params.providerId,allFavorites = params.allFavorites,customCategories = params.customCategories,providerCategories = params.providerCategories,@@ -798,13 +851,7 @@ class MoviesViewModel @Inject constructor(libraryCount = params.libraryCount,hiddenProviderCategoryIds = params.hiddenCategoryIds,loadItemsByIds = { ids -> movieRepository.getMoviesByIds(ids).first() },- loadCategoryPreviewRows = { providerId, limit ->- movieRepository.getCategoryPreviewRows(- providerId = providerId,- categoryIds = params.providerCategories.take(8).map { it.id },- limitPerCategory = limit- ).first()- },+ providerPreviews = providerPreviews,itemId = Movie::id,itemCategoryId = Movie::categoryId,copyWithFavorite = { movie, isFavorite -> movie.copy(isFavorite = isFavorite) }@@ -1125,6 +1172,8 @@ data class MoviesUiState(val vodViewMode: VodViewMode = VodViewMode.MODERN,val continueWatching: List<PlaybackHistory> = emptyList(),val isLoading: Boolean = true,+ val isLoadingPreviewRows: Boolean = false,+ val hasMorePreviewRows: Boolean = false,val parentalControlLevel: Int = 0,val unlockedCategoryIds: Set<Long> = emptySet(),val showDialog: Boolean = false,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.ktindex 114202c1..9bf8610a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt@@ -1,4 +1,4 @@-package com.streamvault.app.ui.screens.multiview+package com.streamvault.app.ui.screens.multiviewimport android.app.Activityimport android.view.View@@ -528,7 +528,7 @@ private fun MultiViewControlHud(color = Color.White.copy(alpha = 0.86f),style = MaterialTheme.typography.labelMedium)- Text(text = "•", color = Color.White.copy(alpha = 0.42f))+ Text(text = "Γאó", color = Color.White.copy(alpha = 0.42f))Text(text = stringResource(R.string.multiview_telemetry_snapshot,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.ktindex ad83aa51..3fe330e5 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt@@ -440,6 +440,10 @@ class MultiViewViewModel @Inject constructor(fun selectPickerCategory(category: Category) {val providerId = currentProviderId ?: return+ parentalControlManager.retainUnlockedCategory(+ providerId = providerId,+ categoryId = category.id.takeIf { !category.isVirtual && it > 0L }+ )viewModelScope.launch {_uiState.value = _uiState.value.copy(pickerState = _uiState.value.pickerState.copy(@@ -475,6 +479,7 @@ class MultiViewViewModel @Inject constructor(}fun backToPickerCategories() {+ currentProviderId?.let { parentalControlManager.clearUnlockedCategories(it) }_uiState.value = _uiState.value.copy(pickerState = _uiState.value.pickerState.copy(selectedCategory = null,@@ -486,6 +491,7 @@ class MultiViewViewModel @Inject constructor(}fun resetPicker() {+ currentProviderId?.let { parentalControlManager.clearUnlockedCategories(it) }_uiState.value = _uiState.value.copy(pickerState = MultiViewPickerState())}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex 58f507f4..285da6a9 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt@@ -15,6 +15,7 @@ import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.input.key.onKeyEventimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalConfiguration@@ -61,6 +62,8 @@ import javax.inject.Injectimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.LazyRowimport androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.material3.Sliderimport androidx.compose.material3.SliderDefaultsimport androidx.compose.material3.CircularProgressIndicator@@ -172,6 +175,7 @@ fun PlayerScreen(val playbackSpeed by viewModel.playbackSpeed.collectAsStateWithLifecycle()val castConnectionState by viewModel.castConnectionState.collectAsStateWithLifecycle()val seekPreview by viewModel.seekPreview.collectAsStateWithLifecycle()+ val preventStandbyDuringPlayback by viewModel.preventStandbyDuringPlayback.collectAsStateWithLifecycle()var showTrackSelection by remember { mutableStateOf<TrackType?>(null) }var showSpeedSelection by remember { mutableStateOf(false) }@@ -242,8 +246,11 @@ fun PlayerScreen(DisposableEffect(Unit) {onDispose { playerWindow?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) }}- LaunchedEffect(isPlaying, playbackState) {- if (isPlaying || playbackState == PlaybackState.BUFFERING) {+ LaunchedEffect(preventStandbyDuringPlayback, isPlaying, playbackState) {+ if (preventStandbyDuringPlayback) {+ // Keep screen always on while in player — prevents TV OS standby nag+ playerWindow?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)+ } else if (isPlaying || playbackState == PlaybackState.BUFFERING) {playerWindow?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)} else {playerWindow?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)@@ -253,9 +260,9 @@ fun PlayerScreen(// Consolidated focus management for all overlaysval liveOverlayVisible = contentType == "LIVE" && (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay)val anyOverlayVisible = liveOverlayVisible || showTrackSelection != null || showSpeedSelection || showProgramHistory || showSplitDialog || showDiagnostics-- LaunchedEffect(anyOverlayVisible) {- if (anyOverlayVisible) {++ LaunchedEffect(contentType, showCategoryListOverlay, showChannelListOverlay, showEpgOverlay, showChannelInfoOverlay) {+ if (contentType == "LIVE" && (showCategoryListOverlay || showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay)) {// Give overlays a moment to animate in before requesting focusdelay(150)when {@@ -264,12 +271,16 @@ fun PlayerScreen(showEpgOverlay -> epgFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "EPG overlay")showChannelInfoOverlay -> channelInfoFocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "Channel info overlay")}- } else {+ }+ }++ LaunchedEffect(anyOverlayVisible) {+ if (!anyOverlayVisible) {// Restore focus to main player when all overlays are gonefocusRequester.requestFocusSafely(tag = "PlayerScreen", target = "Player root")}}-+val resolutionBadgeLabel = buildResolutionBadgeLabel(videoFormat = videoFormat,videoTracks = availableVideoQualities,@@ -417,6 +428,52 @@ fun PlayerScreen(canFocus = !anyOverlayVisible && !showControls}.focusable()+ .pointerInput(contentType, anyOverlayVisible, showControls) {+ detectTapGestures {+ when {+ anyOverlayVisible -> return@detectTapGestures+ showControls -> viewModel.toggleControls()+ contentType == "LIVE" -> viewModel.openChannelInfoOverlay()+ else -> viewModel.toggleControls()+ }+ }+ }+ .onPreviewKeyEvent { event ->+ if (event.nativeKeyEvent.action != KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ if (contentType != "LIVE") {+ return@onPreviewKeyEvent false+ }+ if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay) {+ return@onPreviewKeyEvent false+ }+ if (showTrackSelection != null || showSpeedSelection || showProgramHistory || showSplitDialog) {+ return@onPreviewKeyEvent false+ }++ when (event.nativeKeyEvent.keyCode) {+ KeyEvent.KEYCODE_DPAD_UP,+ KeyEvent.KEYCODE_CHANNEL_UP,+ KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {+ if (showChannelInfoOverlay || showDiagnostics) {+ viewModel.onLiveOverlayInteraction()+ }+ viewModel.playNext()+ true+ }+ KeyEvent.KEYCODE_DPAD_DOWN,+ KeyEvent.KEYCODE_CHANNEL_DOWN,+ KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> {+ if (showChannelInfoOverlay || showDiagnostics) {+ viewModel.onLiveOverlayInteraction()+ }+ viewModel.playPrevious()+ true+ }+ else -> false+ }+ }.onKeyEvent { event ->// Only handle KeyDown to avoid double actionsif (event.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {@@ -509,7 +566,7 @@ fun PlayerScreen(if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {viewModel.onLiveOverlayInteraction()}- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay) return@onKeyEvent false+ if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay) return@onKeyEvent falseif (showControls && contentType != "LIVE") return@onKeyEvent falseif (contentType == "LIVE") {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.ktindex 2deeca67..da262382 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt@@ -552,6 +552,10 @@ class PlayerViewModel @Inject constructor(val mediaTitle: StateFlow<String?> = playerEngine.mediaTitleval playbackSpeed: StateFlow<Float> = playerEngine.playbackSpeed+ val preventStandbyDuringPlayback: StateFlow<Boolean> =+ preferencesRepository.preventStandbyDuringPlayback+ .stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), true)+fun selectAudioTrack(trackId: String) {playerEngine.selectAudioTrack(trackId)}@@ -1136,20 +1140,26 @@ class PlayerViewModel @Inject constructor(}}} else if (categoryId == VirtualCategoryIds.FAVORITES) {- // Global Favorites+ // Global Favorites — preserve user-defined position orderfavoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)- .map { favorites -> favorites.map { it.contentId } }- .flatMapLatest { ids ->- if (ids.isEmpty()) flowOf(emptyList())- else channelRepository.getChannelsByIds(ids)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids ->+ if (ids.isEmpty()) flowOf(emptyList())+ else channelRepository.getChannelsByIds(ids).map { unsorted ->+ val byId = unsorted.associateBy { it.id }+ ids.mapNotNull { byId[it] }+ }}} else {val groupId = if (categoryId < 0) -categoryId else categoryIdfavoriteRepository.getFavoritesByGroup(groupId)- .map { favorites -> favorites.map { it.contentId } }- .flatMapLatest { ids ->- if (ids.isEmpty()) flowOf(emptyList())- else channelRepository.getChannelsByIds(ids)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids ->+ if (ids.isEmpty()) flowOf(emptyList())+ else channelRepository.getChannelsByIds(ids).map { unsorted ->+ val byId = unsorted.associateBy { it.id }+ ids.mapNotNull { byId[it] }+ }}}} else {@@ -1276,29 +1286,51 @@ class PlayerViewModel @Inject constructor(openChannelListOverlay()}+ private fun resolveCurrentLiveChannelIndex(): Int {+ if (channelList.isEmpty()) return -1++ val currentIndexMatchesChannel = currentChannelIndex in channelList.indices && run {+ val currentChannel = channelList[currentChannelIndex]+ currentChannel.id == currentContentId || currentChannel.streamUrl == currentStreamUrl+ }+ if (currentIndexMatchesChannel) {+ return currentChannelIndex+ }++ currentChannelIndex = when {+ currentContentId > 0 -> channelList.indexOfFirst { it.id == currentContentId }+ else -> -1+ }++ if (currentChannelIndex == -1) {+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }+ }++ return currentChannelIndex+ }++ private fun wrappedChannelIndex(offset: Int): Int {+ val resolvedIndex = resolveCurrentLiveChannelIndex()+ if (resolvedIndex == -1) return -1+ val size = channelList.size+ return ((resolvedIndex + offset) % size + size) % size+ }+fun playNext() {clearNumericChannelInput()if (channelList.isEmpty()) return-- if (currentChannelIndex == -1) {- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }- if (currentChannelIndex == -1) return- }-- val nextIndex = (currentChannelIndex + 1) % channelList.size++ val nextIndex = wrappedChannelIndex(offset = 1)+ if (nextIndex == -1) returnchangeChannel(nextIndex)}fun playPrevious() {clearNumericChannelInput()if (channelList.isEmpty()) return-- if (currentChannelIndex == -1) {- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }- if (currentChannelIndex == -1) return- }-- val prevIndex = if (currentChannelIndex - 1 < 0) channelList.size - 1 else currentChannelIndex - 1++ val prevIndex = wrappedChannelIndex(offset = -1)+ if (prevIndex == -1) returnchangeChannel(prevIndex)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex 5fcce956..2f8e0c7d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt@@ -4,9 +4,13 @@ import androidx.compose.animation.animateColorAsStateimport androidx.compose.animation.core.animateFloatAsStateimport androidx.compose.animation.core.tweenimport androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.Canvasimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.borderimport androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequesterimport com.streamvault.app.ui.interaction.mouseClickableimport androidx.compose.foundation.layout.*import androidx.compose.foundation.rememberScrollState@@ -22,17 +26,26 @@ import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.scale+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusProperties+import androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusEventimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.TextRangeimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.text.input.OffsetMapping+import androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.text.input.TransformedTextimport androidx.compose.ui.text.input.VisualTransformationimport androidx.compose.ui.text.style.TextAlign@@ -290,18 +303,7 @@ private fun ProviderFormContent(modifier: Modifier = Modifier) {val scrollState = rememberScrollState()- val density = LocalDensity.current- val imeBottom = WindowInsets.ime.getBottom(density)- val coroutineScope = rememberCoroutineScope()-- // When the keyboard appears, scroll to the bottom so the active field- // and the action button are always above the keyboard.- LaunchedEffect(imeBottom) {- if (imeBottom > 0) {- delay(120)- coroutineScope.launch { scrollState.animateScrollTo(scrollState.maxValue) }- }- }+ val isTelevisionDevice = rememberIsTelevisionDevice()Surface(modifier = modifier,@@ -331,7 +333,12 @@ private fun ProviderFormContent(ProviderTextField(value = serverUrl, onValueChange = onServerUrlChange,placeholder = androidx.compose.ui.res.stringResource(R.string.setup_server_hint),- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next)+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Uri,+ imeAction = ImeAction.Next+ ))ProviderTextField(value = username, onValueChange = onUsernameChange,@@ -339,6 +346,7 @@ private fun ProviderFormContent(keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None,autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,imeAction = ImeAction.Next))@@ -349,7 +357,7 @@ private fun ProviderFormContent(keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.None,autoCorrectEnabled = false,- keyboardType = KeyboardType.Password,+ keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Password,imeAction = ImeAction.Done))@@ -608,9 +616,90 @@ private fun ProviderTextField(keyboardOptions: KeyboardOptions = KeyboardOptions.Default,keyboardActions: KeyboardActions = KeyboardActions.Default) {- var isFocused by remember { mutableStateOf(false) }+ val isTelevisionDevice = rememberIsTelevisionDevice()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var fieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ var isPasswordVisible by rememberSaveable(isPassword) { mutableStateOf(false) }var revealedPasswordIndex by remember { mutableStateOf<Int?>(null) }var previousValue by remember { mutableStateOf(value) }+ val containerFocusRequester = remember { FocusRequester() }+ val inputFocusRequester = remember { FocusRequester() }+ val visibilityToggleFocusRequester = remember { FocusRequester() }+ val keyboardController = LocalSoftwareKeyboardController.current+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ val coroutineScope = rememberCoroutineScope()+ val isFocused = hasContainerFocus || hasInputFocus+ val passwordVisibilityDescription = if (isPassword) {+ androidx.compose.ui.res.stringResource(+ if (isPasswordVisible) R.string.setup_hide_password else R.string.setup_show_password+ )+ } else {+ null+ }++ fun activateInput() {+ if (!isTelevisionDevice) {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ coroutineScope.launch {+ runCatching { bringIntoViewRequester.bringIntoView() }+ delay(180)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ return+ }+ acceptsInput = true+ pendingInputActivation = true+ coroutineScope.launch {+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ LaunchedEffect(value) {+ if (value != fieldValue.text) {+ val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = fieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ fieldValue = fieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {+ return@LaunchedEffect+ }+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ pendingInputActivation = false+ }++ LaunchedEffect(isPassword) {+ if (!isPassword) {+ isPasswordVisible = false+ }+ }// Show most-recently typed character briefly before maskingLaunchedEffect(value, isPassword) {@@ -632,35 +721,173 @@ private fun ProviderTextField(val borderColor by animateColorAsState(if (isFocused) Primary else SurfaceHighlight, tween(150), label = "border")val bgColor by animateColorAsState(if (isFocused) Surface else SurfaceElevated, tween(150), label = "bg")- androidx.compose.foundation.text.BasicTextField(- value = value,- onValueChange = onValueChange,+ Box(modifier = modifier.fillMaxWidth()- // hasFocus = true when this node OR any child (the real text cursor) has focus- .onFocusEvent { isFocused = it.hasFocus },- singleLine = true,- keyboardOptions = keyboardOptions,- keyboardActions = keyboardActions,- textStyle = MaterialTheme.typography.bodyMedium.copy(color = OnBackground),- visualTransformation = if (isPassword) RevealingPasswordVisualTransformation(revealedPasswordIndex)- else VisualTransformation.None,- cursorBrush = SolidColor(Primary),- decorationBox = { innerTextField ->- Box(- modifier = Modifier- .background(bgColor, RoundedCornerShape(10.dp))- .border(if (isFocused) 2.dp else 1.dp, borderColor, RoundedCornerShape(10.dp))- .padding(horizontal = 16.dp, vertical = 14.dp),- contentAlignment = Alignment.CenterStart- ) {- if (value.isEmpty()) {- Text(text = placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)+ .focusRequester(containerFocusRequester)+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusEvent {+ hasContainerFocus = it.hasFocus+ if (!it.hasFocus && isTelevisionDevice) {+ acceptsInput = false+ keyboardController?.hide()}- innerTextField()}+ .mouseClickable(focusRequester = containerFocusRequester, onClick = ::activateInput)+ .clickable(onClick = ::activateInput)+ .focusable()+ .padding(0.dp)+ ) {+ androidx.compose.foundation.text.BasicTextField(+ value = fieldValue,+ onValueChange = { updatedValue ->+ fieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(inputFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = if (isPassword) visibilityToggleFocusRequester else FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = fieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ if (isPassword && cursor >= fieldValue.text.length) {+ visibilityToggleFocusRequester.requestFocus()+ return@onPreviewKeyEvent true+ }+ val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }+ .onFocusEvent {+ hasInputFocus = it.hasFocus+ if (it.hasFocus) {+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ } else if (isTelevisionDevice) {+ keyboardController?.hide()+ }+ },+ singleLine = true,+ readOnly = isTelevisionDevice && !acceptsInput,+ keyboardOptions = keyboardOptions,+ keyboardActions = keyboardActions,+ textStyle = MaterialTheme.typography.bodyMedium.copy(color = OnBackground),+ visualTransformation = when {+ !isPassword || isPasswordVisible -> VisualTransformation.None+ else -> RevealingPasswordVisualTransformation(revealedPasswordIndex)+ },+ cursorBrush = SolidColor(Primary),+ decorationBox = { innerTextField ->+ Row(+ modifier = Modifier+ .background(bgColor, RoundedCornerShape(10.dp))+ .border(if (isFocused) 2.dp else 1.dp, borderColor, RoundedCornerShape(10.dp))+ .padding(horizontal = 16.dp, vertical = 14.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Box(+ modifier = Modifier.weight(1f),+ contentAlignment = Alignment.CenterStart+ ) {+ if (value.isEmpty()) {+ Text(text = placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)+ }+ innerTextField()+ }++ if (isPassword) {+ Box(+ modifier = Modifier+ .padding(start = 12.dp)+ .size(24.dp)+ .focusRequester(visibilityToggleFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ left = inputFocusRequester+ }+ .onFocusEvent {+ if (it.hasFocus) {+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }+ }+ .semantics {+ contentDescription = passwordVisibilityDescription.orEmpty()+ }+ .clickable {+ isPasswordVisible = !isPasswordVisible+ }+ .mouseClickable(focusRequester = visibilityToggleFocusRequester) {+ isPasswordVisible = !isPasswordVisible+ }+ .focusable(enabled = !isTelevisionDevice || acceptsInput)+ ) {+ PasswordVisibilityGlyph(+ isVisible = isPasswordVisible,+ tint = if (isFocused) Primary else OnSurfaceDim,+ modifier = Modifier.align(Alignment.Center)+ )+ }+ }+ }+ }+ )+ }+}++@Composable+private fun PasswordVisibilityGlyph(+ isVisible: Boolean,+ tint: Color,+ modifier: Modifier = Modifier+) {+ Canvas(modifier = modifier.size(18.dp)) {+ val stroke = Stroke(width = size.minDimension * 0.11f)+ drawOval(+ color = tint,+ topLeft = androidx.compose.ui.geometry.Offset(1.6f, size.height * 0.22f),+ size = androidx.compose.ui.geometry.Size(size.width - 3.2f, size.height * 0.56f),+ style = stroke+ )+ drawCircle(+ color = tint,+ radius = size.minDimension * 0.14f,+ center = center+ )+ if (!isVisible) {+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.82f),+ end = androidx.compose.ui.geometry.Offset(size.width * 0.82f, size.height * 0.18f),+ strokeWidth = size.minDimension * 0.11f+ )}- )+ }}// ??? Sync progress dialog ?????????????????????????????????????????????????????diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.ktindex 05ff2b44..924cbab3 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt@@ -42,6 +42,7 @@ import com.streamvault.app.ui.components.SeriesCardimport com.streamvault.app.ui.components.TvEmptyStateimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffold+import com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.theme.*import com.streamvault.domain.manager.ParentalControlManagerimport com.streamvault.domain.model.Channel@@ -276,7 +277,7 @@ fun SearchScreen(}LaunchedEffect(Unit) {- runCatching { searchFocusRequester.requestFocus() }+ searchFocusRequester.requestFocusSafely(tag = "SearchScreen", target = "Search field")}LaunchedEffect(initialQuery) {@@ -288,7 +289,7 @@ fun SearchScreen(LaunchedEffect(showPinDialog) {if (!showPinDialog) {- runCatching { searchFocusRequester.requestFocus() }+ searchFocusRequester.requestFocusSafely(tag = "SearchScreen", target = "Search field")}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.ktindex 20cc66b0..c763f658 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailScreen.kt@@ -50,10 +50,12 @@ import com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.components.shell.ContentMetadataStripimport com.streamvault.app.ui.components.shell.EpisodeRowCard+import com.streamvault.app.ui.components.shell.ExternalRatingsStripimport com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.model.formatVodRatingLabelimport com.streamvault.domain.model.Episode+import com.streamvault.domain.model.ExternalRatingsimport com.streamvault.domain.model.Seasonimport com.streamvault.domain.model.Seriesimport com.streamvault.app.ui.interaction.TvClickableSurface@@ -100,6 +102,8 @@ fun SeriesDetailScreen(series = series,selectedSeason = uiState.selectedSeason,unwatchedEpisodeCount = uiState.unwatchedEpisodeCount,+ externalRatings = uiState.externalRatings,+ isLoadingExternalRatings = uiState.isLoadingExternalRatings,onSeasonSelected = viewModel::selectSeason,onEpisodeClick = onEpisodeClick,onBack = onBack@@ -111,6 +115,8 @@ private fun SeriesDetailContent(series: Series,selectedSeason: Season?,unwatchedEpisodeCount: Int,+ externalRatings: ExternalRatings,+ isLoadingExternalRatings: Boolean,onSeasonSelected: (Season) -> Unit,onEpisodeClick: (Episode) -> Unit,onBack: () -> Unit@@ -231,6 +237,10 @@ private fun SeriesDetailContent(selectedSeason?.name.orEmpty()))+ ExternalRatingsStrip(+ ratings = externalRatings,+ isLoading = isLoadingExternalRatings+ )Text(text = series.plot ?: stringResource(R.string.series_plot_fallback),style = MaterialTheme.typography.bodyLarge,@@ -294,6 +304,10 @@ private fun SeriesDetailContent(selectedSeason?.name.orEmpty()))+ ExternalRatingsStrip(+ ratings = externalRatings,+ isLoading = isLoadingExternalRatings+ )Text(text = series.plot ?: stringResource(R.string.series_plot_fallback),style = MaterialTheme.typography.bodyLarge,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.ktindex 3a08c6ad..7c534b32 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesDetailViewModel.kt@@ -3,9 +3,13 @@ package com.streamvault.app.ui.screens.seriesimport androidx.lifecycle.SavedStateHandleimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.ExternalRatings+import com.streamvault.domain.model.ExternalRatingsLookupimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Seasonimport com.streamvault.domain.model.Series+import com.streamvault.domain.repository.ExternalRatingsRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SeriesRepositoryimport com.streamvault.domain.repository.ProviderRepository@@ -23,7 +27,8 @@ class SeriesDetailViewModel @Inject constructor(savedStateHandle: SavedStateHandle,private val seriesRepository: SeriesRepository,private val providerRepository: ProviderRepository,- private val playbackHistoryRepository: PlaybackHistoryRepository+ private val playbackHistoryRepository: PlaybackHistoryRepository,+ private val externalRatingsRepository: ExternalRatingsRepository) : ViewModel() {private val seriesId: Long = checkNotNull(@@ -53,6 +58,7 @@ class SeriesDetailViewModel @Inject constructor(when (val result = seriesRepository.getSeriesDetails(provider.id, seriesId)) {is Result.Success -> {+ loadExternalRatings(result.data)_uiState.update {it.copy(isLoading = false,@@ -82,6 +88,33 @@ class SeriesDetailViewModel @Inject constructor(}}+ private fun loadExternalRatings(series: Series) {+ viewModelScope.launch {+ _uiState.update { it.copy(isLoadingExternalRatings = true) }+ val ratingsResult = externalRatingsRepository.getRatings(+ ExternalRatingsLookup(+ contentType = ContentType.SERIES,+ title = series.name,+ releaseYear = series.releaseDate,+ tmdbId = series.tmdbId+ )+ )+ _uiState.update { currentState ->+ when (ratingsResult) {+ is Result.Success -> currentState.copy(+ isLoadingExternalRatings = false,+ externalRatings = ratingsResult.data+ )+ is Result.Error -> currentState.copy(+ isLoadingExternalRatings = false,+ externalRatings = ExternalRatings.unavailable()+ )+ is Result.Loading -> currentState+ }+ }+ }+ }+private fun observeUnwatchedCount(providerId: Long) {viewModelScope.launch {playbackHistoryRepository.getUnwatchedCount(providerId = providerId, seriesId = seriesId).collect { count ->@@ -100,5 +133,7 @@ data class SeriesDetailUiState(val series: Series? = null,val selectedSeason: Season? = null,val unwatchedEpisodeCount: Int = 0,- val error: String? = null+ val error: String? = null,+ val isLoadingExternalRatings: Boolean = false,+ val externalRatings: ExternalRatings = ExternalRatings.unavailable())diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.ktindex 04f3f6ae..b490218d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt@@ -174,7 +174,7 @@ fun SeriesScreen(subtitle = uiState.errorMessage ?: "")}- } else if (uiState.seriesByCategory.isEmpty()) {+ } else if (uiState.seriesByCategory.isEmpty() && !uiState.isLoadingPreviewRows) {Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {AppMessageState(title = stringResource(R.string.series_no_found),@@ -221,6 +221,7 @@ fun SeriesScreen(viewModel.selectFullLibraryBrowse()},onLoadMore = viewModel::loadMoreSelectedCategory,+ onLoadMorePreviewRows = viewModel::loadMorePreviewRows,onDismissReorder = viewModel::exitCategoryReorderMode)}@@ -308,6 +309,7 @@ private fun SeriesVodContent(onOpenTopRated: () -> Unit,onOpenFresh: () -> Unit,onLoadMore: () -> Unit,+ onLoadMorePreviewRows: () -> Unit,onDismissReorder: () -> Unit) {val screenWidth = LocalConfiguration.current.screenWidthDp.dp@@ -574,7 +576,7 @@ private fun SeriesVodContent(val catEntries = uiState.seriesByCategory.entries.filter { (name, items) ->name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()- }.take(8).toList()+ }.toList()items(catEntries, key = { it.key }) { entry ->val categoryName = entry.keyval seriesList = entry.value@@ -597,6 +599,25 @@ private fun SeriesVodContent()}}+ if (uiState.isLoadingPreviewRows) {+ item(key = "preview_loading") {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 24.dp),+ contentAlignment = Alignment.Center+ ) {+ CircularProgressIndicator(color = Color.White, modifier = Modifier.size(32.dp))+ }+ }+ }+ if (uiState.hasMorePreviewRows && !uiState.isLoadingPreviewRows && catEntries.isNotEmpty()) {+ item(key = "load_more_preview_trigger") {+ LaunchedEffect(catEntries.size) {+ onLoadMorePreviewRows()+ }+ }+ }}return}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.ktindex c3ec2b8d..d195e839 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt@@ -90,6 +90,14 @@ class SeriesViewModel @Inject constructor(private val _selectedCategoryLoadLimit = MutableStateFlow(VodBrowseDefaults.SELECTED_CATEGORY_PAGE_SIZE)private val _selectedLibraryFilterType = MutableStateFlow(LibraryFilterType.ALL)private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)+ private val _previewBatchSize = MutableStateFlow(8)+ private var activeProviderId: Long? = null++ private data class PreviewLoadResult(+ val snapshot: SeriesCatalogSnapshot,+ val isLoadingPreviewRows: Boolean,+ val hasMorePreviewRows: Boolean+ )init {viewModelScope.launch {@@ -97,6 +105,7 @@ class SeriesViewModel @Inject constructor(providerRepository.getActiveProvider().filterNotNull().flatMapLatest { provider ->+ activeProviderId = provider.idcombine(favoriteRepository.getAllFavorites(ContentType.SERIES),getCustomCategories(ContentType.SERIES),@@ -141,32 +150,57 @@ class SeriesViewModel @Inject constructor(}}.flatMapLatest { params ->- flow {- emit(- if (params.query.isBlank()) {- buildPreviewCatalog(params)- } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {- buildSearchCatalog(- series = emptyList(),- allFavorites = params.allFavorites,- customCategories = params.customCategories,- providerCategories = params.providerCategories,- hiddenCategoryIds = params.hiddenCategoryIds- ).copy(libraryCount = 0)+ _previewBatchSize.value = 8+ _previewBatchSize.flatMapLatest { batchSize ->+ if (params.query.isBlank()) {+ val categoryIds = params.providerCategories.take(batchSize).map { it.id }+ if (categoryIds.isEmpty()) {+ flow {+ emit(PreviewLoadResult(buildPreviewCatalog(params, emptyMap()), false, false))+ }} else {+ seriesRepository.getCategoryPreviewRows(+ providerId = params.providerId,+ categoryIds = categoryIds,+ limitPerCategory = VodBrowseDefaults.PREVIEW_ROW_LIMIT+ ).map { providerPreviews ->+ val isLoading = categoryIds.all { id -> providerPreviews[id].isNullOrEmpty() }+ val hasMore = params.providerCategories.size > batchSize+ PreviewLoadResult(buildPreviewCatalog(params, providerPreviews), isLoading, hasMore)+ }+ }+ } else if (params.query.length < MIN_SEARCH_QUERY_LENGTH) {+ flow {+ emit(PreviewLoadResult(+ buildSearchCatalog(+ series = emptyList(),+ allFavorites = params.allFavorites,+ customCategories = params.customCategories,+ providerCategories = params.providerCategories,+ hiddenCategoryIds = params.hiddenCategoryIds+ ).copy(libraryCount = 0),+ false, false+ ))+ }+ } else {+ flow {val searchResults = seriesRepository.searchSeries(params.providerId, params.query).first()- buildSearchCatalog(- series = searchResults,- allFavorites = params.allFavorites,- customCategories = params.customCategories,- providerCategories = params.providerCategories,- hiddenCategoryIds = params.hiddenCategoryIds- ).copy(libraryCount = searchResults.size)+ emit(PreviewLoadResult(+ buildSearchCatalog(+ series = searchResults,+ allFavorites = params.allFavorites,+ customCategories = params.customCategories,+ providerCategories = params.providerCategories,+ hiddenCategoryIds = params.hiddenCategoryIds+ ).copy(libraryCount = searchResults.size),+ false, false+ ))}- )+ }}}- .collect { snapshot ->+ .collect { result ->+ val snapshot = result.snapshotval isReordering = _uiState.value.isReorderModeval currentSelected = _uiState.value.selectedCategoryval preserveSelectedCategory = currentSelected != null && _searchQuery.value.isNotBlank()@@ -189,6 +223,8 @@ class SeriesViewModel @Inject constructor(canLoadMoreSelectedCategory = if (resolvedSelected == null) false else it.canLoadMoreSelectedCategory,filteredSeries = if (isReordering) it.filteredSeries else emptyList(),isLoading = false,+ isLoadingPreviewRows = result.isLoadingPreviewRows,+ hasMorePreviewRows = result.hasMorePreviewRows,errorMessage = null)}@@ -406,6 +442,12 @@ class SeriesViewModel @Inject constructor(}fun selectCategory(categoryName: String?) {+ activeProviderId?.let { providerId ->+ parentalControlManager.retainUnlockedCategory(+ providerId = providerId,+ categoryId = resolveProviderCategoryId(categoryName)+ )+ }selectVodCategory(categoryName = categoryName,selectedCategoryLoadLimit = _selectedCategoryLoadLimit,@@ -437,6 +479,12 @@ class SeriesViewModel @Inject constructor()}+ fun loadMorePreviewRows() {+ if (_uiState.value.hasMorePreviewRows && !_uiState.value.isLoadingPreviewRows) {+ _previewBatchSize.update { it + 8 }+ }+ }+fun setSearchQuery(query: String) {setVodSearchQuery(query, _searchQuery, _uiState) { updatedQuery ->copy(searchQuery = updatedQuery)@@ -625,6 +673,11 @@ class SeriesViewModel @Inject constructor(_uiState.update { it.copy(selectedCategoryForOptions = null) }}+ private fun resolveProviderCategoryId(categoryName: String?): Long? =+ _uiState.value.providerCategories+ .firstOrNull { it.name == categoryName && !it.isVirtual && it.id > 0L }+ ?.id+fun hideCategory(category: Category) {if (category.isVirtual) returnviewModelScope.launch {@@ -791,10 +844,10 @@ class SeriesViewModel @Inject constructor(}private suspend fun buildPreviewCatalog(- params: SeriesCatalogParams+ params: SeriesCatalogParams,+ providerPreviews: Map<Long?, List<Series>>): SeriesCatalogSnapshot {val snapshot = buildVodPreviewCatalog(- providerId = params.providerId,allFavorites = params.allFavorites,customCategories = params.customCategories,providerCategories = params.providerCategories,@@ -802,9 +855,7 @@ class SeriesViewModel @Inject constructor(libraryCount = params.libraryCount,hiddenProviderCategoryIds = params.hiddenCategoryIds,loadItemsByIds = { ids -> seriesRepository.getSeriesByIds(ids).first() },- loadCategoryPreviewRows = { providerId, limit ->- seriesRepository.getCategoryPreviewRows(providerId, limit).first()- },+ providerPreviews = providerPreviews,itemId = Series::id,itemCategoryId = Series::categoryId,copyWithFavorite = { series, isFavorite -> series.copy(isFavorite = isFavorite) }@@ -1128,6 +1179,8 @@ data class SeriesUiState(val vodViewMode: VodViewMode = VodViewMode.MODERN,val continueWatching: List<PlaybackHistory> = emptyList(),val isLoading: Boolean = true,+ val isLoadingPreviewRows: Boolean = false,+ val hasMorePreviewRows: Boolean = false,val parentalControlLevel: Int = 0,val unlockedCategoryIds: Set<Long> = emptySet(),val showDialog: Boolean = false,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.ktindex 84fafc51..ad9d43a4 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt@@ -2,6 +2,8 @@ package com.streamvault.app.ui.screens.settingsimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.border+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequesterimport androidx.compose.ui.draw.clipimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumn@@ -14,11 +16,18 @@ import androidx.compose.runtime.*import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.foundation.focusableimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.input.key.onKeyEvent+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.platform.LocalUriHandler+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValueimport androidx.compose.ui.unit.dpimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.tv.material3.*@@ -43,6 +52,7 @@ import com.streamvault.app.ui.interaction.TvIconButtonimport com.streamvault.app.ui.components.dialogs.PinDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButtonimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.components.TvEmptyStateimport com.streamvault.app.localization.localeForLanguageTag@@ -50,6 +60,7 @@ import com.streamvault.app.localization.supportedAppLanguageTagsimport com.streamvault.app.ui.components.shell.AppNavigationChromeimport com.streamvault.app.ui.components.shell.AppScreenScaffoldimport com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.ui.theme.*import com.streamvault.domain.manager.BackupConflictStrategy@@ -140,9 +151,11 @@ fun SettingsScreen(var showLevelDialog by rememberSaveable { mutableStateOf(false) }var showLanguageDialog by rememberSaveable { mutableStateOf(false) }var showLiveTvModeDialog by rememberSaveable { mutableStateOf(false) }+ var showLiveTvQuickFilterVisibilityDialog by rememberSaveable { mutableStateOf(false) }var showLiveChannelNumberingDialog by rememberSaveable { mutableStateOf(false) }var showVodViewModeDialog by rememberSaveable { mutableStateOf(false) }var showPlaybackSpeedDialog by rememberSaveable { mutableStateOf(false) }+ var showLiveTvFiltersDialog by rememberSaveable { mutableStateOf(false) }var showAudioLanguageDialog by rememberSaveable { mutableStateOf(false) }var showSubtitleSizeDialog by rememberSaveable { mutableStateOf(false) }var showSubtitleTextColorDialog by rememberSaveable { mutableStateOf(false) }@@ -337,11 +350,44 @@ fun SettingsScreen(// ── 1: Playback ───────────────────────────────────────────else if (selectedCategory == 1) {item {+ TvClickableSurface(+ onClick = { viewModel.setPreventStandbyDuringPlayback(!uiState.preventStandbyDuringPlayback) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = stringResource(R.string.settings_prevent_standby), style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = stringResource(R.string.settings_prevent_standby_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))+ }+ Switch(checked = uiState.preventStandbyDuringPlayback, onCheckedChange = { viewModel.setPreventStandbyDuringPlayback(it) })+ }+ }+ HorizontalDivider(color = Color.White.copy(alpha = 0.07f), modifier = Modifier.padding(vertical = 4.dp))ClickableSettingsRow(label = stringResource(R.string.settings_live_tv_channel_mode),value = stringResource(uiState.liveTvChannelMode.labelResId()),onClick = { showLiveTvModeDialog = true })+ ClickableSettingsRow(+ label = stringResource(R.string.settings_live_tv_quick_filters),+ value = formatLiveTvQuickFiltersValue(uiState.liveTvCategoryFilters, context),+ onClick = { showLiveTvFiltersDialog = true }+ )+ ClickableSettingsRow(+ label = stringResource(R.string.settings_live_tv_quick_filter_visibility),+ value = stringResource(uiState.liveTvQuickFilterVisibilityMode.labelResId()),+ onClick = { showLiveTvQuickFilterVisibilityDialog = true }+ )ClickableSettingsRow(label = stringResource(R.string.settings_live_channel_numbering_mode),value = stringResource(uiState.liveChannelNumberingMode.labelResId()),@@ -918,13 +964,19 @@ fun SettingsScreen(androidx.activity.compose.BackHandler(enabled = true) {// Do nothing, effectively blocking back}-++ val overlayFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) { overlayFocusRequester.requestFocus() }+// OverlayBox(modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.7f)).clickable(enabled = true, onClick = {}) // Consume clicks+ .focusRequester(overlayFocusRequester)+ .focusable()+ .onKeyEvent { true } // Consume all d-pad/key events.align(Alignment.Center),contentAlignment = Alignment.Center) {@@ -959,6 +1011,17 @@ fun SettingsScreen()}+ if (showLiveTvQuickFilterVisibilityDialog) {+ LiveTvQuickFilterVisibilityDialog(+ selectedMode = uiState.liveTvQuickFilterVisibilityMode,+ onDismiss = { showLiveTvQuickFilterVisibilityDialog = false },+ onModeSelected = { mode ->+ viewModel.setLiveTvQuickFilterVisibilityMode(mode)+ showLiveTvQuickFilterVisibilityDialog = false+ }+ )+ }+if (showLiveChannelNumberingDialog) {LiveChannelNumberingModeDialog(selectedMode = uiState.liveChannelNumberingMode,@@ -1001,6 +1064,15 @@ fun SettingsScreen(}}+ if (showLiveTvFiltersDialog) {+ LiveTvQuickFiltersDialog(+ filters = uiState.liveTvCategoryFilters,+ onDismiss = { showLiveTvFiltersDialog = false },+ onAddFilter = viewModel::addLiveTvCategoryFilter,+ onRemoveFilter = viewModel::removeLiveTvCategoryFilter+ )+ }+if (showAudioLanguageDialog) {val autoLabel = stringResource(R.string.settings_audio_language_auto)val audioLanguageOptions = remember(autoLabel) { supportedAudioLanguages(autoLabel) }@@ -1340,11 +1412,6 @@ private fun ProviderSyncOptionsDialog(SyncOptionButton(stringResource(R.string.settings_sync_option_all)) {onSelect(ProviderSyncSelection.ALL)}- if (provider.type == ProviderType.XTREAM_CODES) {- SyncOptionButton(stringResource(R.string.settings_sync_option_fast)) {- onSelect(ProviderSyncSelection.FAST)- }- }availableSyncSelections(provider).forEach { option ->SyncOptionButton(text = syncSelectionLabel(option)) {onSelect(option)@@ -2323,6 +2390,57 @@ private fun LiveTvChannelModeDialog()}+@Composable+private fun LiveTvQuickFilterVisibilityDialog(+ selectedMode: LiveTvQuickFilterVisibilityMode,+ onDismiss: () -> Unit,+ onModeSelected: (LiveTvQuickFilterVisibilityMode) -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_live_tv_quick_filter_visibility),+ subtitle = stringResource(R.string.settings_live_tv_quick_filter_visibility_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ LiveTvQuickFilterVisibilityMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(mode.labelResId()),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == selectedMode) Primary else OnBackground+ )+ Text(+ text = stringResource(mode.descriptionResId()),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}+@Composableprivate fun SettingsSectionHeader(title: String,@@ -2976,37 +3094,236 @@ private fun EpgSourceTextField(onValueChange: (String) -> Unit,placeholder: String) {+ val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()val focusRequester = remember { FocusRequester() }- var isFocused by remember { mutableStateOf(false) }+ val keyboardController = LocalSoftwareKeyboardController.current+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ val coroutineScope = rememberCoroutineScope()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var fieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ val isFocused = hasContainerFocus || hasInputFocus++ fun requestBringIntoView(delayMillis: Long = 0L) {+ coroutineScope.launch {+ if (delayMillis > 0) {+ kotlinx.coroutines.delay(delayMillis)+ }+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ LaunchedEffect(value) {+ if (value != fieldValue.text) {+ val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = fieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ fieldValue = fieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {+ return@LaunchedEffect+ }+ focusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView(120)+ pendingInputActivation = false+ }+TvClickableSurface(- onClick = { focusRequester.requestFocus() },+ onClick = {+ if (!isTelevisionDevice) {+ focusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView()+ requestBringIntoView(180)+ return@TvClickableSurface+ }+ acceptsInput = true+ pendingInputActivation = true+ requestBringIntoView()+ },shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),colors = ClickableSurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.08f),focusedContainerColor = Color.White.copy(alpha = 0.12f)),scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier.fillMaxWidth()+ modifier = Modifier+ .fillMaxWidth()+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusChanged { hasContainerFocus = it.isFocused }) {Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {if (value.isEmpty() && !isFocused) {Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)}BasicTextField(- value = value,- onValueChange = onValueChange,+ value = fieldValue,+ onValueChange = { updatedValue ->+ fieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),singleLine = true,cursorBrush = SolidColor(Primary),modifier = Modifier.fillMaxWidth().focusRequester(focusRequester)- .onFocusChanged { isFocused = it.isFocused }+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = fieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }+ .onFocusChanged {+ hasInputFocus = it.isFocused+ if (it.isFocused) {+ requestBringIntoView(120)+ } else {+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()+ }+ },+ readOnly = isTelevisionDevice && !acceptsInput)}}}+@Composable+private fun LiveTvQuickFiltersDialog(+ filters: List<String>,+ onDismiss: () -> Unit,+ onAddFilter: (String) -> Unit,+ onRemoveFilter: (String) -> Unit+) {+ var pendingFilter by rememberSaveable { mutableStateOf("") }++ PremiumDialog(+ title = stringResource(R.string.settings_live_tv_quick_filters_dialog_title),+ subtitle = stringResource(R.string.settings_live_tv_quick_filters_dialog_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.5f,+ content = {+ EpgSourceTextField(+ value = pendingFilter,+ onValueChange = { pendingFilter = it },+ placeholder = stringResource(R.string.settings_live_tv_quick_filters_placeholder)+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.settings_live_tv_quick_filters_add),+ enabled = pendingFilter.isNotBlank(),+ onClick = {+ onAddFilter(pendingFilter)+ pendingFilter = ""+ }+ )+ if (filters.isEmpty()) {+ Text(+ text = stringResource(R.string.settings_live_tv_quick_filters_empty),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ } else {+ Text(+ text = stringResource(R.string.settings_live_tv_quick_filters_saved),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ LazyColumn(+ modifier = Modifier.heightIn(max = 260.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ items(filters, key = { it }) { filter ->+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .background(Color.White.copy(alpha = 0.06f), RoundedCornerShape(12.dp))+ .padding(horizontal = 14.dp, vertical = 10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = filter,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface,+ modifier = Modifier.weight(1f)+ )+ TvButton(onClick = { onRemoveFilter(filter) }) {+ Text(stringResource(R.string.settings_live_tv_quick_filters_remove))+ }+ }+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++private fun formatLiveTvQuickFiltersValue(filters: List<String>, context: android.content.Context): String {+ if (filters.isEmpty()) {+ return context.getString(R.string.settings_live_tv_quick_filters_none)+ }+ return context.resources.getQuantityString(+ R.plurals.settings_live_tv_quick_filters_count,+ filters.size,+ filters.size+ )+}+@Composableprivate fun SettingsNavItem(label: String,@@ -3260,6 +3577,18 @@ private fun LiveTvChannelMode.descriptionResId(): Int = when (this) {LiveTvChannelMode.PRO -> R.string.settings_live_tv_mode_pro_desc}+private fun LiveTvQuickFilterVisibilityMode.labelResId(): Int = when (this) {+ LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide+ LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available+ LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always+}++private fun LiveTvQuickFilterVisibilityMode.descriptionResId(): Int = when (this) {+ LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide_desc+ LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available_desc+ LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always_desc+}+private fun VodViewMode.labelResId(): Int = when (this) {VodViewMode.MODERN -> R.string.settings_vod_view_mode_modernVodViewMode.CLASSIC -> R.string.settings_vod_view_mode_classicdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex 0295dd4a..ce246727 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScopeimport com.streamvault.app.Rimport com.streamvault.app.tvinput.TvInputChannelSyncManagerimport com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityModeimport com.streamvault.app.ui.model.VodViewModeimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.sync.SyncManager@@ -82,8 +83,11 @@ private data class SettingsPreferenceSnapshot(val isIncognitoMode: Boolean,val useXtreamTextClassification: Boolean,val liveTvChannelMode: LiveTvChannelMode,+ val liveTvCategoryFilters: List<String>,+ val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode,val liveChannelNumberingMode: ChannelNumberingMode,- val vodViewMode: VodViewMode+ val vodViewMode: VodViewMode,+ val preventStandbyDuringPlayback: Boolean)@HiltViewModel@@ -140,8 +144,11 @@ class SettingsViewModel @Inject constructor(isIncognitoMode = false,useXtreamTextClassification = true,liveTvChannelMode = LiveTvChannelMode.COMPACT,+ liveTvCategoryFilters = emptyList(),+ liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,liveChannelNumberingMode = ChannelNumberingMode.GROUP,- vodViewMode = VodViewMode.MODERN+ vodViewMode = VodViewMode.MODERN,+ preventStandbyDuringPlayback = true)}.combine(preferencesRepository.appLanguage) { snapshot, language ->snapshot.copy(appLanguage = language)@@ -175,10 +182,18 @@ class SettingsViewModel @Inject constructor(snapshot.copy(useXtreamTextClassification = useTextClass)}.combine(preferencesRepository.liveTvChannelMode) { snapshot, liveTvChannelMode ->snapshot.copy(liveTvChannelMode = LiveTvChannelMode.fromStorage(liveTvChannelMode))+ }.combine(preferencesRepository.liveTvCategoryFilters) { snapshot, liveTvCategoryFilters ->+ snapshot.copy(liveTvCategoryFilters = liveTvCategoryFilters)+ }.combine(preferencesRepository.liveTvQuickFilterVisibility) { snapshot, visibilityMode ->+ snapshot.copy(+ liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.fromStorage(visibilityMode)+ )}.combine(preferencesRepository.liveChannelNumberingMode) { snapshot, liveChannelNumberingMode ->snapshot.copy(liveChannelNumberingMode = liveChannelNumberingMode)}.combine(preferencesRepository.vodViewMode) { snapshot, vodViewMode ->snapshot.copy(vodViewMode = VodViewMode.fromStorage(vodViewMode))+ }.combine(preferencesRepository.preventStandbyDuringPlayback) { snapshot, preventStandby ->+ snapshot.copy(preventStandbyDuringPlayback = preventStandby)}.collect { snapshot ->_uiState.update {it.copy(@@ -206,8 +221,11 @@ class SettingsViewModel @Inject constructor(isIncognitoMode = snapshot.isIncognitoMode,useXtreamTextClassification = snapshot.useXtreamTextClassification,liveTvChannelMode = snapshot.liveTvChannelMode,+ liveTvCategoryFilters = snapshot.liveTvCategoryFilters,+ liveTvQuickFilterVisibilityMode = snapshot.liveTvQuickFilterVisibilityMode,liveChannelNumberingMode = snapshot.liveChannelNumberingMode,- vodViewMode = snapshot.vodViewMode+ vodViewMode = snapshot.vodViewMode,+ preventStandbyDuringPlayback = snapshot.preventStandbyDuringPlayback)}}@@ -364,6 +382,47 @@ class SettingsViewModel @Inject constructor(}}+ fun setLiveTvQuickFilterVisibilityMode(mode: LiveTvQuickFilterVisibilityMode) {+ viewModelScope.launch {+ preferencesRepository.setLiveTvQuickFilterVisibility(mode.storageValue)+ }+ }++ fun addLiveTvCategoryFilter(filter: String) {+ viewModelScope.launch {+ val normalized = filter.trim()+ when {+ normalized.isBlank() -> {+ _uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_live_tv_quick_filter_blank))+ }+ }+ _uiState.value.liveTvCategoryFilters.any { existing ->+ existing.equals(normalized, ignoreCase = true)+ } -> {+ _uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_live_tv_quick_filter_duplicate, normalized))+ }+ }+ preferencesRepository.addLiveTvCategoryFilter(normalized) -> {+ _uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_live_tv_quick_filter_added, normalized))+ }+ }+ }+ }+ }++ fun removeLiveTvCategoryFilter(filter: String) {+ viewModelScope.launch {+ if (preferencesRepository.removeLiveTvCategoryFilter(filter)) {+ _uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_live_tv_quick_filter_removed, filter))+ }+ }+ }+ }+fun setLiveChannelNumberingMode(mode: ChannelNumberingMode) {viewModelScope.launch {preferencesRepository.setLiveChannelNumberingMode(mode)@@ -376,6 +435,12 @@ class SettingsViewModel @Inject constructor(}}+ fun setPreventStandbyDuringPlayback(prevent: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setPreventStandbyDuringPlayback(prevent)+ }+ }+fun setCategorySortMode(type: ContentType, mode: CategorySortMode) {val providerId = _uiState.value.activeProviderId ?: returnviewModelScope.launch {@@ -538,6 +603,7 @@ class SettingsViewModel @Inject constructor(fun refreshProvider(providerId: Long, movieFastSyncOverride: Boolean? = null) {viewModelScope.launch {_uiState.update { it.copy(isSyncing = true) }+ try {val result = syncProvider(SyncProviderCommand(providerId = providerId,@@ -568,14 +634,16 @@ class SettingsViewModel @Inject constructor(})}+ } catch (e: Exception) {+ _uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }+ }}}fun syncProviderSection(providerId: Long, selection: ProviderSyncSelection) {viewModelScope.launch {when (selection) {- ProviderSyncSelection.ALL -> refreshProvider(providerId)- ProviderSyncSelection.FAST -> refreshProvider(providerId, movieFastSyncOverride = true)+ ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> refreshProvider(providerId)else -> runSectionSync(providerId, listOf(selection))}}@@ -646,6 +714,7 @@ class SettingsViewModel @Inject constructor(selections: List<ProviderSyncSelection>) {_uiState.update { it.copy(isSyncing = true) }+ try {val failures = mutableListOf<String>()val completed = mutableListOf<String>()@@ -688,6 +757,9 @@ class SettingsViewModel @Inject constructor(})}+ } catch (e: Exception) {+ _uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }+ }}fun deleteProvider(providerId: Long) {@@ -980,8 +1052,11 @@ data class SettingsUiState(val isIncognitoMode: Boolean = false,val useXtreamTextClassification: Boolean = true,val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.COMFORTABLE,+ val liveTvCategoryFilters: List<String> = emptyList(),+ val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,val liveChannelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP,val vodViewMode: VodViewMode = VodViewMode.MODERN,+ val preventStandbyDuringPlayback: Boolean = true,val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),val hiddenCategories: List<Category> = emptyList(),val epgSources: List<com.streamvault.domain.model.EpgSource> = emptyList(),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.ktindex 1f050825..9e2fd307 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt@@ -12,7 +12,6 @@ data class VodCatalogSnapshot<Item>()suspend fun <Item> buildVodPreviewCatalog(- providerId: Long,allFavorites: List<Favorite>,customCategories: List<Category>,providerCategories: List<Category>,@@ -20,7 +19,7 @@ suspend fun <Item> buildVodPreviewCatalog(libraryCount: Int,hiddenProviderCategoryIds: Set<Long>,loadItemsByIds: suspend (List<Long>) -> List<Item>,- loadCategoryPreviewRows: suspend (Long, Int) -> Map<Long?, List<Item>>,+ providerPreviews: Map<Long?, List<Item>>,itemId: (Item) -> Long,itemCategoryId: (Item) -> Long?,copyWithFavorite: (Item, Boolean) -> Item@@ -83,8 +82,6 @@ suspend fun <Item> buildVodPreviewCatalog(}}- val providerPreviews = loadCategoryPreviewRows(providerId, VodBrowseDefaults.PREVIEW_ROW_LIMIT)-providerCategories.forEach { category ->val preview = providerPreviews[category.id].orEmpty()diff --git a/app/src/main/res/drawable-hdpi/ic_launcher_vault_art.png b/app/src/main/res/drawable-hdpi/ic_launcher_vault_art.pngnew file mode 100644index 00000000..b095e588Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_launcher_vault_art.png differdiff --git a/app/src/main/res/drawable-mdpi/ic_launcher_vault_art.png b/app/src/main/res/drawable-mdpi/ic_launcher_vault_art.pngnew file mode 100644index 00000000..a61ea42bBinary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_launcher_vault_art.png differdiff --git a/app/src/main/res/drawable-xhdpi/ic_launcher_vault_art.png b/app/src/main/res/drawable-xhdpi/ic_launcher_vault_art.pngnew file mode 100644index 00000000..3afd423dBinary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_launcher_vault_art.png differdiff --git a/app/src/main/res/drawable-xxhdpi/ic_launcher_vault_art.png b/app/src/main/res/drawable-xxhdpi/ic_launcher_vault_art.pngnew file mode 100644index 00000000..96d6808bBinary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_launcher_vault_art.png differdiff --git a/app/src/main/res/drawable-xxxhdpi/ic_launcher_vault_art.png b/app/src/main/res/drawable-xxxhdpi/ic_launcher_vault_art.pngnew file mode 100644index 00000000..fac722dbBinary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/ic_launcher_vault_art.png differdiff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xmlindex d7c8739c..1a075557 100644--- a/app/src/main/res/drawable/ic_launcher_foreground.xml+++ b/app/src/main/res/drawable/ic_launcher_foreground.xml@@ -1,9 +1,5 @@-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="108dp"- android:height="108dp"- android:viewportWidth="108"- android:viewportHeight="108">- <path- android:fillColor="#00E676"- android:pathData="M33,45 L33,63 L51,63 L51,45 Z M57,45 L57,63 L75,63 L75,45 Z M33,69 L33,87 L51,87 L51,69 Z M57,69 L57,87 L75,87 L75,69 Z M33,21 L33,39 L75,39 L75,21 Z" />-</vector>+<?xml version="1.0" encoding="utf-8"?>+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"+ android:src="@drawable/ic_launcher_vault_art"+ android:gravity="fill"/>+diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xmlindex 5ed0a2df..f1db753b 100644--- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xml+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_vault.xml@@ -1,5 +1,5 @@<?xml version="1.0" encoding="utf-8"?><adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <background android:drawable="@color/ic_launcher_background"/>+ <background android:drawable="@android:color/black"/><foreground android:drawable="@drawable/ic_launcher_foreground"/></adaptive-icon>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 87f955bf..26fb0a32 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -30,6 +30,20 @@<string name="home_loading_channels">Loading channels...</string><string name="home_categories_title">Categories</string><string name="home_search_categories">Search categories...</string>+ <string name="home_quick_filters_title">Quick filters</string>+ <string name="home_quick_filters_button">Quick filters</string>+ <string name="home_quick_filters_show">Show</string>+ <string name="home_quick_filters_hide">Hide</string>+ <string name="home_quick_filters_add_chip">+ Add filter</string>+ <string name="home_quick_filters_add_title">Add quick filter</string>+ <string name="home_quick_filters_add_subtitle">Save a literal category search term so it appears in the Live TV quick filters drawer.</string>+ <string name="home_quick_filters_add_placeholder">Enter a quick filter</string>+ <string name="home_quick_filters_add_action">Save filter</string>+ <string name="home_quick_filters_all">All</string>+ <string name="home_quick_filters_showing_all">Showing all categories</string>+ <string name="home_quick_filters_active">Applied filter: %1$s</string>+ <string name="home_quick_filters_manual_search">Manual search: %1$s</string>+ <string name="home_quick_filters_empty">No saved quick filters yet. Add one to keep category searches close at hand.</string><string name="home_all_channels">All Channels</string><string name="home_recent_channels">Recent</string><string name="home_last_channel">Last Channel</string>@@ -118,6 +132,10 @@<string name="category_options_cancel">Cancel</string><string name="category_options_reorder">Reorder Items</string><string name="category_options_hide">Hide Category</string>+ <string name="category_options_pin">Pin Category</string>+ <string name="category_options_unpin">Unpin Category</string>+ <string name="category_pinned">Pinned %1$s.</string>+ <string name="category_unpinned">Unpinned %1$s.</string><string name="add_group_manage_title">Manage: %1$s</string><string name="add_group_close_cd">Close</string>@@ -267,6 +285,31 @@<string name="settings_playback_subtitle">Tune decoder and buffering behavior for smoother playback.</string><string name="settings_live_tv_channel_mode">Live TV Channel Mode</string><string name="settings_live_tv_channel_mode_subtitle">Choose how the Live TV browser should present channels and whether it should preview before playback.</string>+ <string name="settings_live_tv_quick_filters">Live TV Quick Filters</string>+ <string name="settings_live_tv_quick_filters_none">None</string>+ <plurals name="settings_live_tv_quick_filters_count">+ <item quantity="one">%1$d saved</item>+ <item quantity="other">%1$d saved</item>+ </plurals>+ <string name="settings_live_tv_quick_filters_dialog_title">Manage Live TV Quick Filters</string>+ <string name="settings_live_tv_quick_filters_dialog_subtitle">Save literal search terms like |AR| or Sports so they appear under the Live TV category search bar.</string>+ <string name="settings_live_tv_quick_filters_placeholder">Add a quick filter</string>+ <string name="settings_live_tv_quick_filters_add">Add Filter</string>+ <string name="settings_live_tv_quick_filters_empty">No quick filters saved yet.</string>+ <string name="settings_live_tv_quick_filters_saved">Saved filters</string>+ <string name="settings_live_tv_quick_filters_remove">Remove</string>+ <string name="settings_live_tv_quick_filter_visibility">Quick Filter Visibility</string>+ <string name="settings_live_tv_quick_filter_visibility_subtitle">Choose when the Live TV quick-filter control should appear under category search.</string>+ <string name="settings_live_tv_quick_filter_visibility_hide">Hide</string>+ <string name="settings_live_tv_quick_filter_visibility_hide_desc">Never show the quick-filter control in Live TV.</string>+ <string name="settings_live_tv_quick_filter_visibility_available">Show When Filters Exist</string>+ <string name="settings_live_tv_quick_filter_visibility_available_desc">Show the control only when at least one saved quick filter is available.</string>+ <string name="settings_live_tv_quick_filter_visibility_always">Always Visible</string>+ <string name="settings_live_tv_quick_filter_visibility_always_desc">Always show the control so filters can be added directly from Live TV.</string>+ <string name="settings_live_tv_quick_filter_blank">Enter a filter before saving it.</string>+ <string name="settings_live_tv_quick_filter_duplicate">%1$s is already saved.</string>+ <string name="settings_live_tv_quick_filter_added">Saved %1$s to Live TV quick filters.</string>+ <string name="settings_live_tv_quick_filter_removed">Removed %1$s from Live TV quick filters.</string><string name="settings_live_channel_numbering_mode">Live TV Channel Numbering</string><string name="settings_live_channel_numbering_mode_subtitle">Choose whether live channels use their position in the current group or keep the original numbers from the provider.</string><string name="settings_default_playback_speed">Default Playback Speed</string>@@ -608,6 +651,8 @@<string name="setup_server_hint">Server URL</string><string name="setup_user_hint">Username</string><string name="setup_pass_hint">Password</string>+ <string name="setup_show_password">Show password</string>+ <string name="setup_hide_password">Hide password</string><string name="setup_connecting">Connecting...</string><string name="setup_save">Save Changes</string><string name="setup_login">Login</string>@@ -884,6 +929,11 @@<string name="series_seasons">Seasons</string><string name="series_episodes">Episodes (%1$d)</string><string name="series_unwatched_badge">%1$d left to finish</string>+ <string name="vod_external_ratings_heading">Ratings</string>+ <string name="vod_rating_imdb">IMDb</string>+ <string name="vod_rating_rotten_tomatoes">Rotten Tomatoes</string>+ <string name="vod_rating_metacritic">Metacritic</string>+ <string name="vod_rating_tmdb">TMDb</string><string name="movie_loading_details">Loading details...</string><string name="movie_not_found">Movie not found</string><string name="movie_detail_back">Back to library</string>@@ -953,6 +1003,8 @@<string name="settings_clear_history_confirm">Clear History</string><string name="settings_xtream_text_classification">Xtream Name-Based Adult Detection</string><string name="settings_xtream_text_classification_subtitle">Use category name keywords to flag adult content when the provider doesn\'t set the adult flag explicitly</string>+ <string name="settings_prevent_standby">Keep Screen On During Playback</string>+ <string name="settings_prevent_standby_subtitle">Prevents the TV from showing a standby warning while a channel or video is playing</string><string name="settings_clear_history_dialog_title">Clear Watch History?</string><string name="settings_clear_history_dialog_body">This will permanently delete all watch history, continue watching progress, and last visited categories across all providers.</string>diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/26.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/26.jsonnew file mode 100644index 00000000..cdacd299--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/26.json@@ -0,0 +1,2995 @@+{+ "formatVersion": 1,+ "database": {+ "version": 26,+ "identityHash": "4276e357fccac0838db903507806b989",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "series_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_content_type_group_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4276e357fccac0838db903507806b989')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 26544a12..e8cabfe6 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -30,13 +30,14 @@ import com.streamvault.data.local.entity.*PlaybackHistoryEntity::class,SyncMetadataEntity::class,MovieCategoryHydrationEntity::class,+ SeriesCategoryHydrationEntity::class,EpgSourceEntity::class,ProviderEpgSourceEntity::class,EpgChannelEntity::class,EpgProgrammeEntity::class,ChannelEpgMappingEntity::class],- version = 25,+ version = 26,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -55,6 +56,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun playbackHistoryDao(): PlaybackHistoryDaoabstract fun syncMetadataDao(): SyncMetadataDaoabstract fun movieCategoryHydrationDao(): MovieCategoryHydrationDao+ abstract fun seriesCategoryHydrationDao(): SeriesCategoryHydrationDaoabstract fun epgSourceDao(): EpgSourceDaoabstract fun providerEpgSourceDao(): ProviderEpgSourceDaoabstract fun epgChannelDao(): EpgChannelDao@@ -1180,6 +1182,24 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ val MIGRATION_25_26 = object : Migration(25, 26) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("""+ CREATE TABLE IF NOT EXISTS series_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_hydrated_at INTEGER NOT NULL DEFAULT 0,+ item_count INTEGER NOT NULL DEFAULT 0,+ last_status TEXT NOT NULL DEFAULT 'IDLE',+ last_error TEXT,+ PRIMARY KEY(provider_id, category_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent())+ database.execSQL("CREATE INDEX IF NOT EXISTS index_series_category_hydration_provider_id ON series_category_hydration(provider_id)")+ }+ }+val MIGRATION_24_25 = object : Migration(24, 25) {override fun migrate(database: SupportSQLiteDatabase) {// ── epg_sources ──diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex eb6119c4..3ee49981 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -1693,6 +1693,21 @@ interface MovieCategoryHydrationDao {suspend fun deleteByProvider(providerId: Long)}+@Dao+interface SeriesCategoryHydrationDao {+ @Query("SELECT * FROM series_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ suspend fun get(providerId: Long, categoryId: Long): SeriesCategoryHydrationEntity?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(metadata: SeriesCategoryHydrationEntity)++ @Query("DELETE FROM series_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ suspend fun delete(providerId: Long, categoryId: Long)++ @Query("DELETE FROM series_category_hydration WHERE provider_id = :providerId")+ suspend fun deleteByProvider(providerId: Long)+}+// ── EPG Source DAOs ────────────────────────────────────────────────@Daodiff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex 9a80ac5d..1e699617 100644--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt@@ -683,6 +683,26 @@ data class MovieCategoryHydrationEntity(@ColumnInfo(name = "last_error") val lastError: String? = null)+@Entity(+ tableName = "series_category_hydration",+ primaryKeys = ["provider_id", "category_id"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [Index(value = ["provider_id"])]+)+data class SeriesCategoryHydrationEntity(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "category_id") val categoryId: Long,+ @ColumnInfo(name = "last_hydrated_at") val lastHydratedAt: Long = 0L,+ @ColumnInfo(name = "item_count") val itemCount: Int = 0,+ @ColumnInfo(name = "last_status") val lastStatus: String = "IDLE",+ @ColumnInfo(name = "last_error") val lastError: String? = null+)+// ── External EPG Source ────────────────────────────────────────────@Entity(diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex bb8b98b1..62d729ab 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -66,6 +66,8 @@ class BackupManagerImpl @Inject constructor("parentalPinHash" to (parentalPinBackup?.hash ?: ""),"parentalPinSalt" to (parentalPinBackup?.saltBase64 ?: ""),"appLanguage" to preferencesRepository.appLanguage.first(),+ "liveTvCategoryFilters" to preferencesRepository.liveTvCategoryFilters.first().joinToString("\n"),+ "liveTvQuickFilterVisibility" to (preferencesRepository.liveTvQuickFilterVisibility.first() ?: "always"),"playerPlaybackSpeed" to preferencesRepository.playerPlaybackSpeed.first().toString(),"preferredAudioLanguage" to (preferencesRepository.preferredAudioLanguage.first() ?: "auto"),"playerSubtitleTextScale" to preferencesRepository.playerSubtitleTextScale.first().toString(),@@ -291,6 +293,9 @@ class BackupManagerImpl @Inject constructor().takeIf { it.hash.isNotBlank() && it.saltBase64.isNotBlank() })prefs["appLanguage"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setAppLanguage(it) }+ prefs["liveTvCategoryFilters"]?.let { preferencesRepository.setLiveTvCategoryFilters(it.split('\n')) }+ prefs["liveTvQuickFilterVisibility"]?.takeIf { it.isNotBlank() }+ ?.let { preferencesRepository.setLiveTvQuickFilterVisibility(it) }prefs["playerPlaybackSpeed"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerPlaybackSpeed(it) }preferencesRepository.setPreferredAudioLanguage(prefs["preferredAudioLanguage"])prefs["playerSubtitleTextScale"]?.toFloatOrNull()?.let { preferencesRepository.setPlayerSubtitleTextScale(it) }diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex bc4ad985..ef401c42 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -60,6 +60,8 @@ class PreferencesRepository @Inject constructor(val DEFAULT_CATEGORY_ID = longPreferencesKey("default_category_id")val APP_LANGUAGE = stringPreferencesKey("app_language")val LIVE_TV_CHANNEL_MODE = stringPreferencesKey("live_tv_channel_mode")+ val LIVE_TV_CATEGORY_FILTERS = stringPreferencesKey("live_tv_category_filters")+ val LIVE_TV_QUICK_FILTER_VISIBILITY = stringPreferencesKey("live_tv_quick_filter_visibility")val LIVE_CHANNEL_NUMBERING_MODE = stringPreferencesKey("live_channel_numbering_mode")val VOD_VIEW_MODE = stringPreferencesKey("vod_view_mode")val GUIDE_DENSITY = stringPreferencesKey("guide_density")@@ -88,6 +90,7 @@ class PreferencesRepository @Inject constructor(val GUIDE_SCHEDULED_ONLY = intPreferencesKey("guide_scheduled_only")val RECENT_SEARCH_QUERIES = stringPreferencesKey("recent_search_queries")val XTREAM_TEXT_CLASSIFICATION = booleanPreferencesKey("xtream_text_classification")+ val PREVENT_STANDBY_DURING_PLAYBACK = booleanPreferencesKey("prevent_standby_during_playback")}private object ParentalSessionKeys {@@ -233,6 +236,16 @@ class PreferencesRepository @Inject constructor(}}+ val preventStandbyDuringPlayback: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.PREVENT_STANDBY_DURING_PLAYBACK] ?: true+ }++ suspend fun setPreventStandbyDuringPlayback(prevent: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.PREVENT_STANDBY_DURING_PLAYBACK] = prevent+ }+ }+suspend fun setPlayerMuted(muted: Boolean) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.PLAYER_MUTED] = muted@@ -411,27 +424,17 @@ class PreferencesRepository @Inject constructor(}override fun readSessionState(): ParentalControlSessionState {- val timeoutMs = parentalSessionPreferences.getLong(- ParentalSessionKeys.UNLOCK_TIMEOUT_MS,- ParentalControlSessionState.DEFAULT_UNLOCK_TIMEOUT_MS- )return ParentalControlSessionState(- unlockedCategoryExpirationsByProvider = decodeUnlockEntries(+ unlockedCategoryIdsByProvider = decodeUnlockEntries(parentalSessionPreferences.getString(ParentalSessionKeys.UNLOCK_ENTRIES, null)- ),- unlockTimeoutMs = timeoutMs+ ))}override fun writeSessionState(state: ParentalControlSessionState) {parentalSessionPreferences.edit().apply {- putLong(ParentalSessionKeys.UNLOCK_TIMEOUT_MS, state.unlockTimeoutMs)- val encodedUnlocks = encodeUnlockEntries(state.unlockedCategoryExpirationsByProvider)- if (encodedUnlocks.isBlank()) {- remove(ParentalSessionKeys.UNLOCK_ENTRIES)- } else {- putString(ParentalSessionKeys.UNLOCK_ENTRIES, encodedUnlocks)- }+ remove(ParentalSessionKeys.UNLOCK_TIMEOUT_MS)+ remove(ParentalSessionKeys.UNLOCK_ENTRIES)}.apply()}@@ -485,6 +488,55 @@ class PreferencesRepository @Inject constructor(}}+ val liveTvQuickFilterVisibility: Flow<String?> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.LIVE_TV_QUICK_FILTER_VISIBILITY]+ }++ suspend fun setLiveTvQuickFilterVisibility(mode: String) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.LIVE_TV_QUICK_FILTER_VISIBILITY] = mode+ }+ }++ val liveTvCategoryFilters: Flow<List<String>> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.LIVE_TV_CATEGORY_FILTERS]+ ?.split('\n')+ .orEmpty()+ .normalizeLiveTvCategoryFilters()+ }++ suspend fun setLiveTvCategoryFilters(filters: List<String>) {+ context.dataStore.edit { preferences ->+ val normalized = filters.normalizeLiveTvCategoryFilters()+ if (normalized.isEmpty()) {+ preferences.remove(PreferencesKeys.LIVE_TV_CATEGORY_FILTERS)+ } else {+ preferences[PreferencesKeys.LIVE_TV_CATEGORY_FILTERS] = normalized.joinToString("\n")+ }+ }+ }++ suspend fun addLiveTvCategoryFilter(filter: String): Boolean {+ val normalized = filter.trim()+ if (normalized.isBlank()) return false+ val current = liveTvCategoryFilters.first()+ if (current.any { it.equals(normalized, ignoreCase = true) }) {+ return false+ }+ setLiveTvCategoryFilters(current + normalized)+ return true+ }++ suspend fun removeLiveTvCategoryFilter(filter: String): Boolean {+ val current = liveTvCategoryFilters.first()+ val updated = current.filterNot { it.equals(filter, ignoreCase = true) }+ if (updated.size == current.size) {+ return false+ }+ setLiveTvCategoryFilters(updated)+ return true+ }+val liveChannelNumberingMode: Flow<ChannelNumberingMode> = context.dataStore.data.map { preferences ->ChannelNumberingMode.fromStorage(preferences[PreferencesKeys.LIVE_CHANNEL_NUMBERING_MODE])}@@ -610,6 +662,43 @@ class PreferencesRepository @Inject constructor(}}+ fun getPinnedCategoryIds(providerId: Long, type: ContentType): Flow<Set<Long>> {+ val key = stringPreferencesKey(pinnedCategoriesKey(providerId, type))+ return context.dataStore.data.map { preferences ->+ preferences[key]+ ?.split(',')+ ?.mapNotNull { token -> token.toLongOrNull() }+ ?.toSet()+ .orEmpty()+ }+ }++ suspend fun setCategoryPinned(+ providerId: Long,+ type: ContentType,+ categoryId: Long,+ pinned: Boolean+ ) {+ val key = stringPreferencesKey(pinnedCategoriesKey(providerId, type))+ context.dataStore.edit { preferences ->+ val current = preferences[key]+ ?.split(',')+ ?.mapNotNull { token -> token.toLongOrNull() }+ ?.toMutableSet()+ ?: mutableSetOf()+ if (pinned) {+ current += categoryId+ } else {+ current -= categoryId+ }+ if (current.isEmpty()) {+ preferences.remove(key)+ } else {+ preferences[key] = current.sorted().joinToString(",")+ }+ }+ }+fun getCategorySortMode(providerId: Long, type: ContentType): Flow<CategorySortMode> {val key = stringPreferencesKey(categorySortModeKey(providerId, type))return context.dataStore.data.map { preferences ->@@ -717,6 +806,22 @@ class PreferencesRepository @Inject constructor(private fun hiddenCategoriesKey(providerId: Long, type: ContentType): String ="hidden_categories_${providerId}_${type.name}"+ private fun pinnedCategoriesKey(providerId: Long, type: ContentType): String =+ "pinned_categories_${providerId}_${type.name}"+++ private fun List<String>.normalizeLiveTvCategoryFilters(): List<String> {+ val seen = linkedSetOf<String>()+ val normalized = mutableListOf<String>()+ forEach { filter ->+ val trimmed = filter.trim()+ if (trimmed.isBlank()) return@forEach+ if (seen.add(trimmed.lowercase())) {+ normalized += trimmed+ }+ }+ return normalized+ }private fun categorySortModeKey(providerId: Long, type: ContentType): String ="category_sort_${providerId}_${type.name}"@@ -753,32 +858,20 @@ class PreferencesRepository @Inject constructor(editor.apply()}- private fun encodeUnlockEntries(entries: Map<Long, Map<Long, Long>>): String {- return entries.entries- .sortedBy { it.key }- .flatMap { (providerId, categories) ->- categories.entries- .sortedBy { it.key }- .map { (categoryId, expiresAtMs) -> "$providerId:$categoryId:$expiresAtMs" }- }- .joinToString(",")- }-- private fun decodeUnlockEntries(encoded: String?): Map<Long, Map<Long, Long>> {+ private fun decodeUnlockEntries(encoded: String?): Map<Long, Set<Long>> {return encoded.orEmpty().split(',').asSequence().mapNotNull { token ->val parts = token.split(':')- if (parts.size != 3) return@mapNotNull null+ if (parts.size < 2) return@mapNotNull nullval providerId = parts[0].toLongOrNull() ?: return@mapNotNull nullval categoryId = parts[1].toLongOrNull() ?: return@mapNotNull null- val expiresAtMs = parts[2].toLongOrNull() ?: return@mapNotNull null- Triple(providerId, categoryId, expiresAtMs)+ providerId to categoryId}- .groupBy({ it.first }, { it.second to it.third })- .mapValues { (_, categoryEntries) -> categoryEntries.associate { (categoryId, expiresAtMs) -> categoryId to expiresAtMs } }+ .groupBy({ it.first }, { it.second })+ .mapValues { (_, categoryIds) -> categoryIds.toSet() }}private fun hasStoredParentalPin(preferences: Preferences): Boolean {diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.ktindex 85915ea8..f53c46c6 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt@@ -6,8 +6,6 @@ import com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.ProviderTypeimport java.net.URI-import java.net.URLDecoder-import java.nio.charset.StandardCharsetsimport javax.inject.Injectimport javax.inject.Singleton@@ -112,7 +110,7 @@ internal fun extractStreamExpirationTime(url: String): Long? {if (key !in expirationKeys) return@mapNotNull nullval rawValue = part.substringAfter('=', missingDelimiterValue = "")- val decodedValue = URLDecoder.decode(rawValue, StandardCharsets.UTF_8)+ val decodedValue = XtreamUrlCodec.decode(rawValue)parseXtreamExpirationDate(decodedValue)}.firstOrNull()diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.ktindex 7b256ac3..6a537270 100644--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt@@ -4,9 +4,43 @@ import com.streamvault.domain.model.ContentTypeimport java.net.URIimport java.net.URLDecoderimport java.net.URLEncoder-import java.nio.charset.StandardCharsetsimport java.util.Locale+internal object XtreamUrlCodec {+ private const val UTF_8_NAME = "UTF-8"+ private val encodeWithCharsetMethod = runCatching {+ URLEncoder::class.java.getMethod(+ "encode",+ String::class.java,+ java.nio.charset.Charset::class.java+ )+ }.getOrNull()+ private val decodeWithCharsetMethod = runCatching {+ URLDecoder::class.java.getMethod(+ "decode",+ String::class.java,+ java.nio.charset.Charset::class.java+ )+ }.getOrNull()++ fun encode(value: String): String {+ val encoded = encodeWithCharsetMethod+ ?.let { method ->+ runCatching { method.invoke(null, value, Charsets.UTF_8) as? String }.getOrNull()+ }+ ?: URLEncoder.encode(value, UTF_8_NAME)+ return encoded.replace("+", "%20")+ }++ fun decode(value: String): String {+ return decodeWithCharsetMethod+ ?.let { method ->+ runCatching { method.invoke(null, value, Charsets.UTF_8) as? String }.getOrNull()+ }+ ?: URLDecoder.decode(value, UTF_8_NAME)+ }+}+enum class XtreamStreamKind(val pathSegment: String) {LIVE("live"),MOVIE("movie"),@@ -367,11 +401,11 @@ object XtreamUrlFactory {private fun encodePathSegment(value: String): String = encodeQueryComponent(value)private fun encodeQueryComponent(value: String): String {- return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20")+ return XtreamUrlCodec.encode(value)}private fun decodeQueryComponent(value: String): String {- return URLDecoder.decode(value, StandardCharsets.UTF_8)+ return XtreamUrlCodec.decode(value)}private fun normalizeContainerExtension(containerExtension: String?): String? {diff --git a/data/src/main/java/com/streamvault/data/repository/ExternalRatingsRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ExternalRatingsRepositoryImpl.ktnew file mode 100644index 00000000..666b2197--- /dev/null+++ b/data/src/main/java/com/streamvault/data/repository/ExternalRatingsRepositoryImpl.kt@@ -0,0 +1,16 @@+package com.streamvault.data.repository++import com.streamvault.domain.model.ExternalRatings+import com.streamvault.domain.model.ExternalRatingsLookup+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.ExternalRatingsRepository+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class ExternalRatingsRepositoryImpl @Inject constructor() : ExternalRatingsRepository {++ override suspend fun getRatings(lookup: ExternalRatingsLookup): Result<ExternalRatings> {+ return Result.success(ExternalRatings.unavailable())+ }+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 9a284551..ba4e99f6 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -915,7 +915,6 @@ class MovieRepositoryImpl @Inject constructor(}private suspend fun shouldUsePersistedCategoryHydration(provider: ProviderEntity, providerId: Long): Boolean {- if (provider.xtreamFastSyncEnabled) return truereturn syncMetadataRepository.getMetadata(providerId)?.movieSyncMode == VodSyncMode.LAZY_BY_CATEGORY}diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 80f29a8a..ed089ae5 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -7,10 +7,14 @@ import com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.data.security.CredentialCrypto+import com.streamvault.data.sync.ContentCachePolicyimport com.streamvault.domain.model.*import com.streamvault.domain.model.Result.Successimport com.streamvault.domain.repository.SeriesRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.TimeoutCancellationExceptionimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.combine@@ -20,6 +24,7 @@ import kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutimport com.streamvault.data.util.toFtsPrefixQueryimport com.streamvault.data.util.rankSearchResults@@ -42,7 +47,8 @@ class SeriesRepositoryImpl @Inject constructor(private val providerDao: ProviderDao,private val xtreamApiService: XtreamApiService,private val preferencesRepository: PreferencesRepository,- private val xtreamStreamUrlResolver: XtreamStreamUrlResolver+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,+ private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao) : SeriesRepository {private companion object {const val SEARCH_RESULT_LIMIT = 200@@ -59,6 +65,8 @@ class SeriesRepositoryImpl @Inject constructor(private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()+ private val backgroundRefreshes = ConcurrentHashMap.newKeySet<String>()+ private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)override fun getSeries(providerId: Long): Flow<List<Series>> =combine(@@ -127,18 +135,27 @@ class SeriesRepositoryImpl @Inject constructor()}- override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> =+ override fun getCategoryPreviewRows(providerId: Long, categoryIds: List<Long>, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> =combine(categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name),preferencesRepository.parentalControlLevel) { categories, level ->+ val requestedIds = categoryIds.toSet()val filtered = if (level == 2) categories.filter { !it.isAdult && !it.isUserProtected } else categories- filtered to level+ filtered.filter { it.categoryId in requestedIds } to level}.flatMapLatest { (filteredCategories, level) ->if (filteredCategories.isEmpty()) {flowOf(emptyMap())} else {- // SQL LIMIT applied per-category — avoids loading the full catalog into memory+ filteredCategories.forEach { category ->+ val key = "${providerId}:${category.categoryId}"+ if (!loadedXtreamCategories.contains(key)) {+ val provider = providerDao.getById(providerId)+ if (provider != null && provider.type == com.streamvault.domain.model.ProviderType.XTREAM_CODES) {+ triggerSeriesCategoryHydration(providerId, category.categoryId, provider)+ }+ }+ }val categoryGroupFlows: List<Flow<Pair<Long?, List<Series>>>> = filteredCategories.map { cat ->seriesDao.getByCategoryPreview(providerId, cat.categoryId, limitPerCategory).map { entities ->@@ -697,18 +714,57 @@ class SeriesRepositoryImpl @Inject constructor(private suspend fun ensureXtreamCategoryLoaded(providerId: Long, categoryId: Long) {val key = "$providerId:$categoryId"if (loadedXtreamCategories.contains(key)) return- if (seriesDao.getCountByCategory(providerId, categoryId).first() > 0) {++ val provider = providerDao.getById(providerId) ?: return+ if (provider.type != ProviderType.XTREAM_CODES) return++ val localCount = seriesDao.getCountByCategory(providerId, categoryId).first()+ val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)+ val isFresh = hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)++ if (isFresh) {loadedXtreamCategories.add(key)return}- val provider = providerDao.getById(providerId) ?: return- if (provider.type != ProviderType.XTREAM_CODES) return+ // Stale but has cached data — show immediately, refresh in background+ if (localCount > 0) {+ loadedXtreamCategories.add(key)+ triggerSeriesCategoryHydration(providerId, categoryId, provider)+ return+ }+ // No data — fetch inline so the user sees something right away+ hydrateSeriesCategory(providerId, categoryId, provider)+ }++ private fun triggerSeriesCategoryHydration(+ providerId: Long,+ categoryId: Long,+ provider: ProviderEntity+ ) {+ val key = "$providerId:$categoryId"+ if (!backgroundRefreshes.add(key)) return+ repositoryScope.launch {+ try {+ hydrateSeriesCategory(providerId, categoryId, provider)+ } finally {+ backgroundRefreshes.remove(key)+ }+ }+ }++ private suspend fun hydrateSeriesCategory(+ providerId: Long,+ categoryId: Long,+ provider: ProviderEntity+ ) {+ val key = "$providerId:$categoryId"val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }lock.withLock {- if (loadedXtreamCategories.contains(key)) return- if (seriesDao.getCountByCategory(providerId, categoryId).first() > 0) {+ val localCount = seriesDao.getCountByCategory(providerId, categoryId).first()+ val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)+ if (hydration?.isFresh() == true && (localCount > 0 || hydration.itemCount == 0)) {loadedXtreamCategories.add(key)return}@@ -719,20 +775,44 @@ class SeriesRepositoryImpl @Inject constructor(xtreamProvider.getSeriesList(categoryId)}) {is Success -> {- seriesDao.replaceCategory(- providerId,- categoryId,- result.data.map { item -> item.toEntity() }- )+ val entities = result.data.map { item -> item.toEntity() }+ seriesDao.replaceCategory(providerId, categoryId, entities)episodeDao.deleteOrphans()+ seriesCategoryHydrationDao.upsert(+ SeriesCategoryHydrationEntity(+ providerId = providerId,+ categoryId = categoryId,+ lastHydratedAt = System.currentTimeMillis(),+ itemCount = entities.size,+ lastStatus = "SUCCESS",+ lastError = null+ )+ )loadedXtreamCategories.add(key)}else -> Unit}+ }.onFailure { error ->+ val currentCount = seriesDao.getCountByCategory(providerId, categoryId).first()+ seriesCategoryHydrationDao.upsert(+ SeriesCategoryHydrationEntity(+ providerId = providerId,+ categoryId = categoryId,+ lastHydratedAt = hydration?.lastHydratedAt ?: 0L,+ itemCount = currentCount,+ lastStatus = "ERROR",+ lastError = error.message+ )+ )}}}+ private fun SeriesCategoryHydrationEntity.isFresh(now: Long = System.currentTimeMillis()): Boolean {+ if (lastStatus != "SUCCESS") return false+ return !ContentCachePolicy.shouldRefresh(lastHydratedAt, ContentCachePolicy.SERIES_CATEGORY_TTL_MILLIS, now)+ }+private suspend fun <T> withXtreamSeriesCategoryTimeout(categoryId: Long,block: suspend () -> Tdiff --git a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.ktindex a50dc09c..d09ed027 100644--- a/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt+++ b/data/src/main/java/com/streamvault/data/sync/ContentCachePolicy.kt@@ -2,6 +2,7 @@ package com.streamvault.data.syncobject ContentCachePolicy {const val CATALOG_TTL_MILLIS = 24L * 60 * 60 * 1000L+ const val SERIES_CATEGORY_TTL_MILLIS = 6L * 60 * 60 * 1000Lconst val EPG_TTL_MILLIS = 6L * 60 * 60 * 1000Lfun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 6dbc9c71..86e373f9 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -381,20 +381,40 @@ class SyncManager @Inject constructor(val resolvedCategoryId = categoryId ?: returnval resolvedCategoryName = categoryName?.trim().takeUnless { it.isNullOrEmpty() }?: "Category $resolvedCategoryId"- categories.putIfAbsent(- resolvedCategoryId,- CategoryEntity(- categoryId = resolvedCategoryId,- name = resolvedCategoryName,- parentId = 0,- type = type,- providerId = providerId,- isAdult = isAdult || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)- )+ val candidate = CategoryEntity(+ categoryId = resolvedCategoryId,+ name = resolvedCategoryName,+ parentId = 0,+ type = type,+ providerId = providerId,+ isAdult = isAdult || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName))+ val existing = categories[resolvedCategoryId]+ categories[resolvedCategoryId] = if (existing == null) {+ candidate+ } else {+ existing.copy(+ name = preferredCategoryName(existing.name, candidate.name, resolvedCategoryId),+ isAdult = existing.isAdult || candidate.isAdult,+ isUserProtected = existing.isUserProtected || candidate.isUserProtected+ )+ }}fun entities(): List<CategoryEntity> = categories.values.toList()++ private fun preferredCategoryName(+ currentName: String,+ candidateName: String,+ categoryId: Long+ ): String {+ val placeholderName = "Category $categoryId"+ return when {+ currentName == placeholderName && candidateName != placeholderName -> candidateName+ currentName != placeholderName -> currentName+ else -> candidateName+ }+ }}private data class StagedCatalogSnapshot(@@ -562,7 +582,7 @@ class SyncManager @Inject constructor(progress(provider.id,onProgress,- if (provider.xtreamFastSyncEnabled) "Loading movie categories..." else "Downloading Movies..."+ "Downloading Movies...")val movieSyncResult = syncXtreamMoviesCatalog(provider = provider,@@ -584,21 +604,14 @@ class SyncManager @Inject constructor(when (val catalogResult = movieSyncResult.catalogResult) {is CatalogStrategyResult.Success -> {- val acceptedCount = if (movieSyncResult.syncMode == VodSyncMode.FAST_SYNC) {- movieSyncResult.categories?.let {- syncCatalogStore.replaceCategories(provider.id, "MOVIE", it)- }- movieDao.getCount(provider.id).first()- } else {- movieSyncResult.stagedSessionId?.let { sessionId ->- syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)- movieSyncResult.stagedAcceptedCount- } ?: syncCatalogStore.replaceMovieCatalog(- providerId = provider.id,- categories = movieSyncResult.categories,- movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }- )- }+ val acceptedCount = movieSyncResult.stagedSessionId?.let { sessionId ->+ syncCatalogStore.applyStagedMovieCatalog(provider.id, sessionId, movieSyncResult.categories)+ movieSyncResult.stagedAcceptedCount+ } ?: syncCatalogStore.replaceMovieCatalog(+ providerId = provider.id,+ categories = movieSyncResult.categories,+ movies = catalogResult.items.asSequence().map { movie -> movie.toEntity() }+ )metadata = metadata.copy(lastMovieSync = now,lastMovieAttempt = now,@@ -1070,7 +1083,7 @@ class SyncManager @Inject constructor(progress(provider.id,onProgress,- if (provider.xtreamFastSyncEnabled) "Refreshing movie categories..." else "Retrying Movies..."+ "Retrying Movies...")val useTextClassification = preferencesRepository.useXtreamTextClassification.first()val api = createXtreamSyncProvider(provider, useTextClassification)@@ -1333,62 +1346,107 @@ class SyncManager @Inject constructor(TAG,"Xtream movies strategy start for provider ${provider.id}. previousMode=${existingMetadata.movieSyncMode} rememberSequential=${existingMetadata.movieParallelFailuresRemembered}")- if (provider.xtreamFastSyncEnabled) {- progress(provider.id, onProgress, "Loading movie categories...")- }val rawVodCategories = fetchXtreamVodCategories(provider)val resolvedCategories = rawVodCategories?.let { categories -> api.mapCategories(ContentType.MOVIE, categories) }?.map { category -> category.toEntity(provider.id) }?.takeIf { it.isNotEmpty() }+ var fullPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("full"),+ categories = null+ )+ var pagedPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("paged"),+ categories = null+ )+ var categoryPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),+ categories = null+ )++ // Fast sync: skip all downloads, expose categories only and hydrate on demand.if (provider.xtreamFastSyncEnabled) {return if (!resolvedCategories.isNullOrEmpty()) {+ Log.i(TAG, "Xtream movies fast sync: returning LAZY_BY_CATEGORY for provider ${provider.id} with ${resolvedCategories.size} categories.")MovieCatalogSyncResult(- catalogResult = CatalogStrategyResult.Success(+ catalogResult = CatalogStrategyResult.Failure(strategyName = "fast_sync",- items = emptyList()+ error = IllegalStateException("Fast sync enabled; movies will hydrate on demand"),+ warnings = emptyList()),categories = resolvedCategories,- syncMode = VodSyncMode.FAST_SYNC+ syncMode = VodSyncMode.LAZY_BY_CATEGORY,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false))} else {+ Log.w(TAG, "Xtream movies fast sync: no categories available for provider ${provider.id}, falling through to standard strategies.")+ // No categories — fall through to normal strategies belowMovieCatalogSyncResult(catalogResult = CatalogStrategyResult.Failure(- strategyName = "fast_sync",- error = IllegalStateException("Fast Sync could not load VOD categories")+ strategyName = "fast_sync_no_categories",+ error = IllegalStateException("Fast sync enabled but no categories available"),+ warnings = listOf("Fast sync enabled but no categories returned from server.")),categories = null,- syncMode = VodSyncMode.FAST_SYNC+ syncMode = VodSyncMode.UNKNOWN,+ warnings = listOf("Fast sync enabled but no categories returned from server."),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false))}}- var fullPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("full"),- categories = null- )- var pagedPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("paged"),- categories = null- )- var categoryPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),- categories = null- )+ progress(provider.id, onProgress, "Checking Movies full catalog...")+ fullPayload = loadXtreamMoviesFull(provider, api)+ when (val fullResult = fullPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(+ catalogResult = fullResult,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),+ syncMode = VodSyncMode.FULL,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = false,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ ).also {+ Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items.")+ }+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(+ catalogResult = fullResult,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),+ syncMode = VodSyncMode.FULL,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = false,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ ).also {+ Log.w(TAG, "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items.")+ }+ else -> Unit+ }- progress(provider.id, onProgress, "Preparing Movies category sync...")- categoryPayload = loadXtreamMoviesByCategory(- provider = provider,- api = api,- rawCategories = rawVodCategories.orEmpty(),- onProgress = onProgress,- preferSequential = existingMetadata.movieParallelFailuresRemembered- )+ if (!resolvedCategories.isNullOrEmpty()) {+ progress(provider.id, onProgress, "Preparing Movies category sync...")+ categoryPayload = loadXtreamMoviesByCategory(+ provider = provider,+ api = api,+ rawCategories = rawVodCategories.orEmpty(),+ onProgress = onProgress,+ preferSequential = existingMetadata.movieParallelFailuresRemembered+ )+ }when (val categoryResult = categoryPayload.catalogResult) {is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(catalogResult = categoryResult,- categories = resolvedCategories ?: categoryPayload.categories,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),syncMode = VodSyncMode.CATEGORY_BULK,warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),strategyFeedback = XtreamStrategyFeedback(@@ -1406,7 +1464,7 @@ class SyncManager @Inject constructor(}is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(catalogResult = categoryResult,- categories = resolvedCategories ?: categoryPayload.categories,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),syncMode = VodSyncMode.CATEGORY_BULK,warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),strategyFeedback = XtreamStrategyFeedback(@@ -1474,7 +1532,7 @@ class SyncManager @Inject constructor(when (val fullResult = fullPayload.catalogResult) {is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(catalogResult = fullResult,- categories = resolvedCategories ?: fullPayload.categories,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),syncMode = VodSyncMode.FULL,warnings = strategyWarnings(categoryPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),strategyFeedback = XtreamStrategyFeedback(@@ -1702,7 +1760,10 @@ class SyncManager @Inject constructor(when (fullResult) {is CatalogStrategyResult.Success -> return CatalogSyncPayload(catalogResult = fullResult,- categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),+ categories = mergePreferredAndFallbackCategories(+ resolvedCategories,+ buildFallbackLiveCategories(provider.id, fullResult.items)+ ),warnings = emptyList(),strategyFeedback = XtreamStrategyFeedback(attemptedFullCatalog = true,@@ -1711,7 +1772,10 @@ class SyncManager @Inject constructor()is CatalogStrategyResult.Partial -> return CatalogSyncPayload(catalogResult = fullResult,- categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),+ categories = mergePreferredAndFallbackCategories(+ resolvedCategories,+ buildFallbackLiveCategories(provider.id, fullResult.items)+ ),warnings = emptyList(),strategyFeedback = XtreamStrategyFeedback(attemptedFullCatalog = true,@@ -1732,8 +1796,14 @@ class SyncManager @Inject constructor(return CatalogSyncPayload(catalogResult = categoryResult,categories = when (categoryResult) {- is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)- is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)+ is CatalogStrategyResult.Success -> mergePreferredAndFallbackCategories(+ resolvedCategories,+ buildFallbackLiveCategories(provider.id, categoryResult.items)+ )+ is CatalogStrategyResult.Partial -> mergePreferredAndFallbackCategories(+ resolvedCategories,+ buildFallbackLiveCategories(provider.id, categoryResult.items)+ )else -> null},warnings = strategyWarnings(fullResult),@@ -2219,6 +2289,35 @@ class SyncManager @Inject constructor(categories = null)+ // Fast sync: skip all downloads, expose categories only and hydrate on demand.+ if (provider.xtreamFastSyncEnabled) {+ return if (!resolvedCategories.isNullOrEmpty()) {+ Log.i(TAG, "Xtream series fast sync: returning lazy_by_category for provider ${provider.id} with ${resolvedCategories.size} categories.")+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "lazy_by_category",+ error = IllegalStateException("Fast sync enabled; series will hydrate on demand"),+ warnings = emptyList()+ ),+ categories = resolvedCategories,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ } else {+ Log.w(TAG, "Xtream series fast sync: no categories available for provider ${provider.id}.")+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "fast_sync_no_categories",+ error = IllegalStateException("Fast sync enabled but no series categories available"),+ warnings = listOf("Fast sync enabled but no series categories returned from server.")+ ),+ categories = null,+ warnings = listOf("Fast sync enabled but no series categories returned from server."),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ }+ }+if (!resolvedCategories.isNullOrEmpty()) {progress(provider.id, onProgress, "Preparing Series category sync...")categoryPayload = loadXtreamSeriesByCategory(@@ -2232,7 +2331,7 @@ class SyncManager @Inject constructor(is CatalogStrategyResult.Success,is CatalogStrategyResult.Partial -> return CatalogSyncPayload(catalogResult = categoryResult,- categories = resolvedCategories ?: categoryPayload.categories,+ categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),warnings = strategyWarnings(fullPayload.catalogResult),strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = true,@@ -3268,23 +3367,71 @@ class SyncManager @Inject constructor(categoryName: (T) -> String?,isAdult: (T) -> Boolean): List<CategoryEntity> {- return items- .asSequence()- .mapNotNull { item ->- val resolvedCategoryId = categoryId(item) ?: return@mapNotNull null- val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }- ?: "Category $resolvedCategoryId"- CategoryEntity(- categoryId = resolvedCategoryId,- name = resolvedCategoryName,- parentId = 0,- type = type,- providerId = providerId,- isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)+ val categories = LinkedHashMap<Long, CategoryEntity>()+ items.forEach { item ->+ val resolvedCategoryId = categoryId(item) ?: return@forEach+ val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }+ ?: "Category $resolvedCategoryId"+ val candidate = CategoryEntity(+ categoryId = resolvedCategoryId,+ name = resolvedCategoryName,+ parentId = 0,+ type = type,+ providerId = providerId,+ isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)+ )+ val existing = categories[resolvedCategoryId]+ categories[resolvedCategoryId] = if (existing == null) {+ candidate+ } else {+ existing.copy(+ name = preferredFallbackCategoryName(existing.name, candidate.name, resolvedCategoryId),+ isAdult = existing.isAdult || candidate.isAdult,+ isUserProtected = existing.isUserProtected || candidate.isUserProtected)}- .distinctBy { it.categoryId }- .toList()+ }+ return categories.values.toList()+ }++ private fun preferredFallbackCategoryName(+ currentName: String,+ candidateName: String,+ categoryId: Long+ ): String {+ val placeholderName = "Category $categoryId"+ return when {+ currentName == placeholderName && candidateName != placeholderName -> candidateName+ currentName != placeholderName -> currentName+ else -> candidateName+ }+ }++ private fun mergePreferredAndFallbackCategories(+ preferred: List<CategoryEntity>?,+ fallback: List<CategoryEntity>?+ ): List<CategoryEntity>? {+ if (preferred.isNullOrEmpty()) return fallback?.takeIf { it.isNotEmpty() }+ if (fallback.isNullOrEmpty()) return preferred++ val merged = LinkedHashMap<Pair<Long, ContentType>, CategoryEntity>()+ preferred.forEach { category ->+ merged[category.categoryId to category.type] = category+ }+ fallback.forEach { category ->+ val key = category.categoryId to category.type+ val existing = merged[key]+ merged[key] = if (existing == null) {+ category+ } else {+ existing.copy(+ isAdult = existing.isAdult || category.isAdult,+ isUserProtected = existing.isUserProtected || category.isUserProtected,+ name = existing.name.ifBlank { category.name }+ )+ }+ }+ return merged.values.toList()}private suspend fun stageMovieItems(diff --git a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.ktindex 7afeba5b..7184d22a 100644--- a/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt+++ b/data/src/main/java/com/streamvault/data/util/AdultContentClassifier.kt@@ -2,21 +2,42 @@ package com.streamvault.data.utilimport java.text.Normalizerimport java.util.Locale+import java.util.concurrent.ConcurrentHashMapobject AdultContentClassifier {- private val keywords = listOf(- // English+ private const val MAX_CLASSIFICATION_CACHE_SIZE = 4096+ private val diacriticsRegex = Regex("\\p{InCombiningDiacriticalMarks}+")+ private val separatorsRegex = Regex("[^a-z0-9+]+")++ // Strong tags are matched via normalized substring contains (case-insensitive by normalization).+ private val strongContainsKeywords = listOf("xxx",- "adult","18+",+ "+18",+ "+ 18",+ "18 +","18 plus",- "18plus",+ "plus 18",+ "18plus"+ )++ // Softer tags are matched on normalized word boundaries to avoid overmatching.+ private val boundaryKeywords = listOf(+ // English+ "adult",+ "adults","porn","porno",+ "milf",+ "gay",+ "lesbian","sex","erotic","hustler","playboy",+ "hanime",+ "live cam",+ "live cams","redlight","red light",// Spanish@@ -43,15 +64,25 @@ object AdultContentClassifier {"pour adultes","para adultos")+ private val normalizedStrongKeywords = strongContainsKeywords.map(::normalize).distinct()+ private val normalizedBoundaryKeywords = boundaryKeywords.map(::normalize).distinct()+ private val classificationCache = ConcurrentHashMap<String, Boolean>()fun isAdultCategoryName(name: String?): Boolean {if (name.isNullOrBlank()) return false- // Pad with spaces so we can do word-boundary matching via contains().- // This prevents "sex" matching "Essex" or "Middlesex", "adult" matching "adulting", etc.- val normalized = " ${normalize(name)} "- return keywords.any { keyword ->- normalized.contains(" ${normalize(keyword)} ")+ val normalized = normalize(name)+ classificationCache[normalized]?.let { return it }+ val normalizedPadded = " $normalized "+ val isAdult = normalizedStrongKeywords.any { keyword ->+ normalized.contains(keyword)+ } || normalizedBoundaryKeywords.any { keyword ->+ normalizedPadded.contains(" $keyword ")+ }+ if (classificationCache.size >= MAX_CLASSIFICATION_CACHE_SIZE) {+ classificationCache.clear()}+ classificationCache[normalized] = isAdult+ return isAdult}fun adultCategoryIds(namesById: Map<Long, String>): Set<Long> {@@ -63,9 +94,9 @@ object AdultContentClassifier {private fun normalize(value: String): String {val decomposed = Normalizer.normalize(value, Normalizer.Form.NFD)return decomposed- .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")+ .replace(diacriticsRegex, "").lowercase(Locale.ROOT)- .replace(Regex("[^a-z0-9+]+"), " ")+ .replace(separatorsRegex, " ").trim()}}diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.ktindex c870a444..ebbfdd31 100644--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt@@ -5,6 +5,7 @@ import java.util.Localeobject UrlSecurityPolicy {private val secureRemoteSchemes = setOf("https")+ private val playlistSourceSchemes = setOf("http", "https")private val xtreamServerSchemes = setOf("http", "https")private val localSchemes = setOf("file", "content")// IPTV stream/asset URLs may legitimately use plain HTTP or RTSP@@ -37,10 +38,10 @@ object UrlSecurityPolicy {}fun validatePlaylistSourceUrl(url: String): String? {- return if (isAllowedImportedUrl(url)) {+ return if (!containsNewlines(url) && hasAllowedScheme(url, playlistSourceSchemes + localSchemes)) {null} else {- "Playlist sources must use HTTPS or point to a local file."+ "Playlist sources must use HTTP, HTTPS, or point to a local file."}}diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamDtoParsingTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamDtoParsingTest.ktnew file mode 100644index 00000000..b97e30c6--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamDtoParsingTest.kt@@ -0,0 +1,82 @@+package com.streamvault.data.remote.xtream++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.dto.XtreamSeriesItem+import com.streamvault.data.remote.dto.XtreamStream+import com.streamvault.data.remote.dto.XtreamVodMovieData+import kotlinx.serialization.decodeFromString+import kotlinx.serialization.json.Json+import org.junit.Test++class XtreamDtoParsingTest {++ private val json = Json {+ ignoreUnknownKeys = true+ isLenient = true+ }++ @Test+ fun `xtream category decodes is_adult from provider payload`() {+ val category = json.decodeFromString<XtreamCategory>(+ """+ {+ "category_id": "28",+ "category_name": "|+18| ADULTS LIVE",+ "is_adult": "1"+ }+ """.trimIndent()+ )++ assertThat(category.isAdult).isTrue()+ }++ @Test+ fun `xtream stream and vod payloads decode nullable is_adult`() {+ val stream = json.decodeFromString<XtreamStream>(+ """+ {+ "name": "Adult Channel",+ "stream_id": 99,+ "is_adult": 1+ }+ """.trimIndent()+ )+ val vod = json.decodeFromString<XtreamVodMovieData>(+ """+ {+ "stream_id": 123,+ "name": "Adult Movie",+ "is_adult": "true"+ }+ """.trimIndent()+ )++ assertThat(stream.isAdult).isTrue()+ assertThat(vod.isAdult).isTrue()+ }++ @Test+ fun `xtream series payload decodes false and missing is_adult safely`() {+ val explicitFalse = json.decodeFromString<XtreamSeriesItem>(+ """+ {+ "series_id": 77,+ "name": "Series",+ "is_adult": "0"+ }+ """.trimIndent()+ )+ val missing = json.decodeFromString<XtreamSeriesItem>(+ """+ {+ "series_id": 78,+ "name": "Series Two"+ }+ """.trimIndent()+ )++ assertThat(explicitFalse.isAdult).isFalse()+ assertThat(missing.isAdult).isNull()+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.ktindex 90bb156e..b2b09cd8 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt@@ -258,6 +258,86 @@ class XtreamProviderTest {assertThat(movie.isAdult).isTrue()}+ @Test+ fun `getLiveCategories honors explicit adult flag from xtream category payload`() = runBlocking {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ liveCategories = listOf(+ XtreamCategory(+ categoryId = "28",+ categoryName = "General",+ isAdult = true+ )+ )+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )++ val category = provider.getLiveCategories().getOrNull().orEmpty().single()++ assertThat(category.id).isEqualTo(28L)+ assertThat(category.isAdult).isTrue()+ }++ @Test+ fun `getLiveStreams inherits adult status from xtream category flag`() = runBlocking {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ liveCategories = listOf(+ XtreamCategory(+ categoryId = "28",+ categoryName = "General",+ isAdult = true+ )+ ),+ liveStreams = listOf(+ XtreamStream(+ name = "Channel",+ streamId = 77,+ categoryId = "28",+ categoryName = "General",+ isAdult = null+ )+ )+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )++ val channel = provider.getLiveStreams().getOrNull().orEmpty().single()++ assertThat(channel.isAdult).isTrue()+ }++ @Test+ fun `getSeriesCategories honors explicit adult flag from xtream category payload`() = runBlocking {+ val provider = XtreamProvider(+ providerId = 42,+ api = FakeXtreamApiService(+ seriesCategories = listOf(+ XtreamCategory(+ categoryId = "683",+ categoryName = "Series",+ isAdult = true+ )+ )+ ),+ serverUrl = "https://example.com",+ username = "user",+ password = "pass"+ )++ val category = provider.getSeriesCategories().getOrNull().orEmpty().single()++ assertThat(category.id).isEqualTo(683L)+ assertThat(category.isAdult).isTrue()+ }+@Testfun `vod list and details both normalize ratings to ten point scale`() = runBlocking {val provider = XtreamProvider(diff --git a/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.kt b/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.ktnew file mode 100644index 00000000..7b2a9abf--- /dev/null+++ b/data/src/test/java/com/streamvault/data/util/AdultContentClassifierTest.kt@@ -0,0 +1,41 @@+package com.streamvault.data.util++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class AdultContentClassifierTest {++ @Test+ fun `matches plus18 and adults labels used by xtream categories`() {+ assertThat(AdultContentClassifier.isAdultCategoryName("|+18| ADULTS LIVE")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("|+18| ADULTS")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("ADULT")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("ADULTS")).isTrue()+ }++ @Test+ fun `matches both 18plus orientations`() {+ assertThat(AdultContentClassifier.isAdultCategoryName("18+")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("+18")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("+ 18")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("18 +")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("Plus 18")).isTrue()+ }++ @Test+ fun `matching is case insensitive`() {+ assertThat(AdultContentClassifier.isAdultCategoryName("aDuLtS live")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("xXx premium")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("HaNiMe TV")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("MILF channel")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("Gay premium")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("LESBIAN world")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("Live Cam 4K")).isTrue()+ assertThat(AdultContentClassifier.isAdultCategoryName("LIVE CAMS HD")).isTrue()+ }++ @Test+ fun `boundary terms avoid obvious false positives`() {+ assertThat(AdultContentClassifier.isAdultCategoryName("Essex Sports")).isFalse()+ }+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.ktindex ec8ea10f..3261acfc 100644--- a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt+++ b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt@@ -22,12 +22,13 @@ class UrlSecurityPolicyTest {}@Test- fun `validatePlaylistSourceUrl allows local and https only`() {+ fun `validatePlaylistSourceUrl allows local http and https`() {assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("file:///storage/emulated/0/playlist.m3u")).isNull()assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("content://downloads/public_downloads/1")).isNull()assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("https://example.com/playlist.m3u")).isNull()- assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("http://example.com/playlist.m3u"))- .isEqualTo("Playlist sources must use HTTPS or point to a local file.")+ assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("http://example.com/playlist.m3u")).isNull()+ assertThat(UrlSecurityPolicy.validatePlaylistSourceUrl("ftp://example.com/playlist.m3u"))+ .isEqualTo("Playlist sources must use HTTP, HTTPS, or point to a local file.")}@Testdiff --git a/docs/images/dashboard.svg b/docs/images/dashboard.svgnew file mode 100644index 00000000..049dad7a--- /dev/null+++ b/docs/images/dashboard.svg@@ -0,0 +1,17 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Dashboard placeholder">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#07111B"/>+ <stop offset="100%" stop-color="#162338"/>+ </linearGradient>+ </defs>+ <rect width="1280" height="720" fill="url(#bg)"/>+ <rect x="56" y="56" width="1168" height="608" rx="30" fill="#0F1B29" stroke="#264C6D95"/>+ <text x="96" y="136" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Dashboard Placeholder</text>+ <text x="96" y="184" fill="#BBC6D8" font-family="Segoe UI, Arial, sans-serif" font-size="24">Replace with a captured StreamVault dashboard screenshot.</text>+ <rect x="96" y="236" width="280" height="360" rx="24" fill="#1D2E46"/>+ <rect x="408" y="236" width="720" height="72" rx="18" fill="#162338"/>+ <rect x="408" y="332" width="720" height="72" rx="18" fill="#162338"/>+ <rect x="408" y="428" width="720" height="72" rx="18" fill="#162338"/>+ <rect x="408" y="524" width="720" height="72" rx="18" fill="#162338"/>+</svg>\ No newline at end of filediff --git a/docs/images/live-tv.svg b/docs/images/live-tv.svgnew file mode 100644index 00000000..29b4c335--- /dev/null+++ b/docs/images/live-tv.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Live TV placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <rect x="54" y="54" width="1172" height="612" rx="30" fill="#0F1B29" stroke="#264C6D95"/>+ <text x="96" y="132" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Live TV Placeholder</text>+ <rect x="96" y="176" width="250" height="430" rx="22" fill="#162338"/>+ <rect x="380" y="176" width="748" height="320" rx="28" fill="#1D2E46"/>+ <rect x="380" y="522" width="748" height="84" rx="18" fill="#162338"/>+</svg>\ No newline at end of filediff --git a/docs/images/movies.svg b/docs/images/movies.svgnew file mode 100644index 00000000..3648eb03--- /dev/null+++ b/docs/images/movies.svg@@ -0,0 +1,9 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Movies placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <text x="96" y="128" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Movies Placeholder</text>+ <rect x="92" y="176" width="220" height="360" rx="24" fill="#1D2E46"/>+ <rect x="348" y="176" width="220" height="360" rx="24" fill="#1D2E46"/>+ <rect x="604" y="176" width="220" height="360" rx="24" fill="#1D2E46"/>+ <rect x="860" y="176" width="220" height="360" rx="24" fill="#1D2E46"/>+ <rect x="92" y="570" width="988" height="24" rx="12" fill="#162338"/>+</svg>\ No newline at end of filediff --git a/docs/images/multiview.svg b/docs/images/multiview.svgnew file mode 100644index 00000000..3387fadb--- /dev/null+++ b/docs/images/multiview.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Multiview placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <text x="96" y="128" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Multiview Placeholder</text>+ <rect x="96" y="176" width="520" height="220" rx="24" fill="#1D2E46"/>+ <rect x="664" y="176" width="520" height="220" rx="24" fill="#1D2E46"/>+ <rect x="96" y="444" width="520" height="220" rx="24" fill="#1D2E46"/>+ <rect x="664" y="444" width="520" height="220" rx="24" fill="#1D2E46"/>+</svg>\ No newline at end of filediff --git a/docs/images/player.svg b/docs/images/player.svgnew file mode 100644index 00000000..7ae6e6cc--- /dev/null+++ b/docs/images/player.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Player placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <rect x="72" y="72" width="1136" height="576" rx="36" fill="#162338"/>+ <polygon points="610,280 610,440 742,360" fill="#F5F7FB" opacity="0.9"/>+ <text x="96" y="128" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Player Placeholder</text>+ <rect x="120" y="580" width="1040" height="12" rx="6" fill="#264C6D95"/>+ <rect x="120" y="580" width="430" height="12" rx="6" fill="#69A8FF"/>+</svg>\ No newline at end of filediff --git a/docs/images/search.svg b/docs/images/search.svgnew file mode 100644index 00000000..244eac43--- /dev/null+++ b/docs/images/search.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Search placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <text x="96" y="128" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Search Placeholder</text>+ <rect x="96" y="176" width="1088" height="88" rx="24" fill="#162338"/>+ <rect x="96" y="312" width="1088" height="72" rx="18" fill="#0F1B29" stroke="#264C6D95"/>+ <rect x="96" y="408" width="1088" height="72" rx="18" fill="#0F1B29" stroke="#264C6D95"/>+ <rect x="96" y="504" width="1088" height="72" rx="18" fill="#0F1B29" stroke="#264C6D95"/>+</svg>\ No newline at end of filediff --git a/docs/images/series.svg b/docs/images/series.svgnew file mode 100644index 00000000..9423963e--- /dev/null+++ b/docs/images/series.svg@@ -0,0 +1,9 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="720" viewBox="0 0 1280 720" role="img" aria-label="Series placeholder">+ <rect width="1280" height="720" fill="#07111B"/>+ <text x="96" y="128" fill="#F5F7FB" font-family="Segoe UI, Arial, sans-serif" font-size="44" font-weight="700">Series Placeholder</text>+ <rect x="92" y="180" width="260" height="400" rx="26" fill="#1D2E46"/>+ <rect x="388" y="180" width="800" height="88" rx="20" fill="#162338"/>+ <rect x="388" y="292" width="800" height="88" rx="20" fill="#162338"/>+ <rect x="388" y="404" width="800" height="88" rx="20" fill="#162338"/>+ <rect x="388" y="516" width="800" height="64" rx="16" fill="#223754"/>+</svg>\ No newline at end of filediff --git a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.ktindex 79a7625e..565965ed 100644--- a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlManager.kt@@ -1,11 +1,5 @@package com.streamvault.domain.manager-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.delay-import kotlinx.coroutines.launchimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow@@ -17,128 +11,67 @@ import javax.inject.Singletonclass ParentalControlManager @Inject constructor(private val sessionStore: ParentalControlSessionStore) {- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)private val stateLock = Any()- private var expirationJob: Job? = null- private val _sessionState = MutableStateFlow(normalizeState(sessionStore.readSessionState(), currentTimeMs()))private val _unlockedCategoriesByProvider = MutableStateFlow<Map<Long, Set<Long>>>(emptyMap())val unlockedCategoriesByProvider: StateFlow<Map<Long, Set<Long>>> =_unlockedCategoriesByProvider.asStateFlow()- val unlockTimeoutMs: StateFlow<Long>- get() = MutableStateFlow(_sessionState.value.unlockTimeoutMs).asStateFlow()-init {- publishState(_sessionState.value, persist = true, nowMs = currentTimeMs())+ if (sessionStore.readSessionState().unlockedCategoryIdsByProvider.isNotEmpty()) {+ sessionStore.writeSessionState(ParentalControlSessionState())+ }}fun unlockedCategoriesForProvider(providerId: Long) =unlockedCategoriesByProvider.map { it[providerId] ?: emptySet() }- fun unlockCategory(providerId: Long, categoryId: Long, nowMs: Long = currentTimeMs()) {+ fun unlockCategory(providerId: Long, categoryId: Long) {synchronized(stateLock) {- val state = refreshLocked(nowMs)- val providerEntries = state.unlockedCategoryExpirationsByProvider[providerId].orEmpty() +- (categoryId to (nowMs + state.unlockTimeoutMs))publishState(- state.copy(- unlockedCategoryExpirationsByProvider = state.unlockedCategoryExpirationsByProvider +- (providerId to providerEntries)- ),- nowMs = nowMs+ _unlockedCategoriesByProvider.value + (providerId to setOf(categoryId)))}}- fun isCategoryUnlocked(providerId: Long, categoryId: Long, nowMs: Long = currentTimeMs()): Boolean {- synchronized(stateLock) {- val state = refreshLocked(nowMs)- return state.unlockedCategoryExpirationsByProvider[providerId]?.get(categoryId)?.let { it > nowMs } == true- }- }-- fun setUnlockTimeout(timeoutMs: Long) {+ fun isCategoryUnlocked(providerId: Long, categoryId: Long): Boolean {synchronized(stateLock) {- val state = refreshLocked(currentTimeMs())- publishState(state.copy(unlockTimeoutMs = normalizeTimeout(timeoutMs)), nowMs = currentTimeMs())+ return _unlockedCategoriesByProvider.value[providerId]?.contains(categoryId) == true}}- fun refreshSessionState(nowMs: Long = currentTimeMs()) {+ fun retainUnlockedCategory(providerId: Long, categoryId: Long?) {synchronized(stateLock) {- publishState(normalizeState(sessionStore.readSessionState(), nowMs), persist = true, nowMs = nowMs)+ val retainedCategoryIds = categoryId+ ?.takeIf { unlockedCategoryIds ->+ _unlockedCategoriesByProvider.value[providerId]?.contains(unlockedCategoryIds) == true+ }+ ?.let(::setOf)+ .orEmpty()+ val updatedUnlocks = if (retainedCategoryIds.isEmpty()) {+ _unlockedCategoriesByProvider.value - providerId+ } else {+ _unlockedCategoriesByProvider.value + (providerId to retainedCategoryIds)+ }+ publishState(updatedUnlocks)}}fun clearUnlockedCategories(providerId: Long? = null) {synchronized(stateLock) {- val state = refreshLocked(currentTimeMs())val updatedUnlocks = if (providerId == null) {emptyMap()} else {- state.unlockedCategoryExpirationsByProvider - providerId+ _unlockedCategoriesByProvider.value - providerId}- publishState(state.copy(unlockedCategoryExpirationsByProvider = updatedUnlocks), nowMs = currentTimeMs())- }- }-- private fun refreshLocked(nowMs: Long): ParentalControlSessionState {- val normalized = normalizeState(_sessionState.value, nowMs)- if (normalized != _sessionState.value) {- publishState(normalized, nowMs = nowMs)+ publishState(updatedUnlocks)}- return normalized}private fun publishState(- state: ParentalControlSessionState,- persist: Boolean = true,- nowMs: Long = currentTimeMs()+ state: Map<Long, Set<Long>>) {- val normalized = normalizeState(state, nowMs)- _sessionState.value = normalized- _unlockedCategoriesByProvider.value = normalized.unlockedCategoryExpirationsByProvider- .mapValues { (_, categories) -> categories.keys }- .filterValues { it.isNotEmpty() }-- if (persist) {- sessionStore.writeSessionState(normalized)- }- scheduleExpiration(normalized)- }-- private fun scheduleExpiration(state: ParentalControlSessionState) {- expirationJob?.cancel()- val nextExpiration = state.unlockedCategoryExpirationsByProvider.values- .flatMap { it.values }- .minOrNull()- ?: return- val delayMs = nextExpiration - currentTimeMs()- if (delayMs <= 0L) {- refreshSessionState()- return- }- expirationJob = scope.launch {- delay(delayMs)- refreshSessionState()- }- }-- private fun normalizeState(state: ParentalControlSessionState, nowMs: Long): ParentalControlSessionState {- val prunedUnlocks = state.unlockedCategoryExpirationsByProvider- .mapValues { (_, categories) ->- categories.filterValues { expiresAt -> expiresAt > nowMs }- }+ _unlockedCategoriesByProvider.value = state.filterValues { it.isNotEmpty() }-- return state.copy(- unlockedCategoryExpirationsByProvider = prunedUnlocks,- unlockTimeoutMs = normalizeTimeout(state.unlockTimeoutMs)- )+ sessionStore.writeSessionState(ParentalControlSessionState())}-- private fun normalizeTimeout(timeoutMs: Long): Long =- timeoutMs.coerceAtLeast(ParentalControlSessionState.MIN_UNLOCK_TIMEOUT_MS)-- private fun currentTimeMs(): Long = System.currentTimeMillis()}diff --git a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlSessionStore.kt b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlSessionStore.ktindex a6c3bee0..6ea82679 100644--- a/domain/src/main/java/com/streamvault/domain/manager/ParentalControlSessionStore.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/ParentalControlSessionStore.kt@@ -1,14 +1,8 @@package com.streamvault.domain.managerdata class ParentalControlSessionState(- val unlockedCategoryExpirationsByProvider: Map<Long, Map<Long, Long>> = emptyMap(),- val unlockTimeoutMs: Long = DEFAULT_UNLOCK_TIMEOUT_MS-) {- companion object {- const val DEFAULT_UNLOCK_TIMEOUT_MS: Long = 30 * 60 * 1000L- const val MIN_UNLOCK_TIMEOUT_MS: Long = 60 * 1000L- }-}+ val unlockedCategoryIdsByProvider: Map<Long, Set<Long>> = emptyMap()+)interface ParentalControlSessionStore {fun readSessionState(): ParentalControlSessionStatediff --git a/domain/src/main/java/com/streamvault/domain/model/ExternalRatings.kt b/domain/src/main/java/com/streamvault/domain/model/ExternalRatings.ktnew file mode 100644index 00000000..4ff300de--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/model/ExternalRatings.kt@@ -0,0 +1,46 @@+package com.streamvault.domain.model++data class ExternalRatingsLookup(+ val contentType: ContentType,+ val title: String,+ val releaseYear: String? = null,+ val tmdbId: Long? = null+) {+ init {+ require(contentType == ContentType.MOVIE || contentType == ContentType.SERIES) {+ "External ratings support only movie and series lookups"+ }+ require(title.isNotBlank()) { "title must not be blank" }+ }+}++data class ExternalRatings(+ val imdb: ExternalRatingValue = ExternalRatingValue.unavailable(),+ val rottenTomatoes: ExternalRatingValue = ExternalRatingValue.unavailable(),+ val metacritic: ExternalRatingValue = ExternalRatingValue.unavailable(),+ val tmdb: ExternalRatingValue = ExternalRatingValue.unavailable(),+ val lastUpdatedEpochMs: Long = 0L+) {+ companion object {+ fun unavailable(lastUpdatedEpochMs: Long = 0L): ExternalRatings = ExternalRatings(+ lastUpdatedEpochMs = lastUpdatedEpochMs+ )+ }+}++data class ExternalRatingValue(+ val displayValue: String,+ val available: Boolean+) {+ companion object {+ fun available(displayValue: String): ExternalRatingValue = ExternalRatingValue(+ displayValue = displayValue,+ available = true+ )++ fun unavailable(): ExternalRatingValue = ExternalRatingValue(+ displayValue = "N/A",+ available = false+ )+ }+}\ No newline at end of filediff --git a/domain/src/main/java/com/streamvault/domain/repository/ExternalRatingsRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ExternalRatingsRepository.ktnew file mode 100644index 00000000..e3684e12--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/repository/ExternalRatingsRepository.kt@@ -0,0 +1,9 @@+package com.streamvault.domain.repository++import com.streamvault.domain.model.ExternalRatings+import com.streamvault.domain.model.ExternalRatingsLookup+import com.streamvault.domain.model.Result++interface ExternalRatingsRepository {+ suspend fun getRatings(lookup: ExternalRatingsLookup): Result<ExternalRatings>+}\ No newline at end of filediff --git a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.ktindex 6758ce2d..50a8cca7 100644--- a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt@@ -14,7 +14,7 @@ interface SeriesRepository {fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>>fun getSeriesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Series>>fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>>- fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Series>>>+ fun getCategoryPreviewRows(providerId: Long, categoryIds: List<Long>, limitPerCategory: Int): Flow<Map<Long?, List<Series>>>fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>>fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>>fun getSeriesByIds(ids: List<Long>): Flow<List<Series>>diff --git a/domain/src/test/java/com/streamvault/domain/manager/ParentalControlManagerTest.kt b/domain/src/test/java/com/streamvault/domain/manager/ParentalControlManagerTest.ktindex 46c53324..987d08e5 100644--- a/domain/src/test/java/com/streamvault/domain/manager/ParentalControlManagerTest.kt+++ b/domain/src/test/java/com/streamvault/domain/manager/ParentalControlManagerTest.kt@@ -10,13 +10,11 @@ class ParentalControlManagerTest {private lateinit var manager: ParentalControlManagerprivate lateinit var store: FakeParentalControlSessionStore- private var baseNow: Long = 0L@Beforefun setup() {store = FakeParentalControlSessionStore()manager = ParentalControlManager(store)- baseNow = System.currentTimeMillis() + 10_000L}@Test@@ -27,55 +25,55 @@ class ParentalControlManagerTest {@Testfun `unlockCategory makes category accessible`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1)).isTrue()+ manager.unlockCategory(1L, 100L)+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isTrue()}@Testfun `unlockCategory is scoped to provider`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1)).isTrue()- assertThat(manager.isCategoryUnlocked(2L, 100L, nowMs = baseNow + 1)).isFalse()+ manager.unlockCategory(1L, 100L)+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isTrue()+ assertThat(manager.isCategoryUnlocked(2L, 100L)).isFalse()}@Test- fun `multiple categories can be unlocked per provider`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- manager.unlockCategory(1L, 200L, nowMs = baseNow)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1)).isTrue()- assertThat(manager.isCategoryUnlocked(1L, 200L, nowMs = baseNow + 1)).isTrue()+ fun `unlockCategory replaces previous unlocked category for provider`() {+ manager.unlockCategory(1L, 100L)+ manager.unlockCategory(1L, 200L)++ assertThat(manager.isCategoryUnlocked(1L, 100L)).isFalse()+ assertThat(manager.isCategoryUnlocked(1L, 200L)).isTrue()}@Testfun `clearUnlockedCategories with provider clears that provider only`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- manager.unlockCategory(2L, 200L, nowMs = baseNow)+ manager.unlockCategory(1L, 100L)+ manager.unlockCategory(2L, 200L)manager.clearUnlockedCategories(1L)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1)).isFalse()- assertThat(manager.isCategoryUnlocked(2L, 200L, nowMs = baseNow + 1)).isTrue()+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isFalse()+ assertThat(manager.isCategoryUnlocked(2L, 200L)).isTrue()}@Testfun `clearUnlockedCategories without provider clears all`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- manager.unlockCategory(2L, 200L, nowMs = baseNow)+ manager.unlockCategory(1L, 100L)+ manager.unlockCategory(2L, 200L)manager.clearUnlockedCategories()- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1)).isFalse()- assertThat(manager.isCategoryUnlocked(2L, 200L, nowMs = baseNow + 1)).isFalse()+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isFalse()+ assertThat(manager.isCategoryUnlocked(2L, 200L)).isFalse()assertThat(manager.unlockedCategoriesByProvider.value).isEmpty()}@Testfun `unlockedCategoriesForProvider emits correct set`() = runTest {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- manager.unlockCategory(1L, 200L, nowMs = baseNow)+ manager.unlockCategory(1L, 200L)val unlocked = manager.unlockedCategoriesForProvider(1L).first()- assertThat(unlocked).containsExactly(100L, 200L)+ assertThat(unlocked).containsExactly(200L)}@Test@@ -86,45 +84,40 @@ class ParentalControlManagerTest {@Testfun `unlocking same category twice is idempotent`() {- manager.unlockCategory(1L, 100L, nowMs = baseNow)- manager.unlockCategory(1L, 100L, nowMs = baseNow + 1_000L)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 1_001L)).isTrue()+ manager.unlockCategory(1L, 100L)+ manager.unlockCategory(1L, 100L)+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isTrue()assertThat(manager.unlockedCategoriesByProvider.value[1L]).hasSize(1)}@Test- fun `refreshSessionState prunes expired unlocks from persisted store`() {- store.state = ParentalControlSessionState(- unlockedCategoryExpirationsByProvider = mapOf(- 1L to mapOf(- 100L to (baseNow - 500L),- 200L to (baseNow + 2_000L)- )- )- )+ fun `retainUnlockedCategory keeps unlocked category when revisiting same category`() {+ manager.unlockCategory(1L, 100L)- manager.refreshSessionState(nowMs = baseNow)+ manager.retainUnlockedCategory(1L, 100L)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow)).isFalse()- assertThat(manager.isCategoryUnlocked(1L, 200L, nowMs = baseNow)).isTrue()- assertThat(store.state.unlockedCategoryExpirationsByProvider[1L]).containsKey(200L)- assertThat(store.state.unlockedCategoryExpirationsByProvider[1L]).doesNotContainKey(100L)+ assertThat(manager.isCategoryUnlocked(1L, 100L)).isTrue()}@Test- fun `setUnlockTimeout persists minimum normalized timeout`() {- manager.setUnlockTimeout(5_000L)+ fun `retainUnlockedCategory clears unlock when leaving category`() {+ manager.unlockCategory(1L, 100L)- assertThat(store.state.unlockTimeoutMs).isEqualTo(ParentalControlSessionState.MIN_UNLOCK_TIMEOUT_MS)+ manager.retainUnlockedCategory(1L, 200L)++ assertThat(manager.isCategoryUnlocked(1L, 100L)).isFalse()}@Test- fun `unlockCategory expires after timeout`() {- manager.setUnlockTimeout(60_000L)- manager.unlockCategory(1L, 100L, nowMs = baseNow)+ fun `manager clears persisted unlock state on startup`() {+ store.state = ParentalControlSessionState(+ unlockedCategoryIdsByProvider = mapOf(1L to setOf(100L))+ )++ manager = ParentalControlManager(store)- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 59_999L)).isTrue()- assertThat(manager.isCategoryUnlocked(1L, 100L, nowMs = baseNow + 60_000L)).isFalse()+ assertThat(store.state.unlockedCategoryIdsByProvider).isEmpty()+ assertThat(manager.unlockedCategoriesByProvider.value).isEmpty()}private class FakeParentalControlSessionStore : ParentalControlSessionStore {diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.ktindex fe973006..d92c5d63 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SearchContentTest.kt@@ -139,7 +139,7 @@ private class FakeSeriesRepository(override fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>> = unsupported()override fun getSeriesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Series>> = unsupported()override fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>> = unsupported()- override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> = unsupported()+ override fun getCategoryPreviewRows(providerId: Long, categoryIds: List<Long>, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> = unsupported()override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>> = unsupported()override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>> = unsupported()override fun getSeriesByIds(ids: List<Long>): Flow<List<Series>> = unsupported()diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.ktindex cdc7c1e5..e827d1df 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt@@ -121,6 +121,7 @@ private class FakeSyncProviderRepository(override suspend fun refreshProviderData(providerId: Long,force: Boolean,+ movieFastSyncOverride: Boolean?,onProgress: ((String) -> Unit)?): Result<Unit> {lastRefreshCall = RefreshCall(providerId, force)diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.ktindex 5b64bf10..4c64e08b 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt@@ -201,6 +201,7 @@ private class FakeProviderRepository : ProviderRepository {override suspend fun refreshProviderData(providerId: Long,force: Boolean,+ movieFastSyncOverride: Boolean?,onProgress: ((String) -> Unit)?): Result<Unit> = error("Not used in test")