StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Fix player UX and data sync race conditions
Davidonabc7e023343a6
diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.ktindex e598c892..91f2cebd 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlayerSmokeTest.kt@@ -77,6 +77,8 @@ class PlayerSmokeTest {audioTrackCount = 2,videoQualityCount = 2,currentRecordingStatus = null,+ isMuted = false,+ mediaTitle = null,playButtonFocusRequester = playButtonFocusRequester,onClose = {},onTogglePlayPause = {},@@ -92,6 +94,7 @@ class PlayerSmokeTest {onOpenAudioTracks = {},onOpenVideoTracks = {},onOpenSplitScreen = {},+ onToggleMute = {},clockLabelOverride = TestFixtures.fixedClock)LaunchedEffect(Unit) {@@ -103,6 +106,52 @@ class PlayerSmokeTest {composeRule.onNodeWithText(">").assertIsFocused()}+ @Test+ fun playerControlsOverlay_showsMuteActionWhenMuted() {+ composeRule.setContent {+ StreamVaultTheme {+ PlayerControlsOverlay(+ visible = true,+ title = TestFixtures.liveTitle,+ contentType = "LIVE",+ isPlaying = true,+ currentProgram = null,+ currentChannelName = TestFixtures.liveTitle,+ displayChannelNumber = TestFixtures.displayChannelNumber,+ currentPosition = 0L,+ duration = 0L,+ aspectRatioLabel = TestFixtures.aspectRatioLabel,+ subtitleTrackCount = 1,+ audioTrackCount = 2,+ videoQualityCount = 2,+ currentRecordingStatus = null,+ isMuted = true,+ mediaTitle = null,+ playButtonFocusRequester = FocusRequester(),+ onClose = {},+ onTogglePlayPause = {},+ onSeekBackward = {},+ onSeekForward = {},+ onRestartProgram = {},+ onOpenArchive = {},+ onStartRecording = {},+ onStopRecording = {},+ onScheduleRecording = {},+ onToggleAspectRatio = {},+ onOpenSubtitleTracks = {},+ onOpenAudioTracks = {},+ onOpenVideoTracks = {},+ onOpenSplitScreen = {},+ onToggleMute = {},+ clockLabelOverride = TestFixtures.fixedClock+ )+ }+ }++ composeRule.onNodeWithText("Muted").assertExists()+ composeRule.onNodeWithText("Unmute").assertExists()+ }+@Testfun playerTrackSelectionDialog_selectsAudioTrack() {var selectedTrackId: String? = nulldiff --git a/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.ktindex 51fe77ac..d29ebe62 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlayGoldenTest.kt@@ -47,6 +47,8 @@ class PlayerOverlayGoldenTest {audioTrackCount = 2,videoQualityCount = 2,currentRecordingStatus = null,+ isMuted = false,+ mediaTitle = null,playButtonFocusRequester = FocusRequester(),onClose = {},onTogglePlayPause = {},@@ -62,6 +64,7 @@ class PlayerOverlayGoldenTest {onOpenAudioTracks = {},onOpenVideoTracks = {},onOpenSplitScreen = {},+ onToggleMute = {},clockLabelOverride = TestFixtures.fixedClock)}diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.ktindex d2f9019b..e0cefe0b 100644--- a/app/src/main/java/com/streamvault/app/MainActivity.kt+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt@@ -143,6 +143,10 @@ class MainActivity : ComponentActivity() {applyPlayerPictureInPictureParams()}+ fun enterPlayerPictureInPictureModeFromPlayer(): Boolean {+ return enterPlayerPictureInPictureModeIfEligible()+ }+private fun enterPlayerPictureInPictureModeIfEligible(): Boolean {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || isInPictureInPictureMode) {return falsediff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.ktindex cd83624c..bf00f172 100644--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt@@ -16,7 +16,6 @@ import androidx.work.ExistingPeriodicWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManager-import java.util.concurrent.TimeUnit@HiltAndroidAppclass StreamVaultApp : Application(), SingletonImageLoader.Factory {@@ -28,6 +27,7 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {// BLD-H02: Require network + device idle so the worker doesn't drain battery.val gcConstraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiresBatteryNotLow(true).setRequiresDeviceIdle(true).build()diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex eacd528c..27ee5536 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -536,7 +536,7 @@ fun AppNavigation() {archiveTitle = playerRequest?.archiveTitle,returnRoute = playerRequest?.returnRoute,onBack = { navController.popBackStack() },- onNavigate = { route -> navController.navigate(route) }+ onNavigate = { route -> navController.navigateIfResumed(route) { launchSingleTop = true } })}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 96165c66..0ea7cd54 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@@ -156,24 +156,14 @@ fun ChannelCard(isDragging = isDragging) { isFocused ->if (!isLocked) {- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- // Initials fallback — visible when image is absent or fails to load- Text(- text = channel.name.take(2).uppercase(java.util.Locale.ROOT),- style = MaterialTheme.typography.titleMedium,- color = TextSecondary- )- if (!channel.logoUrl.isNullOrBlank()) {- AsyncImage(- model = rememberCrossfadeImageModel(channel.logoUrl),- contentDescription = channel.name,- modifier = Modifier- .fillMaxSize()- .clip(channelCardShape),- contentScale = ContentScale.Fit- )- }- }+ ChannelLogoBadge(+ channelName = channel.name,+ logoUrl = channel.logoUrl,+ shape = channelCardShape,+ textStyle = MaterialTheme.typography.titleMedium,+ textColor = TextSecondary,+ modifier = Modifier.fillMaxSize()+ )}Box(diff --git a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.ktindex 33eca542..b2001abc 100644--- a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt@@ -23,8 +23,11 @@ fun <T : Any> CategoryRow(modifier: Modifier = Modifier,onSeeAll: (() -> Unit)? = null,keySelector: ((T) -> Any)? = null,+ contentTypeSelector: ((T) -> Any?)? = null,itemContent: @Composable (T) -> Unit) {+ val resolvedContentTypeSelector: (T) -> Any? = contentTypeSelector ?: { null }+Column(modifier = modifier.fillMaxWidth()) {AppSectionHeader(title = title,@@ -42,7 +45,8 @@ fun <T : Any> CategoryRow() {items(items = items,- key = keySelector // null = index-based keys (safe default)+ key = keySelector, // null = index-based keys (safe default)+ contentType = resolvedContentTypeSelector) { item ->itemContent(item)}diff --git a/app/src/main/java/com/streamvault/app/ui/components/ChannelLogo.kt b/app/src/main/java/com/streamvault/app/ui/components/ChannelLogo.ktnew file mode 100644index 00000000..b8525213--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/components/ChannelLogo.kt@@ -0,0 +1,101 @@+package com.streamvault.app.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import coil3.compose.AsyncImage+import com.streamvault.app.ui.design.AppColors+import java.util.Locale++@Composable+fun ChannelLogoBadge(+ channelName: String,+ logoUrl: String?,+ modifier: Modifier = Modifier,+ shape: Shape = RoundedCornerShape(12.dp),+ backgroundColor: Color = AppColors.SurfaceEmphasis,+ contentPadding: PaddingValues = PaddingValues(0.dp),+ textStyle: TextStyle = MaterialTheme.typography.titleMedium,+ textColor: Color = AppColors.TextSecondary+) {+ val model = rememberCrossfadeImageModel(logoUrl?.takeIf { it.isNotBlank() })+ var showFallback by remember(model) { mutableStateOf(true) }++ Box(+ modifier = modifier+ .clip(shape)+ .background(backgroundColor),+ contentAlignment = Alignment.Center+ ) {+ if (!showFallback && model != null) {+ AsyncImage(+ model = model,+ contentDescription = channelName,+ contentScale = ContentScale.Fit,+ onLoading = { showFallback = true },+ onError = { showFallback = true },+ onSuccess = { showFallback = false },+ modifier = Modifier+ .fillMaxSize()+ .padding(contentPadding)+ )+ } else {+ Text(+ text = channelInitials(channelName),+ style = textStyle,+ color = textColor,+ fontWeight = FontWeight.Bold+ )+ if (model != null) {+ AsyncImage(+ model = model,+ contentDescription = channelName,+ contentScale = ContentScale.Fit,+ onLoading = { showFallback = true },+ onError = { showFallback = true },+ onSuccess = { showFallback = false },+ modifier = Modifier+ .fillMaxSize()+ .padding(contentPadding)+ )+ }+ }+ }+}++private fun channelInitials(name: String): String {+ val words = name+ .trim()+ .split(Regex("\\s+"))+ .filter { it.isNotBlank() }++ val initials = when {+ words.size >= 2 -> buildString {+ append(words[0].first())+ append(words[1].first())+ }+ words.size == 1 -> words[0].take(2)+ else -> "--"+ }++ return initials.uppercase(Locale.ROOT)+}\ No newline at end of filediff --git a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.ktindex 81ca95e6..995e920d 100644--- a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt@@ -70,7 +70,11 @@ fun ContinueWatchingRow(contentPadding = PaddingValues(horizontal = 20.dp),horizontalArrangement = Arrangement.spacedBy(8.dp)) {- items(items = items, key = { it.id }) { history ->+ items(+ items = items,+ key = { it.id },+ contentType = { it.contentType }+ ) { history ->ContinueWatchingTile(history = history, onClick = { onItemClick(history) })}}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 677612b8..ca5c4d78 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@@ -24,6 +24,7 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.ExperimentalComposeUiApiimport androidx.compose.ui.Modifierimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.foundation.focusableimport androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.focus.onFocusChanged@@ -54,7 +55,8 @@ fun SearchInput(modifier: Modifier = Modifier,focusRequester: FocusRequester = remember { FocusRequester() },imeAction: ImeAction = ImeAction.Search,- onSearch: () -> Unit = {}+ onSearch: () -> Unit = {},+ enabled: Boolean = true) {var isFocused by remember { mutableStateOf(false) }val keyboardController = LocalSoftwareKeyboardController.current@@ -69,12 +71,18 @@ fun SearchInput(.height(40.dp).background(backgroundColor, RoundedCornerShape(8.dp)).border(borderWidth, borderColor, RoundedCornerShape(8.dp))- .onFocusChanged { isFocused = it.hasFocus }- .focusProperties { enter = { focusRequester } }- .clickable {+ .onFocusChanged {+ isFocused = enabled && it.hasFocus+ }+ .focusProperties {+ canFocus = enabled+ enter = { focusRequester }+ }+ .clickable(enabled = enabled) {focusRequester.requestFocus()keyboardController?.show()}+ .focusable(enabled = enabled).padding(horizontal = 12.dp),contentAlignment = Alignment.CenterStart) {@@ -104,6 +112,7 @@ fun SearchInput(textStyle = MaterialTheme.typography.bodySmall.copy(color = OnSurface),singleLine = true,cursorBrush = SolidColor(Primary),+ enabled = enabled,keyboardOptions = KeyboardOptions(imeAction = imeAction),keyboardActions = KeyboardActions(onSearch = { onSearch() }))diff --git a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.ktindex a77a27f8..b1a12fed 100644--- a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt@@ -80,7 +80,11 @@ fun ChipRowSection(contentPadding = contentPadding,horizontalArrangement = Arrangement.spacedBy(10.dp)) {- items(chips, key = { it.key }) { chip ->+ items(+ items = chips,+ key = { it.key },+ contentType = { "selection_chip" }+ ) { chip ->val isSelected = chip.key == selectedKeySurface(onClick = chip.onClick,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 b4e7e47e..bf5f82d3 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@@ -29,6 +29,7 @@ import androidx.compose.ui.focus.onFocusChangedimport androidx.compose.foundation.shape.CircleShapeimport kotlinx.coroutines.delayimport androidx.tv.material3.*+import android.view.KeyEvent as AndroidKeyEvent@Composablefun AddToGroupDialog(@@ -56,7 +57,24 @@ fun AddToGroupDialog(canInteract = true}+ val blockOpenGesture: (KeyEvent) -> Boolean = { event ->+ !canInteract &&+ event.nativeKeyEvent.action == AndroidKeyEvent.ACTION_UP &&+ when (event.nativeKeyEvent.keyCode) {+ AndroidKeyEvent.KEYCODE_DPAD_CENTER,+ AndroidKeyEvent.KEYCODE_ENTER,+ AndroidKeyEvent.KEYCODE_NUMPAD_ENTER,+ AndroidKeyEvent.KEYCODE_BUTTON_A -> true+ else -> false+ }+ }+val safeDismiss = { if (canInteract) onDismiss() }+ val safeToggleFavorite = { if (canInteract) onToggleFavorite() }+ val safeOpenSplitScreenPlanner = { if (canInteract) onOpenSplitScreenPlanner?.invoke() }+ val safeCreateGroup = { if (canInteract) showCreateGroup = true }+ val safeAddToGroup: (Category) -> Unit = { group -> if (canInteract) onAddToGroup(group) }+ val safeRemoveFromGroup: (Category) -> Unit = { group -> if (canInteract) onRemoveFromGroup(group) }if (showCreateGroup) {CreateGroupDialog(@@ -79,6 +97,7 @@ fun AddToGroupDialog(modifier = Modifier.width(400.dp).padding(16.dp)+ .onPreviewKeyEvent(blockOpenGesture)) {Column(modifier = Modifier.padding(24.dp)) {// Header@@ -108,7 +127,7 @@ fun AddToGroupDialog(item {var isFocused by remember { mutableStateOf(false) }Button(- onClick = onToggleFavorite,+ onClick = safeToggleFavorite,modifier = Modifier.fillMaxWidth().focusRequester(contentFocusRequester)@@ -151,7 +170,7 @@ fun AddToGroupDialog(item {var isFocused by remember { mutableStateOf(false) }Button(- onClick = onOpenSplitScreenPlanner,+ onClick = safeOpenSplitScreenPlanner,modifier = Modifier.fillMaxWidth().onFocusChanged { isFocused = it.isFocused }@@ -222,7 +241,7 @@ fun AddToGroupDialog()Button(onClick = {- if (isMember) onRemoveFromGroup(group) else onAddToGroup(group)+ if (isMember) safeRemoveFromGroup(group) else safeAddToGroup(group)},modifier = Modifier.background(@@ -256,7 +275,7 @@ fun AddToGroupDialog(var isFocused by remember { mutableStateOf(false) }Spacer(modifier = Modifier.height(8.dp))OutlinedButton(- onClick = { showCreateGroup = true },+ onClick = safeCreateGroup,modifier = Modifier.fillMaxWidth().onFocusChanged { isFocused = it.isFocused }diff --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 c8ddfab5..4b5061d5 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@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.aspectRatioimport androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height@@ -42,6 +43,7 @@ import androidx.tv.material3.Surfaceimport androidx.tv.material3.Textimport coil3.compose.AsyncImageimport com.streamvault.app.R+import com.streamvault.app.ui.components.ChannelLogoBadgeimport com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.design.AppMotion@@ -92,25 +94,16 @@ fun LiveChannelRowCard(.width(logoWidth).fillMaxHeight().clip(RoundedCornerShape(12.dp))- .background(AppColors.SurfaceEmphasis),- contentAlignment = Alignment.Center) {- // Fallback initials always visible; covered by AsyncImage on successful load- Text(- text = channel.name.take(2).uppercase(),- style = MaterialTheme.typography.titleLarge,- color = AppColors.TextSecondary+ ChannelLogoBadge(+ channelName = channel.name,+ logoUrl = channel.logoUrl,+ backgroundColor = AppColors.SurfaceEmphasis,+ contentPadding = PaddingValues(logoPadding),+ textStyle = MaterialTheme.typography.titleLarge,+ textColor = AppColors.TextSecondary,+ modifier = Modifier.fillMaxSize())- if (!channel.logoUrl.isNullOrBlank()) {- AsyncImage(- model = rememberCrossfadeImageModel(channel.logoUrl),- contentDescription = channel.name,- modifier = Modifier- .fillMaxSize()- .padding(logoPadding),- contentScale = ContentScale.Fit- )- }}Column(modifier = Modifier.weight(1f),diff --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 58c68529..2d55bcb3 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@@ -44,6 +44,7 @@ import androidx.tv.material3.SurfaceDefaultsimport androidx.tv.material3.Textimport coil3.compose.AsyncImageimport com.streamvault.app.R+import com.streamvault.app.ui.components.ChannelLogoBadgeimport com.streamvault.app.navigation.Routesimport com.streamvault.app.ui.components.CategoryRowimport com.streamvault.app.ui.components.ChannelCard@@ -106,20 +107,22 @@ fun DashboardScreen(}val orderedSections = rememberDashboardSections(uiState)- if (uiState.isLoading) {- Box(- modifier = Modifier.fillMaxSize(),- contentAlignment = Alignment.Center- ) {- CircularProgressIndicator(color = Primary)- }- return@AppScreenScaffold- }-androidx.compose.foundation.lazy.LazyColumn(modifier = Modifier.fillMaxSize(),contentPadding = PaddingValues(bottom = 28.dp)) {+ if (uiState.isLoading && orderedSections.isEmpty()) {+ item(key = "dashboard_loading") {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 28.dp, bottom = 12.dp),+ contentAlignment = Alignment.Center+ ) {+ CircularProgressIndicator(color = Primary)+ }+ }+ }if (uiState.providerWarnings.isNotEmpty()) {item(key = "provider_warnings") {DashboardProviderWarningCard(@@ -776,25 +779,17 @@ private fun FavoriteChannelLogoCard(modifier = Modifier.size(54.dp).clip(RoundedCornerShape(999.dp))- .background(AppColors.SurfaceEmphasis),- contentAlignment = Alignment.Center) {- if (!channel.logoUrl.isNullOrBlank()) {- AsyncImage(- model = rememberCrossfadeImageModel(channel.logoUrl),- contentDescription = channel.name,- contentScale = ContentScale.Fit,- modifier = Modifier- .fillMaxSize()- .padding(8.dp)- )- } else {- Text(- text = channel.name.take(2).uppercase(),- style = MaterialTheme.typography.labelLarge,- color = TextPrimary- )- }+ ChannelLogoBadge(+ channelName = channel.name,+ logoUrl = channel.logoUrl,+ shape = RoundedCornerShape(999.dp),+ backgroundColor = AppColors.SurfaceEmphasis,+ contentPadding = PaddingValues(8.dp),+ textStyle = MaterialTheme.typography.labelLarge,+ textColor = TextPrimary,+ modifier = Modifier.fillMaxSize()+ )}Text(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.ktindex 91c695c6..55a43f91 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt@@ -39,6 +39,7 @@ import kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.onStartimport kotlinx.coroutines.launch@HiltViewModel@@ -75,19 +76,19 @@ class DashboardViewModel @Inject constructor(flowOf(DashboardUiState(isLoading = false))} else {val contentShelves = combine(- observeFavoriteChannels(provider.id),- observeRecentChannels(provider.id),- observeContinueWatching(provider.id),+ observeFavoriteChannels(provider.id).onStart { emit(emptyList()) },+ observeRecentChannels(provider.id).onStart { emit(emptyList()) },+ observeContinueWatching(provider.id).onStart { emit(emptyList()) },movieRepository.getMovies(provider.id).map { movies ->movies.sortedByDescending(::movieFreshnessScore).take(MOVIE_SHELF_LIMIT)- },+ }.onStart { emit(emptyList()) },seriesRepository.getSeries(provider.id).map { series ->series.sortedByDescending(::seriesFreshnessScore).take(SERIES_SHELF_LIMIT)- }+ }.onStart { emit(emptyList()) }) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->DashboardContentShelves(favoriteChannels = favoriteChannels,@@ -100,10 +101,12 @@ class DashboardViewModel @Inject constructor(combine(contentShelves,- buildLiveContext(provider.id),- channelRepository.getChannels(provider.id).map { it.size },- movieRepository.getLibraryCount(provider.id),- seriesRepository.getLibraryCount(provider.id)+ buildLiveContext(provider.id).onStart {+ emit(DashboardLiveContext(lastVisitedCategory = null, shortcuts = emptyList()))+ },+ channelRepository.getChannels(provider.id).map { it.size }.onStart { emit(0) },+ movieRepository.getLibraryCount(provider.id).onStart { emit(0) },+ seriesRepository.getLibraryCount(provider.id).onStart { emit(0) }) { shelves, liveContext, liveChannelCount, movieCount, seriesCount ->DashboardSnapshot(shelves = shelves,@@ -112,7 +115,7 @@ class DashboardViewModel @Inject constructor(movieCount = movieCount,seriesCount = seriesCount)- }.combine(syncManager.syncState) { snapshot, syncState ->+ }.combine(syncManager.syncState.onStart { emit(SyncState.Idle) }) { snapshot, syncState ->DashboardUiState(provider = provider,favoriteChannels = snapshot.shelves.favoriteChannels,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 9cd2b6e7..f276ba05 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@@ -100,6 +100,7 @@ fun HomeScreen(multiViewViewModel: MultiViewViewModel = hiltViewModel()) {val uiState by viewModel.uiState.collectAsStateWithLifecycle()+ val isReorderMode = uiState.isChannelReorderModeval isProMode = uiState.liveTvChannelMode == LiveTvChannelMode.PROval isDenseMode = uiState.liveTvChannelMode != LiveTvChannelMode.COMFORTABLEval channelRowHeight = when (uiState.liveTvChannelMode) {@@ -146,7 +147,7 @@ fun HomeScreen(val hasOverlay = showPinDialog || showSplitManagerDialog || pendingSplitPlannerChannel != null ||uiState.showDialog || uiState.showDeleteGroupDialog ||uiState.showRenameGroupDialog || uiState.selectedCategoryForOptions != null ||- uiState.isChannelReorderMode+ isReorderModeBackHandler(enabled = hasOverlay) {when {@@ -162,7 +163,7 @@ fun HomeScreen(uiState.selectedCategoryForOptions != null -> viewModel.dismissCategoryOptions()uiState.showDialog -> viewModel.onDismissDialog()showSplitManagerDialog -> showSplitManagerDialog = false- uiState.isChannelReorderMode -> viewModel.exitChannelReorderMode()+ isReorderMode -> viewModel.exitChannelReorderMode()}}@@ -197,6 +198,9 @@ fun HomeScreen(viewModel.toggleCategoryLock(category)pendingLockToggleCategory = null}++ pendingUnlockCategory = null+ pendingUnlockChannel = null} else {pinError = context.getString(R.string.home_incorrect_pin)}@@ -208,14 +212,17 @@ fun HomeScreen(if (uiState.selectedCategoryForOptions != null) {val category = uiState.selectedCategoryForOptions!!+ val isCategoryLocked = (category.isAdult || category.isUserProtected) && uiState.parentalControlLevel == 1CategoryOptionsDialog(category = category,onDismissRequest = { viewModel.dismissCategoryOptions() },- onSetAsDefault = {- viewModel.setDefaultCategory(category)- viewModel.dismissCategoryOptions()+ onSetAsDefault = if (isCategoryLocked) null else {+ {+ viewModel.setDefaultCategory(category)+ viewModel.dismissCategoryOptions()+ }},- onRename = if (category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {+ onRename = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {{ viewModel.requestRenameGroup(category) }} else null,onToggleLock = {@@ -223,12 +230,12 @@ fun HomeScreen(pendingLockToggleCategory = categoryshowPinDialog = true},- onDelete = if (category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {+ onDelete = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {{viewModel.requestDeleteGroup(category)}} else null,- onReorderChannels = if (category.isVirtual && category.id != VirtualCategoryIds.RECENT) {+ onReorderChannels = if (!isCategoryLocked && category.isVirtual && category.id != VirtualCategoryIds.RECENT) {{ viewModel.enterChannelReorderMode(category) }} else null)@@ -244,7 +251,7 @@ fun HomeScreen(compactHeader = true,showScreenHeader = false) {- if (uiState.isChannelReorderMode) {+ if (isReorderMode) {ReorderTopBar(categoryName = uiState.reorderCategory?.name ?: uiState.selectedCategory?.name ?: "Channels",onSave = { viewModel.saveChannelReorder() },@@ -299,23 +306,60 @@ fun HomeScreen(val channelSearchFocusRequester = remember { FocusRequester() }val categoryFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }val channelFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }+ val visibleCategories = remember(uiState.categories, uiState.categorySearchQuery) {+ uiState.categories.filter {+ uiState.categorySearchQuery.isEmpty() ||+ it.name.contains(uiState.categorySearchQuery, ignoreCase = true)+ }+ }var lastFocusedCategoryId by rememberSaveable { mutableStateOf<Long?>(null) }var lastFocusedChannelId by rememberSaveable { mutableStateOf<Long?>(null) }var preferredRestoreTarget by rememberSaveable { mutableStateOf(FocusRestoreTarget.CHANNEL.name) }var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }var shouldRestoreChannelFocus by remember { mutableStateOf(false) }+ val visibleCategoryIds = remember(visibleCategories) {+ visibleCategories.mapTo(mutableSetOf()) { it.id }+ }+ val displayedCategory = uiState.selectedCategory?.takeIf { it.id in visibleCategoryIds }+ ?: visibleCategories.firstOrNull()++ LaunchedEffect(uiState.categories) {+ val validIds = uiState.categories.mapTo(mutableSetOf()) { it.id }+ categoryFocusRequesters.keys.retainAll(validIds)+ }++ LaunchedEffect(uiState.filteredChannels) {+ val validIds = uiState.filteredChannels.mapTo(mutableSetOf()) { it.id }+ channelFocusRequesters.keys.retainAll(validIds)+ }++ LaunchedEffect(uiState.categorySearchQuery, displayedCategory?.id, isReorderMode) {+ if (isReorderMode) return@LaunchedEffect+ val selectedCategory = uiState.selectedCategory ?: return@LaunchedEffect+ if (displayedCategory?.id == selectedCategory.id) return@LaunchedEffect+ displayedCategory?.let(viewModel::selectCategory)+ }+LaunchedEffect(uiState.showDialog,showPinDialog,uiState.showDeleteGroupDialog,- uiState.selectedCategoryForOptions+ uiState.selectedCategoryForOptions,+ uiState.showRenameGroupDialog,+ showSplitManagerDialog,+ pendingSplitPlannerChannel,+ isReorderMode) {val modalClosed =!uiState.showDialog &&!showPinDialog &&!uiState.showDeleteGroupDialog &&- uiState.selectedCategoryForOptions == null+ !uiState.showRenameGroupDialog &&+ !showSplitManagerDialog &&+ pendingSplitPlannerChannel == null &&+ uiState.selectedCategoryForOptions == null &&+ !isReorderModeif (!modalClosed) return@LaunchedEffect@@ -423,10 +467,15 @@ fun HomeScreen()SearchInput(value = uiState.categorySearchQuery,- onValueChange = { viewModel.updateCategorySearchQuery(it) },+ onValueChange = {+ if (!isReorderMode) {+ viewModel.updateCategorySearchQuery(it)+ }+ },placeholder = stringResource(R.string.home_search_categories),focusRequester = categorySearchFocusRequester,- modifier = Modifier.padding(bottom = 10.dp)+ modifier = Modifier.padding(bottom = 10.dp),+ enabled = !isReorderMode)}@@ -492,10 +541,7 @@ fun HomeScreen(}items(- items = uiState.categories.filter {- uiState.categorySearchQuery.isEmpty() ||- it.name.contains(uiState.categorySearchQuery, ignoreCase = true)- },+ items = visibleCategories,key = { it.id }) { category ->val isLocked = (category.isAdult || category.isUserProtected) && uiState.parentalControlLevel == 1@@ -507,6 +553,7 @@ fun HomeScreen(isLocked = isLocked,focusRequester = categoryFocusRequester,onClick = {+ if (isReorderMode) return@CategoryItemif (isLocked) {pendingUnlockCategory = categoryshowPinDialog = true@@ -515,6 +562,7 @@ fun HomeScreen(}},onLongClick = {+ if (isReorderMode || isLocked) return@CategoryItempreferredRestoreTarget = FocusRestoreTarget.CATEGORY.nameviewModel.showCategoryOptions(category)},@@ -557,7 +605,7 @@ fun HomeScreen(verticalArrangement = Arrangement.spacedBy(if (isDenseMode) 2.dp else 4.dp)) {Text(- text = uiState.selectedCategory?.name ?: stringResource(R.string.home_all_channels),+ text = displayedCategory?.name ?: stringResource(R.string.home_all_channels),style = if (isDenseMode) MaterialTheme.typography.titleMedium else MaterialTheme.typography.titleLarge,color = OnBackground)@@ -596,11 +644,16 @@ fun HomeScreen() {SearchInput(value = uiState.channelSearchQuery,- onValueChange = { viewModel.updateChannelSearchQuery(it) },+ onValueChange = {+ if (!isReorderMode) {+ viewModel.updateChannelSearchQuery(it)+ }+ },placeholder = stringResource(R.string.home_search_channels),onSearch = { focusManager.clearFocus() },focusRequester = channelSearchFocusRequester,- modifier = Modifier.width(if (isProMode) 270.dp else if (isDenseMode) 300.dp else 340.dp)+ modifier = Modifier.width(if (isProMode) 270.dp else if (isDenseMode) 300.dp else 340.dp),+ enabled = !isReorderMode)if (hasSplitChannels) {StatusPill(@@ -694,8 +747,8 @@ fun HomeScreen(var draggingChannel by remember { mutableStateOf<Channel?>(null) }- LaunchedEffect(uiState.isChannelReorderMode) {- if (!uiState.isChannelReorderMode) {+ LaunchedEffect(isReorderMode) {+ if (!isReorderMode) {draggingChannel = null}}@@ -758,7 +811,7 @@ fun HomeScreen(isDragging = isDraggingThis,rowHeight = channelRowHeight,onClick = {- if (uiState.isChannelReorderMode) {+ if (isReorderMode) {draggingChannel = if (isDraggingThis) null else channel} else if (ignoreNextClick) {ignoreNextClick = false@@ -779,7 +832,7 @@ fun HomeScreen(}},onLongClick = {- if (!uiState.isChannelReorderMode) {+ if (!isReorderMode) {ignoreNextClick = truepreferredRestoreTarget = FocusRestoreTarget.CHANNEL.nameviewModel.onShowDialog(channel)diff --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 0ec1dec7..e9073446 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@@ -5,6 +5,7 @@ import androidx.lifecycle.viewModelScopeimport com.streamvault.app.di.AuxiliaryPlayerEngineimport com.streamvault.app.ui.model.LiveTvChannelModeimport com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.sync.SyncManagerimport com.streamvault.domain.manager.ParentalControlManagerimport com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channel@@ -14,6 +15,7 @@ import com.streamvault.domain.model.Programimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.SyncStateimport com.streamvault.domain.model.VirtualCategoryIdsimport com.streamvault.domain.repository.CategoryRepositoryimport com.streamvault.domain.repository.ChannelRepository@@ -26,6 +28,7 @@ import com.streamvault.player.PlaybackStateimport com.streamvault.player.PlayerEngineimport dagger.hilt.android.lifecycle.HiltViewModelimport com.streamvault.app.R+import java.util.concurrent.CancellationExceptionimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.FlowPreviewimport kotlinx.coroutines.Job@@ -48,6 +51,7 @@ class HomeViewModel @Inject constructor(private val playbackHistoryRepository: PlaybackHistoryRepository,private val getCustomCategories: GetCustomCategories,private val parentalControlManager: ParentalControlManager,+ private val syncManager: SyncManager,@AuxiliaryPlayerEngineprivate val playerEngineProvider: InjectProvider<PlayerEngine>) : ViewModel() {@@ -100,7 +104,13 @@ class HomeViewModel @Inject constructor(}}- _uiState.update { it.copy(filteredChannels = markedChannels, isLoading = false) }+ _uiState.update { state ->+ if (state.isChannelReorderMode) {+ state+ } else {+ state.copy(filteredChannels = markedChannels)+ }+ }val previewChannelId = _uiState.value.previewChannelIdif (previewChannelId != null && markedChannels.none { it.id == previewChannelId }) {clearPreview()@@ -153,6 +163,22 @@ class HomeViewModel @Inject constructor(}}}++ viewModelScope.launch {+ syncManager.syncState.collectLatest { syncState ->+ val isSyncing = syncState is SyncState.Syncing+ _uiState.update { state ->+ state.copy(+ isSyncing = isSyncing,+ isLoading = when {+ state.hasChannels -> false+ isSyncing && state.selectedCategory != null -> true+ else -> state.isLoading && isSyncing+ }+ )+ }+ }+ }}private fun loadAllProviders() {@@ -256,7 +282,13 @@ class HomeViewModel @Inject constructor(if (_uiState.value.selectedCategory?.id == category.id) returnparentalControlManager.clearUnlockedCategories(_uiState.value.provider?.id)clearPreview()- _uiState.update { it.copy(selectedCategory = category, isLoading = true) }+ _uiState.update {+ it.copy(+ selectedCategory = category,+ isLoading = true,+ errorMessage = null+ )+ }_preferredInitialCategoryId.value = nullif (category.id != VirtualCategoryIds.RECENT) {val providerId = _uiState.value.provider?.id@@ -290,50 +322,65 @@ class HomeViewModel @Inject constructor(loadChannelsJob?.cancel()loadChannelsJob = viewModelScope.launch {try {- val queryFlow = _uiState.map { it.channelSearchQuery }- .debounce(150)- .distinctUntilChanged()-- val channelsFlow = if (category.isVirtual) {- val orderedFlow = if (category.id == VirtualCategoryIds.RECENT) {- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)- .map { it.toRecentLiveContentIds() }- .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }- } else if (category.id == VirtualCategoryIds.FAVORITES) {- favoriteRepository.getFavorites(ContentType.LIVE)- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }- .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }- } else {- val groupId = -category.id- favoriteRepository.getFavoritesByGroup(groupId)- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }- .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }+ _uiState.update {+ it.copy(+ isLoading = true,+ errorMessage = null+ )}- combine(orderedFlow, queryFlow) { channels, query ->- if (query.isBlank()) {- channels+ val queryFlow = _uiState.map { it.channelSearchQuery }+ .debounce(150)+ .distinctUntilChanged()++ val channelsFlow = if (category.isVirtual) {+ val orderedFlow = if (category.id == VirtualCategoryIds.RECENT) {+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)+ .map { it.toRecentLiveContentIds() }+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }+ } else if (category.id == VirtualCategoryIds.FAVORITES) {+ favoriteRepository.getFavorites(ContentType.LIVE)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }} else {- channels.filter { it.name.contains(query, ignoreCase = true) }+ val groupId = -category.id+ favoriteRepository.getFavoritesByGroup(groupId)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }}- }- } else {- queryFlow.flatMapLatest { query ->- if (query.isBlank()) {- channelRepository.getChannelsByCategory(providerId, category.id)- } else {- channelRepository.searchChannelsByCategory(providerId, category.id, query)++ combine(orderedFlow, queryFlow) { channels, query ->+ if (query.isBlank()) {+ channels+ } else {+ channels.filter { it.name.contains(query, ignoreCase = true) }+ }+ }+ } else {+ queryFlow.flatMapLatest { query ->+ if (query.isBlank()) {+ channelRepository.getChannelsByCategory(providerId, category.id)+ } else {+ channelRepository.searchChannelsByCategory(providerId, category.id, query)+ }}}- }- channelsFlow.collect { channels ->- val numberedChannels = channels.mapIndexed { index, channel ->- channel.copy(number = index + 1)+ channelsFlow.collect { channels ->+ val numberedChannels = channels.mapIndexed { index, channel ->+ channel.copy(number = index + 1)+ }+ _localChannels.value = numberedChannels+ _uiState.update {+ it.copy(+ hasChannels = numberedChannels.isNotEmpty(),+ isLoading = numberedChannels.isEmpty() && it.isSyncing,+ errorMessage = null+ )+ }}- _uiState.update { it.copy(hasChannels = numberedChannels.isNotEmpty(), isLoading = false, errorMessage = null) }- _localChannels.value = numberedChannels- }+ } catch (e: CancellationException) {+ throw e} catch (e: Exception) {_uiState.update {it.copy(@@ -346,10 +393,12 @@ class HomeViewModel @Inject constructor(}fun updateCategorySearchQuery(query: String) {+ if (_uiState.value.isChannelReorderMode) return_uiState.update { it.copy(categorySearchQuery = query) }}fun updateChannelSearchQuery(query: String) {+ if (_uiState.value.isChannelReorderMode) return_uiState.update { it.copy(channelSearchQuery = query) }}@@ -886,6 +935,7 @@ data class HomeUiState(val filteredChannels: List<Channel> = emptyList(),val hasChannels: Boolean = false,val isLoading: Boolean = true,+ val isSyncing: Boolean = false,val categorySearchQuery: String = "",val channelSearchQuery: String = "",val showDialog: Boolean = false,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 7ee9ced4..1e632ff6 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@@ -85,7 +85,6 @@ fun MoviesScreen(var showPinDialog by remember { mutableStateOf(false) }var pinError by remember { mutableStateOf<String?>(null) }var pendingMovie by remember { mutableStateOf<Movie?>(null) }- var selectedLibraryLens by rememberSaveable { mutableStateOf(MovieLibraryLens.FAVORITES.name) }var selectedFacet by rememberSaveable { mutableStateOf(MovieLibraryFacet.ALL.name) }var selectedSort by rememberSaveable { mutableStateOf(MovieLibrarySort.LIBRARY.name) }val scope = rememberCoroutineScope()@@ -178,7 +177,6 @@ fun MoviesScreen(onSelectedFacetChange = { selectedFacet = it },selectedSort = selectedSort,onSelectedSortChange = { selectedSort = it },- onNavigate = onNavigate,onMovieClick = onMovieClick,onProtectedMovieClick = { movie ->pendingMovie = movie@@ -187,598 +185,24 @@ fun MoviesScreen(onShowDialog = viewModel::onShowDialog,onSelectCategory = viewModel::selectCategory,onSelectFullLibraryBrowse = viewModel::selectFullLibraryBrowse,+ onOpenContinueWatching = {+ selectedFacet = MovieLibraryFacet.RESUME.name+ selectedSort = MovieLibrarySort.LIBRARY.name+ viewModel.selectFullLibraryBrowse()+ },+ onOpenTopRated = {+ selectedFacet = MovieLibraryFacet.TOP_RATED.name+ selectedSort = MovieLibrarySort.RATING.name+ viewModel.selectFullLibraryBrowse()+ },+ onOpenFresh = {+ selectedFacet = MovieLibraryFacet.ALL.name+ selectedSort = MovieLibrarySort.RELEASE.name+ viewModel.selectFullLibraryBrowse()+ },onLoadMore = viewModel::loadMoreSelectedCategory,onDismissReorder = viewModel::exitCategoryReorderMode)- return@AppScreenScaffold- Row(modifier = Modifier.fillMaxSize()) {- val focusManager = LocalFocusManager.current- val categorySearchFocusRequester = remember { FocusRequester() }- val categoryFocusRequesters = remember { mutableMapOf<String, FocusRequester>() }- var lastFocusedCategoryName by rememberSaveable { mutableStateOf<String?>(null) }- var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }- var preferCategoryRestore by rememberSaveable { mutableStateOf(false) }- LaunchedEffect(- uiState.selectedCategoryForOptions,- uiState.showRenameGroupDialog,- uiState.showDeleteGroupDialog- ) {- val modalClosed =- uiState.selectedCategoryForOptions == null &&- !uiState.showRenameGroupDialog &&- !uiState.showDeleteGroupDialog- if (modalClosed && preferCategoryRestore && lastFocusedCategoryName != null) {- shouldRestoreCategoryFocus = true- preferCategoryRestore = false- }- }-- LaunchedEffect(shouldRestoreCategoryFocus, uiState.categoryNames) {- if (!shouldRestoreCategoryFocus) return@LaunchedEffect- kotlinx.coroutines.delay(80)- val categoryName = lastFocusedCategoryName- if (categoryName != null) {- runCatching {- categoryFocusRequesters[categoryName]?.requestFocus()- }- }- shouldRestoreCategoryFocus = false- }-- Column(- modifier = Modifier- .width(188.dp)- .fillMaxHeight()- .background(SurfaceElevated.copy(alpha = 0.72f), RoundedCornerShape(20.dp))- .padding(top = 8.dp)- ) {- // Sticky Header- Column(modifier = Modifier.padding(horizontal = 12.dp)) {- Text(- text = stringResource(R.string.movies_categories_title),- style = MaterialTheme.typography.titleSmall,- color = Primary,- modifier = Modifier.padding(vertical = 8.dp)- )-- SearchInput(- value = uiState.searchQuery,- onValueChange = { viewModel.setSearchQuery(it) },- placeholder = stringResource(R.string.movies_search_placeholder),- focusRequester = categorySearchFocusRequester,- modifier = Modifier.padding(bottom = 8.dp)- )- }-- LazyColumn(- modifier = Modifier.fillMaxWidth(),- contentPadding = PaddingValues(bottom = 8.dp)- ) {- item {- val isAllSelected = uiState.selectedCategory == null || uiState.selectedCategory == uiState.fullLibraryCategoryName- Surface(- onClick = { viewModel.selectCategory(null) },- shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isAllSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.25f)- ),- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 2.dp)- .onPreviewKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {- categorySearchFocusRequester.requestFocus()- true- } else false- } else false- }- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.movies_all_categories),- style = MaterialTheme.typography.bodyMedium,- color = if (isAllSelected) Primary else OnSurface,- modifier = Modifier.weight(1f)- )- Text(- text = "${uiState.libraryCount}",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- }- }- items(uiState.categoryNames.size) { index ->- val categoryName = uiState.categoryNames[index]- val isSelected = uiState.selectedCategory == categoryName- val count = uiState.categoryCounts[categoryName] ?: 0- Surface(- onClick = { viewModel.selectCategory(categoryName) },- onLongClick = {- preferCategoryRestore = true- viewModel.showCategoryOptions(categoryName)- },- shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.25f)- ),- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 2.dp)- .focusRequester(categoryFocusRequesters.getOrPut(categoryName) { FocusRequester() })- .onFocusChanged { focusState ->- if (focusState.isFocused) {- lastFocusedCategoryName = categoryName- }- }- .onPreviewKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {- categorySearchFocusRequester.requestFocus()- true- } else false- } else false- }- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = categoryName,- style = MaterialTheme.typography.bodyMedium,- color = if (isSelected) Primary else OnSurface,- maxLines = 1,- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,- modifier = Modifier.weight(1f)- )- Text(- text = "$count",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- }- }- }- }-- val savedShortcuts = remember(- uiState.favoriteCategoryName,- uiState.categories,- uiState.moviesByCategory- ) {- buildList {- val favoriteCount = uiState.categoryCounts[uiState.favoriteCategoryName] ?: 0- if (favoriteCount > 0) {- add(- SavedCategoryShortcut(- name = uiState.favoriteCategoryName,- count = favoriteCount- )- )- }- uiState.categories- .asSequence()- .filterNot { it.name == uiState.favoriteCategoryName }- .map { category ->- SavedCategoryShortcut(- name = category.name,- count = uiState.categoryCounts[category.name] ?: 0- )- }- .filter { it.count > 0 }- .sortedByDescending { it.count }- .forEach(::add)- }- }- val selectedSavedCategory = remember(- uiState.selectedCategory,- uiState.favoriteCategoryName,- uiState.categories- ) {- when (uiState.selectedCategory) {- null -> null- uiState.favoriteCategoryName -> com.streamvault.domain.model.Category(- id = -999L,- name = uiState.favoriteCategoryName,- type = com.streamvault.domain.model.ContentType.MOVIE,- isVirtual = true- )- else -> uiState.categories.firstOrNull { it.name == uiState.selectedCategory }- }- }-- // Main content- if (uiState.selectedCategory == null) {- val activeLibraryLens = remember(selectedLibraryLens, uiState.libraryLensRows) {- MovieLibraryLens.entries.firstOrNull { it.name == selectedLibraryLens && uiState.libraryLensRows.containsKey(it) }- ?: uiState.libraryLensRows.keys.firstOrNull()- }- // Netflix-style rows (All categories view)- LazyColumn(- modifier = Modifier.fillMaxSize().weight(1f),- contentPadding = PaddingValues(- start = LocalSpacing.current.safeHoriz,- end = LocalSpacing.current.safeHoriz,- bottom = LocalSpacing.current.safeBottom- )- ) {- item {- BrowseSearchLaunchCard(- title = stringResource(R.string.movies_search_launch_title),- subtitle = stringResource(R.string.movies_search_launch_subtitle),- onClick = { onNavigate(Routes.SEARCH) },- modifier = Modifier.padding(vertical = LocalSpacing.current.md)- )- }-- item(key = "saved_shortcuts") {- SavedCategoryShortcutsRow(- title = stringResource(R.string.library_saved_title),- subtitle = stringResource(R.string.library_saved_subtitle),- emptyHint = stringResource(R.string.movies_saved_empty_hint),- shortcuts = savedShortcuts,- managementHint = stringResource(R.string.library_saved_manage_hint),- primaryShortcutLabel = stringResource(R.string.library_browse_all),- isPrimaryShortcutSelected = uiState.selectedCategory == null,- onPrimaryShortcutClick = { viewModel.selectCategory(null) },- selectedShortcutName = uiState.selectedCategory,- onShortcutLongClick = viewModel::showCategoryOptions,- onShortcutClick = viewModel::selectCategory- )- }-- if (activeLibraryLens != null) {- item(key = "library_lens_chips") {- SelectionChipRow(- title = stringResource(R.string.library_lens_title),- subtitle = stringResource(R.string.movies_library_lens_subtitle),- chips = uiState.libraryLensRows.keys.map { lens ->- SelectionChip(- key = lens.name,- label = movieLibraryLensLabel(lens),- supportingText = stringResource(- R.string.library_saved_items_count,- uiState.libraryLensRows[lens]?.size ?: 0- )- )- },- selectedKey = activeLibraryLens.name,- onChipSelected = { selectedLibraryLens = it },- contentPadding = PaddingValues(horizontal = 0.dp)- )- }-- item(key = "library_lens_row") {- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- Surface(- onClick = viewModel::selectFullLibraryBrowse,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.06f),- focusedContainerColor = Primary- ),- modifier = Modifier.padding(horizontal = 16.dp)- ) {- Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)) {- Text(- text = stringResource(R.string.library_full_browse_title_movies),- style = MaterialTheme.typography.titleSmall,- color = Color.White- )- Spacer(Modifier.height(4.dp))- Text(- text = stringResource(R.string.library_full_browse_subtitle, uiState.libraryCount),- style = MaterialTheme.typography.bodySmall,- color = Color.White.copy(alpha = 0.8f)- )- }- }-- CategoryRow(- title = movieLibraryLensLabel(activeLibraryLens),- items = uiState.libraryLensRows[activeLibraryLens].orEmpty(),- onSeeAll = if (activeLibraryLens == MovieLibraryLens.FAVORITES) {- { viewModel.selectCategory(uiState.favoriteCategoryName) }- } else {- null- },- keySelector = { it.id }- ) { movie ->- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1- MovieCard(- movie = movie,- isLocked = isLocked,- onClick = {- if (isLocked) {- pendingMovie = movie- showPinDialog = true- } else {- onMovieClick(movie)- }- },- onLongClick = { viewModel.onShowDialog(movie) }- )- }- }- }- }-- // Continue Watching row (shown first, only if non-empty)- item(key = "continue_watching") {- ContinueWatchingRow(- items = uiState.continueWatching,- onItemClick = { history -> onMovieClick(- com.streamvault.domain.model.Movie(- id = history.contentId,- name = history.title,- posterUrl = history.posterUrl,- streamUrl = history.streamUrl,- providerId = history.providerId- )- )}- )- }- items(- items = uiState.moviesByCategory.entries.toList(),- key = { it.key }- ) { (categoryName, movies) ->- CategoryRow(- title = categoryName,- items = movies,- onSeeAll = { viewModel.selectCategory(categoryName) },- keySelector = { it.id }- ) { movie ->- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1- MovieCard(- movie = movie,- isLocked = isLocked,- onClick = {- if (isLocked) {- pendingMovie = movie- showPinDialog = true- } else {- onMovieClick(movie)- }- },- onLongClick = {- viewModel.onShowDialog(movie)- }- )- }- }- }- } else {- // Filtered grid for selected category- val baseMovies = if (uiState.searchQuery.isBlank()) {- uiState.selectedCategoryItems- } else {- uiState.moviesByCategory[uiState.selectedCategory] ?: emptyList()- }- val activeMovies = if (uiState.isReorderMode) uiState.filteredMovies else baseMovies- val resumeMovieIds = remember(uiState.continueWatching) {- uiState.continueWatching.map { it.contentId }.toSet()- }- val activeFacet = remember(selectedFacet) {- MovieLibraryFacet.entries.firstOrNull { it.name == selectedFacet } ?: MovieLibraryFacet.ALL- }- val activeSort = remember(selectedSort) {- MovieLibrarySort.entries.firstOrNull { it.name == selectedSort } ?: MovieLibrarySort.LIBRARY- }- val filteredGridMovies = remember(activeMovies, activeFacet, activeSort, resumeMovieIds, uiState.isReorderMode) {- if (uiState.isReorderMode) {- activeMovies- } else {- applyMovieFacetAndSort(- items = activeMovies,- facet = activeFacet,- sort = activeSort,- resumeMovieIds = resumeMovieIds- )- }- }- val showSelectedCategoryControls = !uiState.isReorderMode &&- (selectedSavedCategory != null || activeMovies.size > 8)-- var draggingMovie by remember { mutableStateOf<Movie?>(null) }-- LaunchedEffect(uiState.isReorderMode) {- if (!uiState.isReorderMode) {- draggingMovie = null- }- }-- Column(- modifier = Modifier- .fillMaxSize()- .weight(1f)- ) {- if (selectedSavedCategory != null) {- SavedCategoryShortcutsRow(- title = stringResource(R.string.library_saved_title),- subtitle = stringResource(R.string.library_saved_subtitle),- emptyHint = stringResource(R.string.movies_saved_empty_hint),- shortcuts = savedShortcuts,- managementHint = stringResource(R.string.library_saved_manage_hint),- primaryShortcutLabel = stringResource(R.string.library_browse_all),- isPrimaryShortcutSelected = uiState.selectedCategory == null,- onPrimaryShortcutClick = { viewModel.selectCategory(null) },- selectedShortcutName = uiState.selectedCategory,- onShortcutLongClick = viewModel::showCategoryOptions,- onShortcutClick = viewModel::selectCategory- )-- SavedCategoryContextCard(- categoryName = selectedSavedCategory.name,- itemCount = uiState.categoryCounts[selectedSavedCategory.name] ?: filteredGridMovies.size,- onManageClick = { viewModel.showCategoryOptions(selectedSavedCategory.name) },- onBrowseAllClick = { viewModel.selectCategory(null) },- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)- )- }-- if (showSelectedCategoryControls) {- SelectionChipRow(- title = stringResource(R.string.library_filter_title),- chips = buildMovieFacetChips(- items = activeMovies,- resumeMovieIds = resumeMovieIds- ),- selectedKey = activeFacet.name,- onChipSelected = { selectedFacet = it },- modifier = Modifier.padding(horizontal = 16.dp),- contentPadding = PaddingValues(horizontal = 0.dp)- )-- SelectionChipRow(- title = stringResource(R.string.library_sort_title),- chips = MovieLibrarySort.entries.map { sort ->- SelectionChip(- key = sort.name,- label = when (sort) {- MovieLibrarySort.LIBRARY -> stringResource(R.string.library_sort_library)- MovieLibrarySort.TITLE -> stringResource(R.string.library_sort_az)- MovieLibrarySort.RELEASE -> stringResource(R.string.library_sort_release)- MovieLibrarySort.RATING -> stringResource(R.string.library_sort_rating)- }- )- },- selectedKey = activeSort.name,- onChipSelected = { selectedSort = it },- modifier = Modifier.padding(horizontal = 16.dp),- contentPadding = PaddingValues(horizontal = 0.dp)- )- }-- LazyVerticalGrid(- columns = GridCells.Adaptive(minSize = 138.dp),- modifier = Modifier- .fillMaxSize()- .onPreviewKeyEvent { event ->- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {- if (draggingMovie != null) {- draggingMovie = null- true- } else {- viewModel.exitCategoryReorderMode()- true- }- } else false- } else false- },- contentPadding = PaddingValues(12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- item(span = { GridItemSpan(maxLineSpan) }) {- Column(modifier = Modifier.padding(bottom = 16.dp)) {- Text(- text = when (uiState.selectedCategory) {- uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_movies)- else -> uiState.selectedCategory ?: ""- },- style = MaterialTheme.typography.titleLarge,- color = Primary,- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold- )- if (!uiState.isReorderMode && uiState.selectedCategoryTotalCount > 0) {- Spacer(Modifier.height(6.dp))- Text(- text = stringResource(- R.string.library_loaded_results,- uiState.selectedCategoryLoadedCount,- uiState.selectedCategoryTotalCount- ),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }-- if (filteredGridMovies.isEmpty()) {- item(span = { GridItemSpan(maxLineSpan) }) {- Text(- text = stringResource(R.string.library_filter_empty),- style = MaterialTheme.typography.bodyLarge,- color = OnSurfaceDim,- modifier = Modifier.padding(bottom = 12.dp)- )- }- }-- gridItems(- items = filteredGridMovies,- key = { it.id }- ) { movie ->- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1- val isDraggingThis = draggingMovie == movie-- MovieCard(- movie = movie,- isLocked = isLocked,- isReorderMode = uiState.isReorderMode,- isDragging = isDraggingThis,- onClick = {- if (uiState.isReorderMode) {- draggingMovie = if (isDraggingThis) null else movie- } else if (isLocked) {- pendingMovie = movie- showPinDialog = true- } else {- onMovieClick(movie)- }- },- onLongClick = {- if (!uiState.isReorderMode) {- viewModel.onShowDialog(movie)- }- },- modifier = Modifier.onPreviewKeyEvent { event ->- if (uiState.isReorderMode && isDraggingThis && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_LEFT,- android.view.KeyEvent.KEYCODE_DPAD_UP -> {- viewModel.moveItemUp(movie)- true- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT,- android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {- viewModel.moveItemDown(movie)- true- }- else -> false- }- } else false- }- )- }-- if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {- item(span = { GridItemSpan(maxLineSpan) }) {- LoadMoreCard(- label = stringResource(- R.string.library_load_more,- uiState.selectedCategoryLoadedCount,- uiState.selectedCategoryTotalCount- ),- onClick = viewModel::loadMoreSelectedCategory,- modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)- )- }- }- }- }- }- }}}SnackbarHost(@@ -858,12 +282,14 @@ private fun MoviesVodContent(onSelectedFacetChange: (String) -> Unit,selectedSort: String,onSelectedSortChange: (String) -> Unit,- onNavigate: (String) -> Unit,onMovieClick: (Movie) -> Unit,onProtectedMovieClick: (Movie) -> Unit,onShowDialog: (Movie) -> Unit,onSelectCategory: (String?) -> Unit,onSelectFullLibraryBrowse: () -> Unit,+ onOpenContinueWatching: () -> Unit,+ onOpenTopRated: () -> Unit,+ onOpenFresh: () -> Unit,onLoadMore: () -> Unit,onDismissReorder: () -> Unit) {@@ -949,7 +375,7 @@ private fun MoviesVodContent(key = "resume",label = stringResource(R.string.library_lens_continue),detail = "${continueWatching.size} items",- onClick = { }+ onClick = onOpenContinueWatching))}@@ -959,7 +385,7 @@ private fun MoviesVodContent(key = MovieLibraryLens.TOP_RATED.name,label = stringResource(R.string.library_lens_top_rated),detail = "${topRatedMovies.size} picks",- onClick = { }+ onClick = onOpenTopRated))}@@ -969,7 +395,7 @@ private fun MoviesVodContent(key = MovieLibraryLens.FRESH.name,label = stringResource(R.string.library_lens_fresh_movies),detail = "${freshMovies.size} picks",- onClick = { }+ onClick = onOpenFresh))}@@ -1150,7 +576,7 @@ private fun MoviesVodContent(key = uiState.selectedCategory ?: "",label = uiState.selectedCategory ?: stringResource(R.string.nav_movies),detail = "${uiState.selectedCategoryTotalCount} titles",- onClick = { }+ onClick = { showCategoryPicker = true }))}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 1e558810..0d94a8d3 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@@ -6,7 +6,9 @@ import androidx.activity.compose.BackHandlerimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.compose.LifecycleEventEffectimport androidx.compose.runtime.*import androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.ui.Alignment@@ -27,7 +29,6 @@ import androidx.compose.ui.text.font.FontWeightimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale-import androidx.hilt.navigation.compose.hiltViewModelimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.foundation.focusable@@ -61,8 +62,6 @@ import androidx.compose.material3.CircularProgressIndicatorimport com.streamvault.app.ui.components.dialogs.ProgramHistoryDialogimport androidx.compose.ui.res.stringResourceimport androidx.lifecycle.Lifecycle-import androidx.lifecycle.LifecycleEventObserver-import androidx.lifecycle.compose.LocalLifecycleOwnerimport com.streamvault.app.Rimport com.streamvault.app.MainActivityimport com.streamvault.app.ui.screens.player.overlay.ChannelInfoOverlay@@ -157,13 +156,19 @@ fun PlayerScreen(val categoryListFocusRequester = remember { FocusRequester() }val epgFocusRequester = remember { FocusRequester() }val playButtonFocusRequester = remember { FocusRequester() }+ val quickActionsFocusRequester = remember { FocusRequester() }val channelInfoFocusRequester = remember { FocusRequester() } // NEWvar lastFocusedChannelListItemId by rememberSaveable { mutableStateOf<Long?>(null) }var lastFocusedEpgProgramToken by rememberSaveable { mutableStateOf<Long?>(null) }val layoutDirection = LocalLayoutDirection.currentval isRtl = layoutDirection == LayoutDirection.Rtl- val lifecycleOwner = LocalLifecycleOwner.currentval currentPictureInPictureMode by rememberUpdatedState(isInPictureInPictureMode)+ val enterPictureInPicture = remember(mainActivity) {+ {+ mainActivity?.enterPlayerPictureInPictureModeFromPlayer()+ Unit+ }+ }LaunchedEffect(Unit) {focusRequester.requestFocus()@@ -187,30 +192,28 @@ fun PlayerScreen(}}- DisposableEffect(lifecycleOwner, mainActivity) {- val observer = LifecycleEventObserver { _, event ->- when (event) {- Lifecycle.Event.ON_START -> viewModel.onAppForegrounded()- Lifecycle.Event.ON_STOP -> {- if (currentPictureInPictureMode) {- viewModel.closeOverlays()- } else {- viewModel.onAppBackgrounded()- }- }- else -> Unit- }+ LifecycleEventEffect(Lifecycle.Event.ON_START) {+ viewModel.onAppForegrounded()+ }++ LifecycleEventEffect(Lifecycle.Event.ON_STOP) {+ if (currentPictureInPictureMode) {+ viewModel.closeOverlays()+ } else {+ viewModel.onAppBackgrounded()}- lifecycleOwner.lifecycle.addObserver(observer)+ }++ DisposableEffect(mainActivity) {onDispose {- lifecycleOwner.lifecycle.removeObserver(observer)mainActivity?.clearPlayerPictureInPictureState()viewModel.onPlayerScreenDisposed()}}// Consolidated focus management for all overlays- val anyOverlayVisible = showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showTrackSelection != null || showProgramHistory || showSplitDialog || showDiagnostics+ val liveOverlayVisible = contentType == "LIVE" && (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay)+ val anyOverlayVisible = liveOverlayVisible || showTrackSelection != null || showProgramHistory || showSplitDialog || showDiagnosticsLaunchedEffect(anyOverlayVisible) {if (anyOverlayVisible) {@@ -284,7 +287,13 @@ fun PlayerScreen(LaunchedEffect(showControls) {if (showControls) {delay(100)- try { playButtonFocusRequester.requestFocus() } catch (_: Exception) {}+ try {+ if (contentType == "LIVE") {+ quickActionsFocusRequester.requestFocus()+ } else {+ playButtonFocusRequester.requestFocus()+ }+ } catch (_: Exception) {}viewModel.hideControlsAfterDelay()} else {try { focusRequester.requestFocus() } catch (_: Exception) {}@@ -309,7 +318,7 @@ fun PlayerScreen(.focusRequester(focusRequester).focusProperties {// Only allow focus on the main background when no overlays are active- canFocus = !anyOverlayVisible+ canFocus = !anyOverlayVisible && !showControls}.focusable().onKeyEvent { event ->@@ -425,6 +434,10 @@ fun PlayerScreen(if (isPlaying) viewModel.pause() else viewModel.play()true}+ KeyEvent.KEYCODE_MUTE, KeyEvent.KEYCODE_VOLUME_MUTE -> {+ viewModel.toggleMute()+ true+ }KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {if (contentType == "LIVE") {viewModel.playNext()@@ -588,6 +601,7 @@ fun PlayerScreen(isMuted = isMuted,mediaTitle = mediaTitle,playButtonFocusRequester = playButtonFocusRequester,+ quickActionsFocusRequester = quickActionsFocusRequester,modifier = Modifier.fillMaxSize(),onClose = onBack,onTogglePlayPause = { if (isPlaying) viewModel.pause() else viewModel.play() },@@ -603,7 +617,10 @@ fun PlayerScreen(onOpenAudioTracks = { showTrackSelection = TrackType.AUDIO },onOpenVideoTracks = { showTrackSelection = TrackType.VIDEO },onOpenSplitScreen = { showSplitDialog = true },- onToggleMute = viewModel::toggleMute+ onEnterPictureInPicture = enterPictureInPicture,+ onToggleMute = viewModel::toggleMute,+ onSeekToPosition = viewModel::seekTo,+ onSetScrubbingMode = viewModel::setScrubbingMode)PlayerNumericInputOverlay(@@ -663,120 +680,122 @@ fun PlayerScreen()}- AnimatedVisibility(- visible = showChannelListOverlay,- enter = slideInHorizontally(initialOffsetX = { if (isRtl) it else -it }),- exit = slideOutHorizontally(targetOffsetX = { if (isRtl) it else -it }),- modifier = Modifier- .align(if (isRtl) Alignment.TopEnd else Alignment.TopStart)- .fillMaxHeight()- .width(350.dp)- .focusGroup()- ) {- ChannelListOverlay(- channels = currentChannelList,- recentChannels = recentChannels,- currentChannelId = currentChannel?.id ?: internalChannelId,- overlayFocusRequester = channelListFocusRequester,- preferredFocusedChannelId = lastFocusedChannelListItemId,- onFocusedChannelChange = { channelId -> lastFocusedChannelListItemId = channelId },- lastVisitedCategoryName = lastVisitedCategory?.name,- onOpenLastGroup = { viewModel.openLastVisitedCategory() },- onSelectChannel = { channelId -> viewModel.zapToChannel(channelId) },- onOpenCategories = { viewModel.openCategoryListOverlay() },- onDismiss = { viewModel.closeOverlays() },- onOverlayInteracted = viewModel::onLiveOverlayInteraction- )- }+ if (contentType == "LIVE") {+ AnimatedVisibility(+ visible = showChannelListOverlay,+ enter = slideInHorizontally(initialOffsetX = { if (isRtl) it else -it }),+ exit = slideOutHorizontally(targetOffsetX = { if (isRtl) it else -it }),+ modifier = Modifier+ .align(if (isRtl) Alignment.TopEnd else Alignment.TopStart)+ .fillMaxHeight()+ .width(350.dp)+ .focusGroup()+ ) {+ ChannelListOverlay(+ channels = currentChannelList,+ recentChannels = recentChannels,+ currentChannelId = currentChannel?.id ?: internalChannelId,+ overlayFocusRequester = channelListFocusRequester,+ preferredFocusedChannelId = lastFocusedChannelListItemId,+ onFocusedChannelChange = { channelId -> lastFocusedChannelListItemId = channelId },+ lastVisitedCategoryName = lastVisitedCategory?.name,+ onOpenLastGroup = { viewModel.openLastVisitedCategory() },+ onSelectChannel = { channelId -> viewModel.zapToChannel(channelId) },+ onOpenCategories = { viewModel.openCategoryListOverlay() },+ onDismiss = { viewModel.closeOverlays() },+ onOverlayInteracted = viewModel::onLiveOverlayInteraction+ )+ }- AnimatedVisibility(- visible = showCategoryListOverlay,- enter = slideInHorizontally(initialOffsetX = { if (isRtl) it else -it }),- exit = slideOutHorizontally(targetOffsetX = { if (isRtl) it else -it }),- modifier = Modifier- .align(if (isRtl) Alignment.TopEnd else Alignment.TopStart)- .fillMaxHeight()- .width(350.dp)- .focusGroup()- ) {- CategoryListOverlay(- categories = availableCategories,- currentCategoryId = activeCategoryId,- overlayFocusRequester = categoryListFocusRequester,- onSelectCategory = { category ->- viewModel.selectCategoryFromOverlay(category)- },- onDismiss = { viewModel.closeOverlays() },- onOverlayInteracted = viewModel::onLiveOverlayInteraction- )- }+ AnimatedVisibility(+ visible = showCategoryListOverlay,+ enter = slideInHorizontally(initialOffsetX = { if (isRtl) it else -it }),+ exit = slideOutHorizontally(targetOffsetX = { if (isRtl) it else -it }),+ modifier = Modifier+ .align(if (isRtl) Alignment.TopEnd else Alignment.TopStart)+ .fillMaxHeight()+ .width(350.dp)+ .focusGroup()+ ) {+ CategoryListOverlay(+ categories = availableCategories,+ currentCategoryId = activeCategoryId,+ overlayFocusRequester = categoryListFocusRequester,+ onSelectCategory = { category ->+ viewModel.selectCategoryFromOverlay(category)+ },+ onDismiss = { viewModel.closeOverlays() },+ onOverlayInteracted = viewModel::onLiveOverlayInteraction+ )+ }- AnimatedVisibility(- visible = showEpgOverlay,- enter = slideInHorizontally(initialOffsetX = { if (isRtl) -it else it }),- exit = slideOutHorizontally(targetOffsetX = { if (isRtl) -it else it }),- modifier = Modifier- .align(if (isRtl) Alignment.TopStart else Alignment.TopEnd)- .fillMaxHeight()- .width(400.dp)- .focusGroup()- ) {- EpgOverlay(- currentChannel = currentChannel,- displayChannelNumber = displayChannelNumber,- currentProgram = currentProgram,- nextProgram = nextProgram,- upcomingPrograms = upcomingPrograms,- overlayFocusRequester = epgFocusRequester,- preferredFocusedProgramToken = lastFocusedEpgProgramToken,- onFocusedProgramChange = { token -> lastFocusedEpgProgramToken = token },- onDismiss = { viewModel.closeOverlays() },- onPlayCatchUp = { program ->- viewModel.playCatchUp(program)- viewModel.closeOverlays()- },- onOverlayInteracted = viewModel::onLiveOverlayInteraction- )- }+ AnimatedVisibility(+ visible = showEpgOverlay,+ enter = slideInHorizontally(initialOffsetX = { if (isRtl) -it else it }),+ exit = slideOutHorizontally(targetOffsetX = { if (isRtl) -it else it }),+ modifier = Modifier+ .align(if (isRtl) Alignment.TopStart else Alignment.TopEnd)+ .fillMaxHeight()+ .width(400.dp)+ .focusGroup()+ ) {+ EpgOverlay(+ currentChannel = currentChannel,+ displayChannelNumber = displayChannelNumber,+ currentProgram = currentProgram,+ nextProgram = nextProgram,+ upcomingPrograms = upcomingPrograms,+ overlayFocusRequester = epgFocusRequester,+ preferredFocusedProgramToken = lastFocusedEpgProgramToken,+ onFocusedProgramChange = { token -> lastFocusedEpgProgramToken = token },+ onDismiss = { viewModel.closeOverlays() },+ onPlayCatchUp = { program ->+ viewModel.playCatchUp(program)+ viewModel.closeOverlays()+ },+ onOverlayInteracted = viewModel::onLiveOverlayInteraction+ )+ }- AnimatedVisibility(- visible = showChannelInfoOverlay,- enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),- exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(),- modifier = Modifier- .align(Alignment.BottomCenter)- .fillMaxWidth()- .focusGroup()- ) {- ChannelInfoOverlay(- currentChannel = currentChannel,- displayChannelNumber = displayChannelNumber,- currentProgram = currentProgram,- nextProgram = nextProgram,- focusRequester = channelInfoFocusRequester,- lastVisitedCategoryName = lastVisitedCategory?.name,- onDismiss = { viewModel.closeChannelInfoOverlay() },- onOverlayInteracted = viewModel::onLiveOverlayInteraction,- onOpenFullEpg = {- viewModel.closeChannelInfoOverlay()- viewModel.openEpgOverlay()- },- onOpenLastGroup = {- viewModel.closeChannelInfoOverlay()- viewModel.openLastVisitedCategory()- },- currentRecordingStatus = currentChannelRecording?.status,- onStartRecording = viewModel::startManualRecording,- onStopRecording = viewModel::stopCurrentRecording,- onRestartProgram = { viewModel.restartCurrentProgram() },- onToggleAspectRatio = { viewModel.toggleAspectRatio() },- onToggleDiagnostics = { viewModel.toggleDiagnostics() },- onTogglePlayPause = { if (isPlaying) viewModel.pause() else viewModel.play() },- isPlaying = isPlaying,- currentAspectRatio = aspectRatio.modeName,- isDiagnosticsEnabled = showDiagnostics,- onOpenSplitScreen = { showSplitDialog = true }- )+ AnimatedVisibility(+ visible = showChannelInfoOverlay,+ enter = slideInVertically(initialOffsetY = { it }) + fadeIn(),+ exit = slideOutVertically(targetOffsetY = { it }) + fadeOut(),+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .fillMaxWidth()+ .focusGroup()+ ) {+ ChannelInfoOverlay(+ currentChannel = currentChannel,+ displayChannelNumber = displayChannelNumber,+ currentProgram = currentProgram,+ nextProgram = nextProgram,+ focusRequester = channelInfoFocusRequester,+ lastVisitedCategoryName = lastVisitedCategory?.name,+ onDismiss = { viewModel.closeChannelInfoOverlay() },+ onOverlayInteracted = viewModel::onLiveOverlayInteraction,+ onOpenFullEpg = {+ viewModel.closeChannelInfoOverlay()+ viewModel.openEpgOverlay()+ },+ onOpenLastGroup = {+ viewModel.closeChannelInfoOverlay()+ viewModel.openLastVisitedCategory()+ },+ currentRecordingStatus = currentChannelRecording?.status,+ onStartRecording = viewModel::startManualRecording,+ onStopRecording = viewModel::stopCurrentRecording,+ onRestartProgram = { viewModel.restartCurrentProgram() },+ onToggleAspectRatio = { viewModel.toggleAspectRatio() },+ onToggleDiagnostics = { viewModel.toggleDiagnostics() },+ onTogglePlayPause = { if (isPlaying) viewModel.pause() else viewModel.play() },+ isPlaying = isPlaying,+ currentAspectRatio = aspectRatio.modeName,+ isDiagnosticsEnabled = showDiagnostics,+ onOpenSplitScreen = { showSplitDialog = true }+ )+ }}}}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 3bcf0806..f36b6c51 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@@ -437,6 +437,19 @@ class PlayerViewModel @Inject constructor()}+ fun seekTo(positionMs: Long) {+ playerEngine.seekTo(positionMs)+ }++ fun setScrubbingMode(enabled: Boolean) {+ playerEngine.setScrubbingMode(enabled)+ }++ private suspend fun preparePlayer(streamInfo: com.streamvault.domain.model.StreamInfo) {+ playerEngine.setMuted(preferencesRepository.playerMuted.first())+ playerEngine.prepare(streamInfo)+ }+fun prepare(streamUrl: String,epgChannelId: String?,@@ -485,7 +498,7 @@ class PlayerViewModel @Inject constructor(title = currentTitle,streamType = com.streamvault.domain.model.StreamType.UNKNOWN)- playerEngine.prepare(streamInfo)+ preparePlayer(streamInfo)}// Show context info on entry for both Live and VOD@@ -565,7 +578,7 @@ class PlayerViewModel @Inject constructor(title = currentTitle,streamType = com.streamvault.domain.model.StreamType.UNKNOWN)- playerEngine.prepare(catchupStream)+ preparePlayer(catchupStream)playerEngine.play()_showControls.value = true} else {@@ -1029,7 +1042,7 @@ class PlayerViewModel @Inject constructor(title = currentTitle,streamType = com.streamvault.domain.model.StreamType.UNKNOWN)- playerEngine.prepare(streamInfo)+ preparePlayer(streamInfo)playerEngine.play()// Once the first frame is on screen, turn off scrubbing for full quality@@ -1229,7 +1242,7 @@ class PlayerViewModel @Inject constructor(title = currentTitle,streamType = com.streamvault.domain.model.StreamType.UNKNOWN)- playerEngine.prepare(streamInfo)+ preparePlayer(streamInfo)playerEngine.play()}return true@@ -1304,7 +1317,13 @@ class PlayerViewModel @Inject constructor(fun pause() = playerEngine.pause()fun seekForward() = playerEngine.seekForward()fun seekBackward() = playerEngine.seekBackward()- fun toggleMute() = playerEngine.toggleMute()+ fun toggleMute() {+ val muted = !isMuted.value+ playerEngine.setMuted(muted)+ viewModelScope.launch {+ preferencesRepository.setPlayerMuted(muted)+ }+ }fun toggleControls() {closeChannelInfoOverlay()@@ -1357,7 +1376,7 @@ class PlayerViewModel @Inject constructor(title = currentTitle,streamType = com.streamvault.domain.model.StreamType.UNKNOWN)- playerEngine.prepare(streamInfo)+ preparePlayer(streamInfo)playerEngine.play()_showControls.value = true} else {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.ktindex ba41acb1..f1fd180a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerControlsChrome.kt@@ -10,9 +10,11 @@ import androidx.compose.animation.slideInVerticallyimport androidx.compose.animation.slideOutHorizontallyimport androidx.compose.animation.slideOutVerticallyimport androidx.compose.foundation.background+import androidx.compose.foundation.layout.FlowRowimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApiimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSize@@ -34,10 +36,12 @@ import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusPropertiesimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Color@@ -89,6 +93,7 @@ fun PlayerControlsOverlay(isMuted: Boolean,mediaTitle: String?,playButtonFocusRequester: FocusRequester,+ quickActionsFocusRequester: FocusRequester,onClose: () -> Unit,onTogglePlayPause: () -> Unit,onSeekBackward: () -> Unit,@@ -103,7 +108,10 @@ fun PlayerControlsOverlay(onOpenAudioTracks: () -> Unit,onOpenVideoTracks: () -> Unit,onOpenSplitScreen: () -> Unit,+ onEnterPictureInPicture: () -> Unit,onToggleMute: () -> Unit,+ onSeekToPosition: (Long) -> Unit = {},+ onSetScrubbingMode: (Boolean) -> Unit = {},clockLabelOverride: String? = null,modifier: Modifier = Modifier) {@@ -137,6 +145,7 @@ fun PlayerControlsOverlay(currentRecordingStatus = currentRecordingStatus,isMuted = isMuted,mediaTitle = mediaTitle,+ quickActionsFocusRequester = quickActionsFocusRequester,modifier = Modifier.align(Alignment.BottomCenter),onRestartProgram = onRestartProgram,onOpenArchive = onOpenArchive,@@ -148,13 +157,17 @@ fun PlayerControlsOverlay(onOpenAudioTracks = onOpenAudioTracks,onOpenVideoTracks = onOpenVideoTracks,onOpenSplitScreen = onOpenSplitScreen,- onToggleMute = onToggleMute+ onEnterPictureInPicture = onEnterPictureInPicture,+ onToggleMute = onToggleMute,+ onSeekToPosition = onSeekToPosition,+ onSetScrubbingMode = onSetScrubbingMode)if (contentType != "LIVE") {PlayerTransportBar(isPlaying = isPlaying,playButtonFocusRequester = playButtonFocusRequester,+ quickActionsFocusRequester = quickActionsFocusRequester,onSeekBackward = onSeekBackward,onSeekForward = onSeekForward,onTogglePlayPause = onTogglePlayPause,@@ -429,6 +442,7 @@ private fun PlayerBottomBar(currentRecordingStatus: RecordingStatus?,isMuted: Boolean,mediaTitle: String?,+ quickActionsFocusRequester: FocusRequester,onRestartProgram: () -> Unit,onOpenArchive: () -> Unit,onStartRecording: () -> Unit,@@ -439,7 +453,10 @@ private fun PlayerBottomBar(onOpenAudioTracks: () -> Unit,onOpenVideoTracks: () -> Unit,onOpenSplitScreen: () -> Unit,+ onEnterPictureInPicture: () -> Unit,onToggleMute: () -> Unit,+ onSeekToPosition: (Long) -> Unit,+ onSetScrubbingMode: (Boolean) -> Unit,modifier: Modifier = Modifier) {Box(@@ -483,6 +500,7 @@ private fun PlayerBottomBar(currentRecordingStatus = currentRecordingStatus,isMuted = isMuted,mediaTitle = mediaTitle,+ quickActionsFocusRequester = quickActionsFocusRequester,onRestartProgram = onRestartProgram,onOpenArchive = onOpenArchive,onStartRecording = onStartRecording,@@ -493,11 +511,13 @@ private fun PlayerBottomBar(onOpenAudioTracks = onOpenAudioTracks,onOpenVideoTracks = onOpenVideoTracks,onOpenSplitScreen = onOpenSplitScreen,+ onEnterPictureInPicture = onEnterPictureInPicture,onToggleMute = onToggleMute)} else if (contentType != "LIVE") {PlayerVodInfo(title = title,+ contentType = contentType,currentPosition = currentPosition,duration = duration,aspectRatioLabel = aspectRatioLabel,@@ -505,10 +525,14 @@ private fun PlayerBottomBar(audioTrackCount = audioTrackCount,videoQualityCount = videoQualityCount,isMuted = isMuted,+ quickActionsFocusRequester = quickActionsFocusRequester,+ onSeekToPosition = onSeekToPosition,+ onSetScrubbingMode = onSetScrubbingMode,onToggleAspectRatio = onToggleAspectRatio,onOpenSubtitleTracks = onOpenSubtitleTracks,onOpenAudioTracks = onOpenAudioTracks,onOpenVideoTracks = onOpenVideoTracks,+ onEnterPictureInPicture = onEnterPictureInPicture,onToggleMute = onToggleMute)}@@ -529,6 +553,7 @@ private fun PlayerLiveInfo(currentRecordingStatus: RecordingStatus?,isMuted: Boolean,mediaTitle: String?,+ quickActionsFocusRequester: FocusRequester,onRestartProgram: () -> Unit,onOpenArchive: () -> Unit,onStartRecording: () -> Unit,@@ -539,9 +564,15 @@ private fun PlayerLiveInfo(onOpenAudioTracks: () -> Unit,onOpenVideoTracks: () -> Unit,onOpenSplitScreen: () -> Unit,+ onEnterPictureInPicture: () -> Unit,onToggleMute: () -> Unit) {val primaryActions = buildList {+ add(PlayerActionSpec(+ stringResource(if (isMuted) R.string.player_unmute else R.string.player_mute),+ onToggleMute+ ))+ add(PlayerActionSpec(stringResource(R.string.player_picture_in_picture), onEnterPictureInPicture))if (currentProgram?.hasArchive == true) {add(PlayerActionSpec(stringResource(R.string.player_restart), onRestartProgram))add(PlayerActionSpec(stringResource(R.string.player_archive), onOpenArchive))@@ -555,10 +586,6 @@ private fun PlayerLiveInfo(}val secondaryActions = buildList {add(PlayerActionSpec(stringResource(R.string.player_aspect_ratio_label, aspectRatioLabel), onToggleAspectRatio))- add(PlayerActionSpec(- stringResource(if (isMuted) R.string.player_unmute else R.string.player_mute),- onToggleMute- ))if (subtitleTrackCount > 0) {add(PlayerActionSpec(stringResource(R.string.player_subs), onOpenSubtitleTracks))}@@ -576,12 +603,18 @@ private fun PlayerLiveInfo(modifier = Modifier.weight(1f),verticalArrangement = Arrangement.spacedBy(8.dp)) {- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {PlayerMetaPill(text = stringResource(R.string.player_live_now), accent = true)PlayerMetaPill(text = stringResource(R.string.player_live_channel, displayChannelNumber))if (currentProgram?.hasArchive == true) {PlayerMetaPill(text = stringResource(R.string.player_archive_badge))}+ if (isMuted) {+ PlayerMetaPill(text = stringResource(R.string.player_muted_badge))+ }}Text(text = currentProgram?.title ?: mediaTitle ?: currentChannelName.orEmpty(),@@ -641,12 +674,17 @@ private fun PlayerLiveInfo(Spacer(modifier = Modifier.height(10.dp))}- PlayerQuickActionRows(primaryActions, secondaryActions)+ PlayerQuickActionRows(+ primaryActions = primaryActions,+ secondaryActions = secondaryActions,+ firstActionFocusRequester = quickActionsFocusRequester+ )}@Composableprivate fun PlayerVodInfo(title: String,+ contentType: String,currentPosition: Long,duration: Long,aspectRatioLabel: String,@@ -654,10 +692,14 @@ private fun PlayerVodInfo(audioTrackCount: Int,videoQualityCount: Int,isMuted: Boolean,+ quickActionsFocusRequester: FocusRequester,+ onSeekToPosition: (Long) -> Unit,+ onSetScrubbingMode: (Boolean) -> Unit,onToggleAspectRatio: () -> Unit,onOpenSubtitleTracks: () -> Unit,onOpenAudioTracks: () -> Unit,onOpenVideoTracks: () -> Unit,+ onEnterPictureInPicture: () -> Unit,onToggleMute: () -> Unit) {val actions = buildList {@@ -666,6 +708,7 @@ private fun PlayerVodInfo(stringResource(if (isMuted) R.string.player_unmute else R.string.player_mute),onToggleMute))+ add(PlayerActionSpec(stringResource(R.string.player_picture_in_picture), onEnterPictureInPicture))if (subtitleTrackCount > 0) {add(PlayerActionSpec(stringResource(R.string.player_subs), onOpenSubtitleTracks))}@@ -681,7 +724,17 @@ private fun PlayerVodInfo(verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.spacedBy(14.dp)) {- PlayerMetaPill(text = stringResource(R.string.player_playback_label), accent = true)+ PlayerMetaPill(+ text = if (contentType == "MOVIE") {+ stringResource(R.string.player_type_movie)+ } else {+ stringResource(R.string.player_type_series)+ },+ accent = true+ )+ if (isMuted) {+ PlayerMetaPill(text = stringResource(R.string.player_muted_badge))+ }Text(text = title,style = MaterialTheme.typography.bodyMedium,@@ -693,17 +746,58 @@ private fun PlayerVodInfo(Spacer(modifier = Modifier.height(14.dp))Row(verticalAlignment = Alignment.CenterVertically) {+ var sliderValue by remember(duration, currentPosition) {+ mutableStateOf(+ if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f+ )+ }+ var isScrubbing by remember { mutableStateOf(false) }+ val latestSeekCallback by rememberUpdatedState(onSeekToPosition)+ val latestScrubbingCallback by rememberUpdatedState(onSetScrubbingMode)++ LaunchedEffect(duration, currentPosition, isScrubbing) {+ if (!isScrubbing) {+ sliderValue = if (duration > 0) {+ currentPosition.toFloat() / duration.toFloat()+ } else {+ 0f+ }+ }+ }+Text(- text = formatDuration(currentPosition),+ text = formatDuration(+ if (isScrubbing && duration > 0) {+ (sliderValue * duration).toLong()+ } else {+ currentPosition+ }+ ),style = MaterialTheme.typography.labelMedium,color = Color.White)Slider(- value = if (duration > 0) currentPosition.toFloat() / duration else 0f,- onValueChange = { },+ value = sliderValue,+ onValueChange = { newValue ->+ if (!isScrubbing) {+ isScrubbing = true+ latestScrubbingCallback(true)+ }+ sliderValue = newValue+ },+ onValueChangeFinished = {+ if (duration > 0) {+ latestSeekCallback((sliderValue.coerceIn(0f, 1f) * duration).toLong())+ }+ if (isScrubbing) {+ latestScrubbingCallback(false)+ isScrubbing = false+ }+ },modifier = Modifier.weight(1f).padding(horizontal = 16.dp),+ enabled = duration > 0,colors = SliderDefaults.colors(activeTrackColor = Primary,inactiveTrackColor = Color.White.copy(alpha = 0.2f)@@ -716,13 +810,19 @@ private fun PlayerVodInfo()}- PlayerQuickActionRows(actions, emptyList())+ PlayerQuickActionRows(+ primaryActions = actions,+ secondaryActions = emptyList(),+ firstActionFocusRequester = quickActionsFocusRequester,+ primaryActionsUpFocusRequester = quickActionsFocusRequester+ )}@Composableprivate fun PlayerTransportBar(isPlaying: Boolean,playButtonFocusRequester: FocusRequester,+ quickActionsFocusRequester: FocusRequester,onSeekBackward: () -> Unit,onSeekForward: () -> Unit,onTogglePlayPause: () -> Unit,@@ -751,7 +851,10 @@ private fun PlayerTransportBar(PlayerTransportButton(label = "\u23EA",contentDescription = stringResource(R.string.player_rewind),- onClick = onSeekBackward+ onClick = onSeekBackward,+ modifier = Modifier.focusProperties {+ down = quickActionsFocusRequester+ })Surface(onClick = onTogglePlayPause,@@ -763,6 +866,9 @@ private fun PlayerTransportBar(modifier = Modifier.size(80.dp).focusRequester(playButtonFocusRequester)+ .focusProperties {+ down = quickActionsFocusRequester+ }.semantics { contentDescription = playPauseDescription }) {Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {@@ -785,7 +891,10 @@ private fun PlayerTransportBar(PlayerTransportButton(label = "\u23E9",contentDescription = stringResource(R.string.player_forward),- onClick = onSeekForward+ onClick = onSeekForward,+ modifier = Modifier.focusProperties {+ down = quickActionsFocusRequester+ })}}@@ -794,7 +903,8 @@ private fun PlayerTransportBar(@Composableprivate fun PlayerQuickSettingsButton(text: String,- onClick: () -> Unit+ onClick: () -> Unit,+ modifier: Modifier = Modifier) {Surface(onClick = onClick,@@ -802,7 +912,8 @@ private fun PlayerQuickSettingsButton(colors = ClickableSurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.1f),focusedContainerColor = Primary.copy(alpha = 0.9f)- )+ ),+ modifier = modifier) {Text(text = text,@@ -817,7 +928,8 @@ private fun PlayerQuickSettingsButton(private fun PlayerTransportButton(label: String,contentDescription: String,- onClick: () -> Unit+ onClick: () -> Unit,+ modifier: Modifier = Modifier) {Surface(onClick = onClick,@@ -826,7 +938,7 @@ private fun PlayerTransportButton(containerColor = Color.White.copy(alpha = 0.1f),focusedContainerColor = Color.White.copy(alpha = 0.3f)),- modifier = Modifier+ modifier = modifier.size(56.dp).semantics { this.contentDescription = contentDescription }) {@@ -860,10 +972,13 @@ private fun PlayerMetaPill(}}+@OptIn(ExperimentalLayoutApi::class)@Composableprivate fun PlayerQuickActionRows(primaryActions: List<PlayerActionSpec>,- secondaryActions: List<PlayerActionSpec>+ secondaryActions: List<PlayerActionSpec>,+ firstActionFocusRequester: FocusRequester,+ primaryActionsUpFocusRequester: FocusRequester? = null) {val rows = listOf(primaryActions, secondaryActions).filter { it.isNotEmpty() }if (rows.isEmpty()) return@@ -872,12 +987,31 @@ private fun PlayerQuickActionRows(Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {rows.forEachIndexed { index, row ->- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {if (index == 1) {PlayerMetaPill(text = stringResource(R.string.player_more_controls))}- row.forEach { action ->- PlayerQuickSettingsButton(action.label, action.onClick)+ row.forEachIndexed { actionIndex, action ->+ PlayerQuickSettingsButton(+ text = action.label,+ onClick = action.onClick,+ modifier = Modifier+ .then(+ if (index == 0 && actionIndex == 0) {+ Modifier.focusRequester(firstActionFocusRequester)+ } else {+ Modifier+ }+ )+ .focusProperties {+ if (index == 0 && actionIndex == 0 && primaryActionsUpFocusRequester != null) {+ up = primaryActionsUpFocusRequester+ }+ }+ )}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.ktindex b56af6f7..79e668ec 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt@@ -62,6 +62,7 @@ import androidx.tv.material3.Surfaceimport androidx.tv.material3.Textimport coil3.compose.AsyncImageimport com.streamvault.app.R+import com.streamvault.app.ui.components.ChannelLogoBadgeimport com.streamvault.app.ui.components.rememberCrossfadeImageModelimport com.streamvault.app.ui.components.shell.StatusPillimport com.streamvault.app.ui.design.AppColors@@ -200,27 +201,17 @@ fun ChannelInfoOverlay(modifier = Modifier.size(52.dp).clip(RoundedCornerShape(12.dp))- .background(AppColors.SurfaceEmphasis.copy(alpha = 0.46f))- .border(1.dp, AppColors.Focus.copy(alpha = 0.05f), RoundedCornerShape(12.dp)),- contentAlignment = Alignment.Center+ .border(1.dp, AppColors.Focus.copy(alpha = 0.05f), RoundedCornerShape(12.dp))) {- if (!currentChannel.logoUrl.isNullOrBlank()) {- AsyncImage(- model = rememberCrossfadeImageModel(currentChannel.logoUrl),- contentDescription = currentChannel.name,- modifier = Modifier- .fillMaxSize()- .padding(6.dp),- contentScale = androidx.compose.ui.layout.ContentScale.Fit- )- } else {- Text(- text = currentChannel.name.take(2).uppercase(Locale.getDefault()),- style = MaterialTheme.typography.labelLarge,- color = AppColors.TextSecondary,- fontWeight = FontWeight.Bold- )- }+ ChannelLogoBadge(+ channelName = currentChannel.name,+ logoUrl = currentChannel.logoUrl,+ backgroundColor = AppColors.SurfaceEmphasis.copy(alpha = 0.46f),+ contentPadding = PaddingValues(6.dp),+ textStyle = MaterialTheme.typography.labelLarge,+ textColor = AppColors.TextSecondary,+ modifier = Modifier.fillMaxSize()+ )}}Column(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 9a5b6647..11d25eb4 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@@ -85,7 +85,6 @@ fun SeriesScreen(var showPinDialog by remember { mutableStateOf(false) }var pinError by remember { mutableStateOf<String?>(null) }var pendingSeriesId by remember { mutableStateOf<Long?>(null) }- var selectedLibraryLens by rememberSaveable { mutableStateOf(SeriesLibraryLens.FAVORITES.name) }var selectedFacet by rememberSaveable { mutableStateOf(SeriesLibraryFacet.ALL.name) }var selectedSort by rememberSaveable { mutableStateOf(SeriesLibrarySort.LIBRARY.name) }val scope = rememberCoroutineScope()@@ -178,7 +177,6 @@ fun SeriesScreen(onSelectedFacetChange = { selectedFacet = it },selectedSort = selectedSort,onSelectedSortChange = { selectedSort = it },- onNavigate = onNavigate,onSeriesClick = onSeriesClick,onProtectedSeriesClick = { seriesId ->pendingSeriesId = seriesId@@ -187,613 +185,24 @@ fun SeriesScreen(onShowDialog = viewModel::onShowDialog,onSelectCategory = viewModel::selectCategory,onSelectFullLibraryBrowse = viewModel::selectFullLibraryBrowse,+ onOpenContinueWatching = {+ selectedFacet = SeriesLibraryFacet.RESUME.name+ selectedSort = SeriesLibrarySort.LIBRARY.name+ viewModel.selectFullLibraryBrowse()+ },+ onOpenTopRated = {+ selectedFacet = SeriesLibraryFacet.TOP_RATED.name+ selectedSort = SeriesLibrarySort.RATING.name+ viewModel.selectFullLibraryBrowse()+ },+ onOpenFresh = {+ selectedFacet = SeriesLibraryFacet.RECENTLY_UPDATED.name+ selectedSort = SeriesLibrarySort.UPDATED.name+ viewModel.selectFullLibraryBrowse()+ },onLoadMore = viewModel::loadMoreSelectedCategory,onDismissReorder = viewModel::exitCategoryReorderMode)- return@AppScreenScaffold- Row(modifier = Modifier.fillMaxSize()) {- // Category sidebar- val categorySearchFocusRequester = remember { FocusRequester() }- val categoryFocusRequesters = remember { mutableMapOf<String, FocusRequester>() }- var lastFocusedCategoryName by rememberSaveable { mutableStateOf<String?>(null) }- var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }- var preferCategoryRestore by rememberSaveable { mutableStateOf(false) }- val heroSeries = remember(uiState.categoryNames, uiState.seriesByCategory) {- uiState.categoryNames- .asSequence()- .mapNotNull { categoryName -> uiState.seriesByCategory[categoryName]?.firstOrNull() }- .firstOrNull()- }-- LaunchedEffect(- uiState.selectedCategoryForOptions,- uiState.showRenameGroupDialog,- uiState.showDeleteGroupDialog- ) {- val modalClosed =- uiState.selectedCategoryForOptions == null &&- !uiState.showRenameGroupDialog &&- !uiState.showDeleteGroupDialog- if (modalClosed && preferCategoryRestore && lastFocusedCategoryName != null) {- shouldRestoreCategoryFocus = true- preferCategoryRestore = false- }- }-- LaunchedEffect(shouldRestoreCategoryFocus, uiState.categoryNames) {- if (!shouldRestoreCategoryFocus) return@LaunchedEffect- kotlinx.coroutines.delay(80)- val categoryName = lastFocusedCategoryName- if (categoryName != null) {- runCatching {- categoryFocusRequesters[categoryName]?.requestFocus()- }- }- shouldRestoreCategoryFocus = false- }-- Column(- modifier = Modifier- .width(188.dp)- .fillMaxHeight()- .background(SurfaceElevated.copy(alpha = 0.72f), RoundedCornerShape(20.dp))- .padding(top = 8.dp)- ) {- // Sticky Header- Column(modifier = Modifier.padding(horizontal = 12.dp)) {- Text(- text = stringResource(R.string.series_categories_title),- style = MaterialTheme.typography.titleSmall,- color = Primary,- modifier = Modifier.padding(vertical = 8.dp)- )- SearchInput(- value = uiState.searchQuery,- onValueChange = { viewModel.setSearchQuery(it) },- placeholder = stringResource(R.string.series_search_placeholder),- focusRequester = categorySearchFocusRequester,- modifier = Modifier.padding(bottom = 8.dp)- )- }-- LazyColumn(- modifier = Modifier.fillMaxWidth(),- contentPadding = PaddingValues(bottom = 8.dp)- ) {- item {- val isAllSelected = uiState.selectedCategory == null || uiState.selectedCategory == uiState.fullLibraryCategoryName- Surface(- onClick = { viewModel.selectCategory(null) },- shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isAllSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.25f)- ),- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 2.dp)- .onPreviewKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {- categorySearchFocusRequester.requestFocus()- true- } else false- } else false- }- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.series_all_categories),- style = MaterialTheme.typography.bodyMedium,- color = if (isAllSelected) Primary else OnSurface,- modifier = Modifier.weight(1f)- )- Text(- text = "${uiState.libraryCount}",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- }- }- items(uiState.categoryNames.size) { index ->- val categoryName = uiState.categoryNames[index]- val isSelected = uiState.selectedCategory == categoryName- val count = uiState.categoryCounts[categoryName] ?: 0- Surface(- onClick = { viewModel.selectCategory(categoryName) },- onLongClick = {- preferCategoryRestore = true- viewModel.showCategoryOptions(categoryName)- },- shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.25f)- ),- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 2.dp)- .focusRequester(categoryFocusRequesters.getOrPut(categoryName) { FocusRequester() })- .onFocusChanged { focusState ->- if (focusState.isFocused) {- lastFocusedCategoryName = categoryName- }- }- .onPreviewKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {- categorySearchFocusRequester.requestFocus()- true- } else false- } else false- }- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = categoryName,- style = MaterialTheme.typography.bodyMedium,- color = if (isSelected) Primary else OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- modifier = Modifier.weight(1f)- )- Text(- text = "$count",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- }- }- }- }-- val savedShortcuts = remember(- uiState.favoriteCategoryName,- uiState.categories,- uiState.seriesByCategory- ) {- buildList {- val favoriteCount = uiState.categoryCounts[uiState.favoriteCategoryName] ?: 0- if (favoriteCount > 0) {- add(- SavedCategoryShortcut(- name = uiState.favoriteCategoryName,- count = favoriteCount- )- )- }- uiState.categories- .asSequence()- .filterNot { it.name == uiState.favoriteCategoryName }- .map { category ->- SavedCategoryShortcut(- name = category.name,- count = uiState.categoryCounts[category.name] ?: 0- )- }- .filter { it.count > 0 }- .sortedByDescending { it.count }- .forEach(::add)- }- }- val selectedSavedCategory = remember(- uiState.selectedCategory,- uiState.favoriteCategoryName,- uiState.categories- ) {- when (uiState.selectedCategory) {- null -> null- uiState.favoriteCategoryName -> com.streamvault.domain.model.Category(- id = -999L,- name = uiState.favoriteCategoryName,- type = com.streamvault.domain.model.ContentType.SERIES,- isVirtual = true- )- else -> uiState.categories.firstOrNull { it.name == uiState.selectedCategory }- }- }-- // Main content- if (uiState.selectedCategory == null) {- val activeLibraryLens = remember(selectedLibraryLens, uiState.libraryLensRows) {- SeriesLibraryLens.entries.firstOrNull { it.name == selectedLibraryLens && uiState.libraryLensRows.containsKey(it) }- ?: uiState.libraryLensRows.keys.firstOrNull()- }- // Netflix-style rows (All categories view)- LazyColumn(- modifier = Modifier.fillMaxSize(),- contentPadding = PaddingValues(- start = LocalSpacing.current.safeHoriz,- end = LocalSpacing.current.safeHoriz,- bottom = LocalSpacing.current.safeBottom- )- ) {- item {- BrowseSearchLaunchCard(- title = stringResource(R.string.series_search_launch_title),- subtitle = stringResource(R.string.series_search_launch_subtitle),- onClick = { onNavigate(Routes.SEARCH) },- modifier = Modifier.padding(vertical = LocalSpacing.current.md)- )- }-- if (heroSeries != null) {- item {- SeriesHeroBanner(- series = heroSeries,- onClick = {- val isLocked = (heroSeries.isAdult || heroSeries.isUserProtected) && uiState.parentalControlLevel == 1- if (isLocked) {- pendingSeriesId = heroSeries.id- showPinDialog = true- } else {- onSeriesClick(heroSeries.id)- }- }- )- }- }-- item(key = "saved_shortcuts") {- SavedCategoryShortcutsRow(- title = stringResource(R.string.library_saved_title),- subtitle = stringResource(R.string.library_saved_subtitle),- emptyHint = stringResource(R.string.series_saved_empty_hint),- shortcuts = savedShortcuts,- managementHint = stringResource(R.string.library_saved_manage_hint),- primaryShortcutLabel = stringResource(R.string.library_browse_all),- isPrimaryShortcutSelected = uiState.selectedCategory == null,- onPrimaryShortcutClick = { viewModel.selectCategory(null) },- selectedShortcutName = uiState.selectedCategory,- onShortcutLongClick = viewModel::showCategoryOptions,- onShortcutClick = viewModel::selectCategory- )- }-- if (activeLibraryLens != null) {- item(key = "library_lens_chips") {- SelectionChipRow(- title = stringResource(R.string.library_lens_title),- subtitle = stringResource(R.string.series_library_lens_subtitle),- chips = uiState.libraryLensRows.keys.map { lens ->- SelectionChip(- key = lens.name,- label = seriesLibraryLensLabel(lens),- supportingText = stringResource(- R.string.library_saved_items_count,- uiState.libraryLensRows[lens]?.size ?: 0- )- )- },- selectedKey = activeLibraryLens.name,- onChipSelected = { selectedLibraryLens = it },- contentPadding = PaddingValues(horizontal = 0.dp)- )- }-- item(key = "library_lens_row") {- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- Surface(- onClick = viewModel::selectFullLibraryBrowse,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.06f),- focusedContainerColor = Primary- ),- modifier = Modifier.padding(horizontal = 16.dp)- ) {- Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)) {- Text(- text = stringResource(R.string.library_full_browse_title_series),- style = MaterialTheme.typography.titleSmall,- color = Color.White- )- Spacer(Modifier.height(4.dp))- Text(- text = stringResource(R.string.library_full_browse_subtitle, uiState.libraryCount),- style = MaterialTheme.typography.bodySmall,- color = Color.White.copy(alpha = 0.8f)- )- }- }-- CategoryRow(- title = seriesLibraryLensLabel(activeLibraryLens),- items = uiState.libraryLensRows[activeLibraryLens].orEmpty(),- onSeeAll = if (activeLibraryLens == SeriesLibraryLens.FAVORITES) {- { viewModel.selectCategory(uiState.favoriteCategoryName) }- } else {- null- },- keySelector = { it.id }- ) { series ->- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1- SeriesCard(- series = series,- isLocked = isLocked,- onClick = {- if (isLocked) {- pendingSeriesId = series.id- showPinDialog = true- } else {- onSeriesClick(series.id)- }- },- onLongClick = { viewModel.onShowDialog(series) }- )- }- }- }- }-- // Continue Watching row (shown first, only if non-empty)- item(key = "continue_watching") {- ContinueWatchingRow(- items = uiState.continueWatching,- onItemClick = { history -> onSeriesClick(history.seriesId ?: history.contentId) }- )- }- items(- items = uiState.seriesByCategory.entries.toList(),- key = { it.key }- ) { (categoryName, seriesList) ->- CategoryRow(- title = categoryName,- items = seriesList,- onSeeAll = { viewModel.selectCategory(categoryName) },- keySelector = { it.id }- ) { series ->- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1- SeriesCard(- series = series,- isLocked = isLocked,- onClick = {- if (isLocked) {- pendingSeriesId = series.id- showPinDialog = true- } else {- onSeriesClick(series.id)- }- },- onLongClick = {- viewModel.onShowDialog(series)- }- )- }- }- }- } else {- // Filtered grid for selected category- val baseSeries = if (uiState.searchQuery.isBlank()) {- uiState.selectedCategoryItems- } else {- uiState.seriesByCategory[uiState.selectedCategory] ?: emptyList()- }- val activeSeries = if (uiState.isReorderMode) uiState.filteredSeries else baseSeries- val resumeSeriesIds = remember(uiState.continueWatching) {- uiState.continueWatching.mapNotNull { history ->- history.seriesId ?: history.contentId- }.toSet()- }- val activeFacet = remember(selectedFacet) {- SeriesLibraryFacet.entries.firstOrNull { it.name == selectedFacet } ?: SeriesLibraryFacet.ALL- }- val activeSort = remember(selectedSort) {- SeriesLibrarySort.entries.firstOrNull { it.name == selectedSort } ?: SeriesLibrarySort.LIBRARY- }- val filteredGridSeries = remember(activeSeries, activeFacet, activeSort, resumeSeriesIds, uiState.isReorderMode) {- if (uiState.isReorderMode) {- activeSeries- } else {- applySeriesFacetAndSort(- items = activeSeries,- facet = activeFacet,- sort = activeSort,- resumeSeriesIds = resumeSeriesIds- )- }- }- val showSelectedCategoryControls = !uiState.isReorderMode &&- (selectedSavedCategory != null || activeSeries.size > 8)-- var draggingSeries by remember { mutableStateOf<com.streamvault.domain.model.Series?>(null) }-- LaunchedEffect(uiState.isReorderMode) {- if (!uiState.isReorderMode) {- draggingSeries = null- }- }-- Column(- modifier = Modifier.fillMaxSize()- ) {- if (selectedSavedCategory != null) {- SavedCategoryShortcutsRow(- title = stringResource(R.string.library_saved_title),- subtitle = stringResource(R.string.library_saved_subtitle),- emptyHint = stringResource(R.string.series_saved_empty_hint),- shortcuts = savedShortcuts,- managementHint = stringResource(R.string.library_saved_manage_hint),- primaryShortcutLabel = stringResource(R.string.library_browse_all),- isPrimaryShortcutSelected = uiState.selectedCategory == null,- onPrimaryShortcutClick = { viewModel.selectCategory(null) },- selectedShortcutName = uiState.selectedCategory,- onShortcutLongClick = viewModel::showCategoryOptions,- onShortcutClick = viewModel::selectCategory- )-- SavedCategoryContextCard(- categoryName = selectedSavedCategory.name,- itemCount = uiState.categoryCounts[selectedSavedCategory.name] ?: filteredGridSeries.size,- onManageClick = { viewModel.showCategoryOptions(selectedSavedCategory.name) },- onBrowseAllClick = { viewModel.selectCategory(null) },- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)- )- }-- if (showSelectedCategoryControls) {- SelectionChipRow(- title = stringResource(R.string.library_filter_title),- chips = buildSeriesFacetChips(- items = activeSeries,- resumeSeriesIds = resumeSeriesIds- ),- selectedKey = activeFacet.name,- onChipSelected = { selectedFacet = it },- modifier = Modifier.padding(horizontal = 16.dp),- contentPadding = PaddingValues(horizontal = 0.dp)- )-- SelectionChipRow(- title = stringResource(R.string.library_sort_title),- chips = SeriesLibrarySort.entries.map { sort ->- SelectionChip(- key = sort.name,- label = when (sort) {- SeriesLibrarySort.LIBRARY -> stringResource(R.string.library_sort_library)- SeriesLibrarySort.TITLE -> stringResource(R.string.library_sort_az)- SeriesLibrarySort.UPDATED -> stringResource(R.string.library_sort_updated)- SeriesLibrarySort.RATING -> stringResource(R.string.library_sort_rating)- }- )- },- selectedKey = activeSort.name,- onChipSelected = { selectedSort = it },- modifier = Modifier.padding(horizontal = 16.dp),- contentPadding = PaddingValues(horizontal = 0.dp)- )- }-- LazyVerticalGrid(- columns = GridCells.Adaptive(minSize = 138.dp),- modifier = Modifier- .fillMaxSize()- .onPreviewKeyEvent { event ->- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {- if (draggingSeries != null) {- draggingSeries = null- true- } else {- viewModel.exitCategoryReorderMode()- true- }- } else false- } else false- },- contentPadding = PaddingValues(12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- item(span = { GridItemSpan(maxLineSpan) }) {- Column(modifier = Modifier.padding(bottom = 16.dp)) {- Text(- text = when (uiState.selectedCategory) {- uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_series)- else -> uiState.selectedCategory ?: ""- },- style = MaterialTheme.typography.titleLarge,- color = Primary,- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold- )- if (!uiState.isReorderMode && uiState.selectedCategoryTotalCount > 0) {- Spacer(Modifier.height(6.dp))- Text(- text = stringResource(- R.string.library_loaded_results,- uiState.selectedCategoryLoadedCount,- uiState.selectedCategoryTotalCount- ),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }-- if (filteredGridSeries.isEmpty()) {- item(span = { GridItemSpan(maxLineSpan) }) {- Text(- text = stringResource(R.string.library_filter_empty),- style = MaterialTheme.typography.bodyLarge,- color = OnSurfaceDim,- modifier = Modifier.padding(bottom = 12.dp)- )- }- }-- gridItems(- items = filteredGridSeries,- key = { it.id }- ) { series ->- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1- val isDraggingThis = draggingSeries == series-- SeriesCard(- series = series,- isLocked = isLocked,- isReorderMode = uiState.isReorderMode,- isDragging = isDraggingThis,- onClick = {- if (uiState.isReorderMode) {- draggingSeries = if (isDraggingThis) null else series- } else if (isLocked) {- pendingSeriesId = series.id- showPinDialog = true- } else {- onSeriesClick(series.id)- }- },- onLongClick = {- if (!uiState.isReorderMode) {- viewModel.onShowDialog(series)- }- },- modifier = Modifier.onPreviewKeyEvent { event ->- if (uiState.isReorderMode && isDraggingThis && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_LEFT,- android.view.KeyEvent.KEYCODE_DPAD_UP -> {- viewModel.moveItemUp(series)- true- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT,- android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {- viewModel.moveItemDown(series)- true- }- else -> false- }- } else false- }- )- }-- if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {- item(span = { GridItemSpan(maxLineSpan) }) {- LoadMoreCard(- label = stringResource(- R.string.library_load_more,- uiState.selectedCategoryLoadedCount,- uiState.selectedCategoryTotalCount- ),- onClick = viewModel::loadMoreSelectedCategory,- modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)- )- }- }- }- }- }- }}}SnackbarHost(@@ -856,25 +265,6 @@ fun SeriesScreen(}}-@Composable-fun SeriesHeroBanner(- series: com.streamvault.domain.model.Series,- onClick: () -> Unit-) {- BrowseHeroPanel(- title = series.name,- subtitle = series.plot ?: stringResource(R.string.series_library_lens_subtitle),- onClick = onClick,- eyebrow = series.genre ?: series.categoryName,- imageUrl = series.backdropUrl ?: series.posterUrl,- metadata = listOfNotNull(- series.releaseDate,- series.rating.takeIf { it > 0f }?.let { "RTG ${String.format("%.1f", it)}" }- ),- actionLabel = stringResource(R.string.player_resume).substringBefore(" ")- )-}-private enum class SeriesLibraryFacet {ALL,FAVORITES,@@ -890,12 +280,14 @@ private fun SeriesVodContent(onSelectedFacetChange: (String) -> Unit,selectedSort: String,onSelectedSortChange: (String) -> Unit,- onNavigate: (String) -> Unit,onSeriesClick: (Long) -> Unit,onProtectedSeriesClick: (Long) -> Unit,onShowDialog: (Series) -> Unit,onSelectCategory: (String?) -> Unit,onSelectFullLibraryBrowse: () -> Unit,+ onOpenContinueWatching: () -> Unit,+ onOpenTopRated: () -> Unit,+ onOpenFresh: () -> Unit,onLoadMore: () -> Unit,onDismissReorder: () -> Unit) {@@ -981,7 +373,7 @@ private fun SeriesVodContent(key = "resume",label = stringResource(R.string.library_lens_continue),detail = "${continueWatching.size} items",- onClick = { }+ onClick = onOpenContinueWatching))}@@ -991,7 +383,7 @@ private fun SeriesVodContent(key = SeriesLibraryLens.TOP_RATED.name,label = stringResource(R.string.library_lens_top_rated),detail = "${topRatedSeries.size} picks",- onClick = { }+ onClick = onOpenTopRated))}@@ -1001,7 +393,7 @@ private fun SeriesVodContent(key = SeriesLibraryLens.FRESH.name,label = stringResource(R.string.library_lens_fresh_series),detail = "${freshSeries.size} picks",- onClick = { }+ onClick = onOpenFresh))}@@ -1172,7 +564,7 @@ private fun SeriesVodContent(key = uiState.selectedCategory ?: "",label = uiState.selectedCategory ?: stringResource(R.string.nav_series),detail = "${uiState.selectedCategoryTotalCount} titles",- onClick = { }+ onClick = { showCategoryPicker = true }))}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 3e6d1de5..c9ecca89 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@@ -967,6 +967,11 @@ private fun ProviderSettingsCard(}ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_epg), count = model.epgCount)}++ ProviderDiagnosticsPanel(+ provider = provider,+ diagnostics = model+ )}if (syncWarnings.isNotEmpty()) {diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 9cee7a1c..7b2a37b3 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -94,7 +94,7 @@<string name="dashboard_provider_expires_at">Expires %1$s</string><string name="dashboard_provider_no_expiry">No expiry reported</string><string name="dashboard_warning_title">Provider Needs Attention</string>- <string name="dashboard_warning_review">Open Diagnostics</string>+ <string name="dashboard_warning_review">Open Provider Details</string><string name="dashboard_updated_series_badge">Updated series</string><string name="dashboard_stat_live">%1$d live</string><string name="dashboard_stat_favorites">%1$d favorites</string>@@ -521,7 +521,9 @@<string name="player_subs">Subs</string><string name="player_audio">Audio</string><string name="player_mute">Mute</string>+ <string name="player_muted_badge">Muted</string><string name="player_unmute">Unmute</string>+ <string name="player_picture_in_picture">Picture in picture</string><string name="player_resume_title">Resume Playback</string><string name="player_resume_desc">Do you want to resume %1$s from where you left off?</string><string name="player_resume_start_over">Start Over</string>diff --git a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt b/data/src/main/java/com/streamvault/data/parser/XmltvParser.ktindex 96ab6860..46355a16 100644--- a/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt+++ b/data/src/main/java/com/streamvault/data/parser/XmltvParser.kt@@ -4,9 +4,13 @@ import com.streamvault.domain.model.Programimport org.xmlpull.v1.XmlPullParserimport org.xmlpull.v1.XmlPullParserFactoryimport java.io.InputStream-import java.text.SimpleDateFormat+import java.time.LocalDate+import java.time.LocalDateTime+import java.time.OffsetDateTime+import java.time.ZoneOffset+import java.time.format.DateTimeFormatter+import java.time.format.DateTimeFormatterBuilderimport java.util.Locale-import java.util.TimeZoneimport java.util.logging.Levelimport java.util.logging.Logger@@ -24,15 +28,27 @@ class XmltvParser {private val logger = Logger.getLogger(XmltvParser::class.java.name)- private val dateFormats = listOf(- SimpleDateFormat("yyyyMMddHHmmss Z", Locale.US),- SimpleDateFormat("yyyyMMddHHmmss", Locale.US),- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US),- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US),- SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US),- SimpleDateFormat("yyyyMMddHHmm", Locale.US),- SimpleDateFormat("yyyyMMdd", Locale.US)- ).onEach { it.timeZone = TimeZone.getTimeZone("UTC") }+ private val offsetDateFormats = listOf(+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyyMMddHHmmss xx")+ .toFormatter(Locale.US),+ DateTimeFormatterBuilder()+ .parseCaseInsensitive()+ .appendPattern("yyyy-MM-dd'T'HH:mm:ssXXX")+ .toFormatter(Locale.US)+ )++ private val localDateTimeFormats = listOf(+ DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.US),+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.US),+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.US),+ DateTimeFormatter.ofPattern("yyyyMMddHHmm", Locale.US)+ )++ private val localDateFormats = listOf(+ DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US)+ )@Deprecated(message = "Loads all programs into memory. Use parseStreaming() for large EPG files.",@@ -209,22 +225,26 @@ class XmltvParser {private fun parseDate(dateStr: String?): Long {if (dateStr.isNullOrBlank()) return 0- for (format in dateFormats) {- try {- val threadSafeFormat = format.clone() as SimpleDateFormat- return threadSafeFormat.parse(dateStr)?.time ?: continue- } catch (_: Exception) {- continue- }- }+ offsetDateFormats.firstNotNullOfOrNull { formatter ->+ parseOffsetDateTime(dateStr, formatter)+ }?.let { return it }++ localDateTimeFormats.firstNotNullOfOrNull { formatter ->+ parseLocalDateTime(dateStr, formatter)+ }?.let { return it }++ localDateFormats.firstNotNullOfOrNull { formatter ->+ parseLocalDate(dateStr, formatter)+ }?.let { return it }// Last resort: try to extract just the timestamp portiontry {val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")if (cleaned.length >= 14) {- val basicFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.US)- basicFormat.timeZone = TimeZone.getTimeZone("UTC")- return basicFormat.parse(cleaned.substring(0, 14))?.time ?: 0+ return parseLocalDateTime(+ cleaned.substring(0, 14),+ DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.US)+ ) ?: 0}} catch (_: Exception) {// Give up@@ -233,4 +253,24 @@ class XmltvParser {logger.warning("Unparseable XMLTV date: $dateStr")return 0}++ private fun parseOffsetDateTime(dateStr: String, formatter: DateTimeFormatter): Long? =+ runCatching {+ OffsetDateTime.parse(dateStr, formatter).toInstant().toEpochMilli()+ }.getOrNull()++ private fun parseLocalDateTime(dateStr: String, formatter: DateTimeFormatter): Long? =+ runCatching {+ LocalDateTime.parse(dateStr, formatter)+ .toInstant(ZoneOffset.UTC)+ .toEpochMilli()+ }.getOrNull()++ private fun parseLocalDate(dateStr: String, formatter: DateTimeFormatter): Long? =+ runCatching {+ LocalDate.parse(dateStr, formatter)+ .atStartOfDay()+ .toInstant(ZoneOffset.UTC)+ .toEpochMilli()+ }.getOrNull()}diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 23cca611..c778a7f8 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -59,6 +59,7 @@ class PreferencesRepository @Inject constructor(val MULTIVIEW_PRESET_3 = stringPreferencesKey("multiview_preset_3")val MULTIVIEW_PERFORMANCE_MODE = stringPreferencesKey("multiview_performance_mode")val IS_INCOGNITO_MODE = booleanPreferencesKey("is_incognito_mode")+ val PLAYER_MUTED = booleanPreferencesKey("player_muted")}val lastActiveProviderId: Flow<Long?> = context.dataStore.data.map { preferences ->@@ -73,6 +74,10 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.IS_INCOGNITO_MODE] ?: false}+ val playerMuted: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.PLAYER_MUTED] ?: false+ }+val parentalControlLevel: Flow<Int> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 1 // Default to 1 = LOCKED@@ -104,6 +109,12 @@ class PreferencesRepository @Inject constructor(}}+ suspend fun setPlayerMuted(muted: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.PLAYER_MUTED] = muted+ }+ }+suspend fun setParentalPin(pin: String) {val salt = ByteArray(PIN_SALT_BYTES).also { secureRandom.nextBytes(it) }val hash = hashPin(pin, salt)diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex 87db7190..8fb34ac6 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -18,11 +18,14 @@ import kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport okhttp3.OkHttpClientimport okhttp3.Requestimport java.io.FilterInputStreamimport java.io.IOException+import java.util.concurrent.ConcurrentHashMapimport javax.inject.Injectimport javax.inject.Singleton@@ -35,6 +38,8 @@ class EpgRepositoryImpl @Inject constructor(private val transactionRunner: DatabaseTransactionRunner) : EpgRepository {+ private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()+companion object {private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MBprivate const val NOW_AND_NEXT_LOOKBACK_MS = 60L * 60L * 1000L@@ -110,62 +115,64 @@ class EpgRepositoryImpl @Inject constructor(override suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit> =withContext(Dispatchers.IO) {- val stagingProviderId = -providerId- val batch = ArrayList<ProgramEntity>(500)- try {- programDao.deleteByProvider(stagingProviderId)-- val request = Request.Builder().url(epgUrl).build()- val response = okHttpClient.newCall(request).execute()+ providerRefreshMutex(providerId).withLock {+ val stagingProviderId = -providerId+ val batch = ArrayList<ProgramEntity>(500)+ try {+ programDao.deleteByProvider(stagingProviderId)- if (!response.isSuccessful) {- return@withContext Result.error("Failed to download EPG: HTTP ${response.code}")- }+ val request = Request.Builder().url(epgUrl).build()+ val response = okHttpClient.newCall(request).execute()- val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1L- if (contentLength > MAX_EPG_SIZE_BYTES) {- response.close()- return@withContext Result.error("EPG file too large (${contentLength / 1_048_576}MB)")- }+ if (!response.isSuccessful) {+ return@withLock Result.error("Failed to download EPG: HTTP ${response.code}")+ }- val body = response.body ?: return@withContext Result.error("Empty EPG response")+ val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1L+ if (contentLength > MAX_EPG_SIZE_BYTES) {+ response.close()+ return@withLock Result.error("EPG file too large (${contentLength / 1_048_576}MB)")+ }- body.byteStream().use { inputStream ->- // Cap total bytes read even when Content-Length is absent (chunked transfer)- val limitedStream = object : FilterInputStream(inputStream) {- private var bytesRead = 0L- override fun read(): Int {- if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")- return super.read().also { if (it >= 0) bytesRead++ }+ val body = response.body ?: return@withLock Result.error("Empty EPG response")++ body.byteStream().use { inputStream ->+ // Cap total bytes read even when Content-Length is absent (chunked transfer)+ val limitedStream = object : FilterInputStream(inputStream) {+ private var bytesRead = 0L+ override fun read(): Int {+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")+ return super.read().also { if (it >= 0) bytesRead++ }+ }+ override fun read(b: ByteArray, off: Int, len: Int): Int {+ if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")+ return super.read(b, off, len).also { if (it > 0) bytesRead += it }+ }}- override fun read(b: ByteArray, off: Int, len: Int): Int {- if (bytesRead >= MAX_EPG_SIZE_BYTES) throw IOException("EPG response too large (>200 MB)")- return super.read(b, off, len).also { if (it > 0) bytesRead += it }+ xmltvParser.parseStreaming(limitedStream) { program ->+ batch.add(program.copy(providerId = stagingProviderId).toEntity())+ if (batch.size >= 500) {+ programDao.insertAll(batch.toList())+ batch.clear()+ }}}- xmltvParser.parseStreaming(limitedStream) { program ->- batch.add(program.copy(providerId = stagingProviderId).toEntity())- if (batch.size >= 500) {- programDao.insertAll(batch.toList())- batch.clear()- }++ if (batch.isNotEmpty()) {+ programDao.insertAll(batch.toList())+ batch.clear()}- }- if (batch.isNotEmpty()) {- programDao.insertAll(batch.toList())- batch.clear()- }+ transactionRunner.inTransaction {+ programDao.deleteByProvider(providerId)+ programDao.moveToProvider(stagingProviderId, providerId)+ }- transactionRunner.inTransaction {- programDao.deleteByProvider(providerId)- programDao.moveToProvider(stagingProviderId, providerId)+ Result.success(Unit)+ } catch (e: Exception) {+ programDao.deleteByProvider(stagingProviderId)+ Result.error("Failed to refresh EPG: ${e.message}", e)}-- Result.success(Unit)- } catch (e: Exception) {- programDao.deleteByProvider(stagingProviderId)- Result.error("Failed to refresh EPG: ${e.message}", e)}}@@ -179,4 +186,7 @@ class EpgRepositoryImpl @Inject constructor(delay(NOW_AND_NEXT_REFRESH_INTERVAL_MS)}}++ private fun providerRefreshMutex(providerId: Long): Mutex =+ providerRefreshMutexes.computeIfAbsent(providerId) { Mutex() }}diff --git a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.ktindex ce612a64..ada1407d 100644--- a/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/FavoriteRepositoryImpl.kt@@ -1,5 +1,6 @@package com.streamvault.data.repository+import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.FavoriteDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.CategoryCount@@ -15,7 +16,8 @@ import javax.inject.Singleton@Singletonclass FavoriteRepositoryImpl @Inject constructor(private val favoriteDao: FavoriteDao,- private val virtualGroupDao: VirtualGroupDao+ private val virtualGroupDao: VirtualGroupDao,+ private val transactionRunner: DatabaseTransactionRunner) : FavoriteRepository {override fun getFavorites(contentType: ContentType?): Flow<List<Favorite>> {@@ -50,14 +52,16 @@ class FavoriteRepositoryImpl @Inject constructor(contentType: ContentType,groupId: Long?): Result<Unit> = try {- val maxPos = favoriteDao.getMaxPosition(groupId) ?: -1- val favorite = Favorite(- contentId = contentId,- contentType = contentType,- position = maxPos + 1,- groupId = groupId- )- favoriteDao.insert(favorite.toEntity())+ transactionRunner.inTransaction {+ val maxPos = favoriteDao.getMaxPosition(groupId) ?: -1+ val favorite = Favorite(+ contentId = contentId,+ contentType = contentType,+ position = maxPos + 1,+ groupId = groupId+ )+ favoriteDao.insert(favorite.toEntity())+ }Result.success(Unit)} catch (e: Exception) {Result.error("Failed to add favorite: ${e.message}", e)diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex b3d05337..27887676 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -89,6 +89,8 @@ class SyncManager @Inject constructor(private val startId: Long // retained for API compatibility but no longer used in ID generation) {private val categoryIds = LinkedHashMap<String, Long>()+ val count: Int+ get() = categoryIds.sizefun idFor(name: String): Long {return categoryIds.getOrPut(name) { stableId(providerId, type, name) }@@ -439,6 +441,8 @@ class SyncManager @Inject constructor(var nextMilestone = PROGRESS_INTERVALval warnings = mutableListOf<String>()var insecureStreamCount = 0+ var publishedLiveCategoryCount = 0+ var publishedMovieCategoryCount = 0openPlaylistStream(provider) { streamed ->progress(onProgress, "Parsing Playlist...")@@ -455,6 +459,14 @@ class SyncManager @Inject constructor() { entry ->parsedCount++if (parsedCount >= nextMilestone) {+ if (includeLive && liveCategories.count > publishedLiveCategoryCount) {+ categoryDao.insertAll(liveCategories.entities())+ publishedLiveCategoryCount = liveCategories.count+ }+ if (includeMovies && movieCategories.count > publishedMovieCategoryCount) {+ categoryDao.insertAll(movieCategories.entities())+ publishedMovieCategoryCount = movieCategories.count+ }progress(onProgress, "Imported $parsedCount playlist entries...")nextMilestone += PROGRESS_INTERVAL}diff --git a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.ktindex 1dd901c9..288991c3 100644--- a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt+++ b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt@@ -1,6 +1,11 @@package com.streamvault.data.parserimport com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.test.runTestimport org.junit.Beforeimport org.junit.Test@@ -16,6 +21,7 @@ import org.junit.Test* Time reference: 2025-01-01 12:00:00 UTC = 1_735_732_800_000 ms epoch* 2025-01-01 09:00:00 UTC = 1_735_722_000_000 ms epoch*/+@OptIn(ExperimentalCoroutinesApi::class)class XmltvParserTest {private lateinit var parser: XmltvParser@@ -172,4 +178,24 @@ class XmltvParserTest {// Depending on where the parser breaks, we expect 0–2 programs (not a crash)assertThat(programs.size).isAtMost(2)}++ @Test+ fun `parse_sameInstance_isStableAcrossConcurrentCalls`() = runTest {+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000 +0300" stop="20250101130000 +0300" channel="ch1">+ <title>Concurrent Parse</title>+ </programme>+ </tv>+ """.trimIndent()++ val timestamps = (1..64).map {+ async(Dispatchers.Default) {+ parser.parse(xml.byteInputStream()).single().startTime+ }+ }.awaitAll()++ assertThat(timestamps.distinct()).containsExactly(1_735_722_000_000L)+ }}diff --git a/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.ktnew file mode 100644index 00000000..a6d54150--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/EpgRepositoryImplTest.kt@@ -0,0 +1,119 @@+package com.streamvault.data.repository++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.entity.ProgramEntity+import com.streamvault.data.parser.XmltvParser+import com.streamvault.domain.model.Program+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.atLeastOnce+import org.mockito.kotlin.mock+import org.mockito.kotlin.times+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever+import java.util.concurrent.atomic.AtomicInteger++@OptIn(ExperimentalCoroutinesApi::class)+class EpgRepositoryImplTest {++ private val programDao: ProgramDao = mock()+ private val xmltvParser: XmltvParser = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }++ @Test+ fun `refreshEpg serializes concurrent syncs for same provider`() = runTest {+ val firstParserEntered = CompletableDeferred<Unit>()+ val releaseFirstParser = CompletableDeferred<Unit>()+ val secondParserEntered = CompletableDeferred<Unit>()+ val parserCallOrder = AtomicInteger(0)+ val activeParsers = AtomicInteger(0)+ val maxConcurrentParsers = AtomicInteger(0)++ whenever(xmltvParser.parseStreaming(any(), any())).thenAnswer { invocation ->+ val activeCount = activeParsers.incrementAndGet()+ maxConcurrentParsers.updateAndGet { current -> maxOf(current, activeCount) }+ val callIndex = parserCallOrder.incrementAndGet()++ try {+ if (callIndex == 1) {+ firstParserEntered.complete(Unit)+ runBlocking { releaseFirstParser.await() }+ } else {+ secondParserEntered.complete(Unit)+ }++ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(1)+ runBlocking {+ onProgram(+ Program(+ providerId = 7L,+ channelId = "channel-1",+ title = "News",+ description = "",+ startTime = 1_735_722_000_000L,+ endTime = 1_735_725_600_000L,+ lang = "en"+ )+ )+ }+ } finally {+ activeParsers.decrementAndGet()+ }+ }++ val repository = EpgRepositoryImpl(+ programDao = programDao,+ xmltvParser = xmltvParser,+ okHttpClient = okHttpClientReturningXml(),+ transactionRunner = transactionRunner+ )++ val firstRefresh = async { repository.refreshEpg(7L, "https://example.com/epg.xml") }+ firstParserEntered.await()++ val secondRefresh = async { repository.refreshEpg(7L, "https://example.com/epg.xml") }+ delay(100)++ assertThat(secondParserEntered.isCompleted).isFalse()++ releaseFirstParser.complete(Unit)++ assertThat(firstRefresh.await().isSuccess).isTrue()+ assertThat(secondRefresh.await().isSuccess).isTrue()+ assertThat(maxConcurrentParsers.get()).isEqualTo(1)++ val insertedPrograms = argumentCaptor<List<ProgramEntity>>()+ verify(programDao, atLeastOnce()).insertAll(insertedPrograms.capture())+ assertThat(insertedPrograms.allValues.flatten()).isNotEmpty()+ verify(programDao, times(2)).moveToProvider(-7L, 7L)+ }++ private fun okHttpClientReturningXml(): OkHttpClient =+ OkHttpClient.Builder()+ .addInterceptor { chain ->+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body("<tv></tv>".toResponseBody("application/xml".toMediaType()))+ .build()+ }+ .build()+}\ No newline at end of filediff --git a/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.ktnew file mode 100644index 00000000..086141ce--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/FavoriteRepositoryImplTest.kt@@ -0,0 +1,75 @@+package com.streamvault.data.repository++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.FavoriteDao+import com.streamvault.data.local.dao.VirtualGroupDao+import com.streamvault.data.local.entity.FavoriteEntity+import com.streamvault.domain.model.ContentType+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.emptyFlow+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.argumentCaptor+import org.mockito.kotlin.doAnswer+import org.mockito.kotlin.mock+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++@OptIn(ExperimentalCoroutinesApi::class)+class FavoriteRepositoryImplTest {++ private val favoriteDao: FavoriteDao = mock()+ private val virtualGroupDao: VirtualGroupDao = mock {+ on { getByType(any()) } doAnswer { emptyFlow() }+ }++ @Test+ fun `addFavorite runs max-position lookup and insert in one transaction`() = runTest {+ var inTransaction = false+ var getMaxInsideTransaction = false+ var insertInsideTransaction = false++ val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T {+ check(!inTransaction)+ inTransaction = true+ return try {+ block()+ } finally {+ inTransaction = false+ }+ }+ }++ whenever(favoriteDao.getMaxPosition(null)).thenAnswer {+ getMaxInsideTransaction = inTransaction+ 4+ }+ whenever(favoriteDao.insert(any())).thenAnswer {+ insertInsideTransaction = inTransaction+ Unit+ }++ val repository = FavoriteRepositoryImpl(+ favoriteDao = favoriteDao,+ virtualGroupDao = virtualGroupDao,+ transactionRunner = transactionRunner+ )++ val result = repository.addFavorite(+ contentId = 42L,+ contentType = ContentType.LIVE,+ groupId = null+ )++ assertThat(result.isSuccess).isTrue()+ assertThat(getMaxInsideTransaction).isTrue()+ assertThat(insertInsideTransaction).isTrue()++ val favoriteCaptor = argumentCaptor<FavoriteEntity>()+ verify(favoriteDao).insert(favoriteCaptor.capture())+ assertThat(favoriteCaptor.firstValue.position).isEqualTo(5)+ }+}\ No newline at end of filediff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex 906af707..638d589d 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -38,6 +38,7 @@ import android.os.Handlerimport android.os.Looperimport android.os.SystemClockimport android.util.Log+import android.graphics.Color as AndroidColorimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.*import kotlinx.coroutines.flow.*@@ -85,7 +86,7 @@ class Media3PlayerEngine @Inject constructor(AudioManager.AUDIOFOCUS_GAIN -> {hasAudioFocus = trueisDucked = false- exoPlayer?.volume = currentVolume+ applyPlayerVolume()if (shouldResumeOnAudioFocusGain) {shouldResumeOnAudioFocusGain = falseexoPlayer?.playWhenReady = true@@ -94,7 +95,7 @@ class Media3PlayerEngine @Inject constructor(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {isDucked = true- exoPlayer?.volume = (currentVolume * 0.2f).coerceAtLeast(0.05f)+ applyPlayerVolume()}AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {@@ -102,7 +103,7 @@ class Media3PlayerEngine @Inject constructor(isDucked = falseshouldResumeOnAudioFocusGain = exoPlayer?.isPlaying == trueexoPlayer?.playWhenReady = false- exoPlayer?.volume = currentVolume+ applyPlayerVolume()}AudioManager.AUDIOFOCUS_LOSS -> {@@ -110,7 +111,7 @@ class Media3PlayerEngine @Inject constructor(isDucked = falseshouldResumeOnAudioFocusGain = falseexoPlayer?.playWhenReady = false- exoPlayer?.volume = currentVolume+ applyPlayerVolume()}}}@@ -156,6 +157,18 @@ class Media3PlayerEngine @Inject constructor(private val _mediaTitle = MutableStateFlow<String?>(null)override val mediaTitle: StateFlow<String?> = _mediaTitle.asStateFlow()+ private fun effectiveVolume(): Float {+ return when {+ _isMuted.value -> 0f+ isDucked -> (currentVolume * 0.2f).coerceAtLeast(0.05f)+ else -> currentVolume+ }+ }++ private fun applyPlayerVolume() {+ exoPlayer?.volume = effectiveVolume()+ }+private fun getOrCreatePlayer(): ExoPlayer {return exoPlayer ?: createPlayer().also {exoPlayer = it@@ -392,6 +405,7 @@ class Media3PlayerEngine @Inject constructor(_error.tryEmit(null)_playerStats.value = PlayerStats() // reset stats_mediaTitle.value = null+ applyPlayerVolume()// If we already preloaded this exact stream, use the cached sourceval mediaSource = if (preloadedStreamInfo?.url == streamInfo.url && preloadedSource != null) {@@ -534,23 +548,36 @@ class Media3PlayerEngine @Inject constructor(override fun setVolume(volume: Float) {currentVolume = volume.coerceIn(0f, 1f)- _isMuted.value = false- exoPlayer?.volume = if (isDucked) {- (currentVolume * 0.2f).coerceAtLeast(0.05f)- } else {- currentVolume+ if (currentVolume > 0f) {+ volumeBeforeMute = currentVolume+ _isMuted.value = false}+ applyPlayerVolume()}- override fun toggleMute() {- if (_isMuted.value) {- _isMuted.value = false- exoPlayer?.volume = volumeBeforeMute- } else {- volumeBeforeMute = currentVolume.coerceAtLeast(0.1f)+ override fun setMuted(muted: Boolean) {+ if (muted == _isMuted.value) {+ applyPlayerVolume()+ return+ }++ if (muted) {+ if (currentVolume > 0f) {+ volumeBeforeMute = currentVolume.coerceAtLeast(0.1f)+ }_isMuted.value = true- exoPlayer?.volume = 0f+ } else {+ _isMuted.value = false+ if (currentVolume <= 0f) {+ currentVolume = volumeBeforeMute.coerceIn(0.1f, 1f)+ }}++ applyPlayerVolume()+ }++ override fun toggleMute() {+ setMuted(!_isMuted.value)}override fun setScrubbingMode(enabled: Boolean) {@@ -724,16 +751,25 @@ class Media3PlayerEngine @Inject constructor(override fun createRenderView(context: Context, resizeMode: PlayerSurfaceResizeMode): View {return PlayerView(context).apply {useController = false+ setShutterBackgroundColor(AndroidColor.TRANSPARENT)+ setKeepContentOnPlayerReset(true)setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER)- player = exoPlayer+ enableComposeSurfaceSyncWorkaroundIfAvailable()applyResizeMode(resizeMode)}}override fun bindRenderView(renderView: View, resizeMode: PlayerSurfaceResizeMode) {val playerView = renderView as? PlayerView ?: return- if (playerView.player !== exoPlayer) {- playerView.player = exoPlayer+ val player = getOrCreatePlayer()+ playerView.enableComposeSurfaceSyncWorkaroundIfAvailable()+ if (playerView.player !== player) {+ playerView.player = player+ } else {+ // Compose can keep the same PlayerView instance while its underlying surface is recreated.+ // Reattaching the player forces Media3 to reconnect video output to the fresh surface.+ playerView.player = null+ playerView.player = player}playerView.applyResizeMode(resizeMode)}@@ -746,11 +782,18 @@ class Media3PlayerEngine @Inject constructor(}}+ private fun PlayerView.enableComposeSurfaceSyncWorkaroundIfAvailable() {+ runCatching {+ javaClass.getMethod("setEnableComposeSurfaceSyncWorkaround", Boolean::class.javaPrimitiveType)+ .invoke(this, true)+ }+ }+private fun requestAudioFocusIfNeeded(): Boolean {if (hasAudioFocus) {if (isDucked) {isDucked = false- exoPlayer?.volume = currentVolume+ applyPlayerVolume()}return true}@@ -762,7 +805,7 @@ class Media3PlayerEngine @Inject constructor(return false}isDucked = false- exoPlayer?.volume = currentVolume+ applyPlayerVolume()return true}diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex d17abcf1..00f3ca4b 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -38,6 +38,7 @@ interface PlayerEngine {fun seekBackward(ms: Long = 10_000)fun setDecoderMode(mode: DecoderMode)fun setVolume(volume: Float)+ fun setMuted(muted: Boolean)fun selectAudioTrack(trackId: String)fun selectSubtitleTrack(trackId: String?) // null to disable subtitlesfun release()