StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Refactor UI and sync helpers
David Nashashea9ac92a2ee2
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex 0e810d07..a3294142 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -242,8 +242,11 @@ fun AppNavigation(mainActivity: MainActivity) {if (currentRoute == route || currentRoute?.startsWith("$route?") == true) returnnavController.navigate(route) {- popUpTo(Routes.HOME)+ popUpTo(navController.graph.startDestinationId) {+ saveState = true+ }launchSingleTop = true+ restoreState = true}}@@ -554,12 +557,13 @@ fun AppNavigation(mainActivity: MainActivity) {episodeNumber = playerRequest?.episodeNumber,onBack = {val route = playerRequest?.returnRoute- if (navController.previousBackStackEntry != null) {- navController.popBackStack()+ if (!route.isNullOrBlank() && navController.popBackStack(route, false)) {+ Unit} else if (!route.isNullOrBlank()) {navController.navigate(route) {popUpTo(Routes.PLAYER) { inclusive = true }launchSingleTop = true+ restoreState = true}} else {navController.popBackStack()@@ -584,10 +588,16 @@ fun AppNavigation(mainActivity: MainActivity) {)) { backStackEntry ->val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }+ val movieId = backStackEntry.arguments?.getLong("movieId") ?: -1Lcom.streamvault.app.ui.screens.movies.MovieDetailScreen(onPlay = { movie ->navController.navigateToPlayer(- Routes.moviePlayer(movie).copy(returnRoute = returnRoute)+ Routes.moviePlayer(movie).copy(+ returnRoute = Routes.movieDetail(+ movieId = movie.id.takeIf { it > 0L } ?: movieId,+ returnRoute = returnRoute+ )+ ))},onBack = {@@ -611,10 +621,16 @@ fun AppNavigation(mainActivity: MainActivity) {)) { backStackEntry ->val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }+ val seriesId = backStackEntry.arguments?.getLong("seriesId") ?: -1Lcom.streamvault.app.ui.screens.series.SeriesDetailScreen(onEpisodeClick = { episode ->navController.navigateToPlayer(- Routes.episodePlayer(episode).copy(returnRoute = returnRoute)+ Routes.episodePlayer(episode).copy(+ returnRoute = Routes.seriesDetail(+ seriesId = episode.seriesId.takeIf { it > 0L } ?: seriesId,+ returnRoute = returnRoute+ )+ ))},onBack = {diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.ktindex f52c19d8..e83204df 100644--- a/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputChannelSyncManager.kt@@ -20,6 +20,8 @@ import com.streamvault.domain.repository.ProviderRepositoryimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport javax.inject.Injectimport javax.inject.Singleton@@ -39,37 +41,41 @@ class TvInputChannelSyncManager @Inject constructor(}suspend fun refreshTvInputCatalogResult(): Result<Unit> = withContext(Dispatchers.IO) {- runCatching {- if (!context.isTelevisionDevice()) {- return@runCatching- }- val provider = providerRepository.getActiveProvider().first()- if (provider == null) {- deleteManagedChannels()- return@runCatching- }+ syncMutex.withLock {+ runCatching {+ if (!context.isTelevisionDevice()) {+ return@runCatching+ }+ val provider = providerRepository.getActiveProvider().first()+ if (provider == null) {+ deleteManagedChannels()+ return@runCatching+ }- val channels = channelRepository.getChannels(provider.id).first()- val existingChannelIds = loadExistingChannels()- val targetKeys = channels.mapTo(mutableSetOf(), ::channelKey)-- existingChannelIds- .filterKeys { it !in targetKeys }- .values- .forEach(::deleteChannel)-- val programsByEpgId = loadPrograms(provider.id, channels)-- channels.forEach { channel ->- val key = channelKey(channel)- val channelId = existingChannelIds[key] ?: insertChannel(provider.id, channel) ?: return@forEach- updateChannel(channelId, provider.id, channel)- replacePrograms(- channelId = channelId,- programs = programsByEpgId[channel.epgChannelId].orEmpty(),- providerId = provider.id,- channel = channel- )+ val channels = channelRepository.getChannels(provider.id).first()+ val existingChannelIds = loadExistingChannels().toMutableMap()+ val targetKeys = channels.mapTo(mutableSetOf(), ::channelKey)++ existingChannelIds+ .filterKeys { it !in targetKeys }+ .values+ .forEach(::deleteChannel)++ val programsByEpgId = loadPrograms(provider.id, channels)++ channels.forEach { channel ->+ val key = channelKey(channel)+ val channelId = ensureChannel(context.contentResolver, existingChannelIds[key], provider.id, channel)+ ?: return@forEach+ existingChannelIds[key] = channelId+ replacePrograms(+ channelId = channelId,+ programs = programsByEpgId[channel.epgChannelId].orEmpty(),+ providerId = provider.id,+ channel = channel,+ existingChannelIds = existingChannelIds+ )+ }}}}@@ -119,19 +125,45 @@ class TvInputChannelSyncManager @Inject constructor(return ContentUris.parseId(uri)}- private fun updateChannel(channelId: Long, providerId: Long, channel: Channel) {- context.contentResolver.update(+ private fun updateChannel(channelId: Long, providerId: Long, channel: Channel): Boolean {+ val rows = context.contentResolver.update(ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId),buildChannelValues(providerId, channel),null,null)+ return rows > 0 && channelExists(context.contentResolver, channelId)}- private fun replacePrograms(channelId: Long, programs: List<Program>, providerId: Long, channel: Channel) {+ private fun ensureChannel(+ resolver: ContentResolver,+ existingChannelId: Long?,+ providerId: Long,+ channel: Channel+ ): Long? {+ val refreshedId = existingChannelId+ ?.takeIf { channelExists(resolver, it) }+ ?.takeIf { updateChannel(it, providerId, channel) }+ return refreshedId ?: insertChannel(providerId, channel)+ }++ private fun replacePrograms(+ channelId: Long,+ programs: List<Program>,+ providerId: Long,+ channel: Channel,+ existingChannelIds: MutableMap<String, Long>+ ) {val resolver = context.contentResolver+ var activeChannelId = channelId++ if (!channelExists(resolver, activeChannelId)) {+ activeChannelId = ensureChannel(resolver, null, providerId, channel) ?: return+ existingChannelIds[channelKey(channel)] = activeChannelId+ }+resolver.query(- TvContract.buildProgramsUriForChannel(channelId),+ TvContract.buildProgramsUriForChannel(activeChannelId),arrayOf(BaseColumns._ID),null,null,@@ -151,13 +183,36 @@ class TvInputChannelSyncManager @Inject constructor(.sortedBy { it.startTime }.take(MAX_PROGRAMS_PER_CHANNEL).forEach { program ->- resolver.insert(- TvContract.Programs.CONTENT_URI,- buildProgramValues(channelId, providerId, channel, program)- )+ try {+ resolver.insert(+ TvContract.Programs.CONTENT_URI,+ buildProgramValues(activeChannelId, providerId, channel, program)+ )+ } catch (throwable: Throwable) {+ if (!channelExists(resolver, activeChannelId)) {+ val recoveredChannelId = ensureChannel(resolver, null, providerId, channel) ?: return@forEach+ existingChannelIds[channelKey(channel)] = recoveredChannelId+ activeChannelId = recoveredChannelId+ resolver.insert(+ TvContract.Programs.CONTENT_URI,+ buildProgramValues(activeChannelId, providerId, channel, program)+ )+ } else {+ throw throwable+ }+ }}}+ private fun channelExists(resolver: ContentResolver, channelId: Long): Boolean =+ resolver.query(+ ContentUris.withAppendedId(TvContract.Channels.CONTENT_URI, channelId),+ arrayOf(BaseColumns._ID),+ null,+ null,+ null+ )?.use { it.moveToFirst() } == true+private fun buildChannelValues(providerId: Long, channel: Channel): ContentValues = ContentValues().apply {put(CHANNEL_COLUMN_INPUT_ID, inputId())put(CHANNEL_COLUMN_TYPE, TvContract.Channels.TYPE_OTHER)@@ -238,5 +293,6 @@ class TvInputChannelSyncManager @Inject constructor(const val PROGRAM_LOOKBACK_MS = 3 * 60 * 60 * 1000Lconst val PROGRAM_LOOKAHEAD_MS = 18 * 60 * 60 * 1000Lconst val ENTRY_SEPARATOR = ":"+ val syncMutex = Mutex()}-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.ktnew file mode 100644index 00000000..ca349479--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgControlComponents.kt@@ -0,0 +1,710 @@+package com.streamvault.app.ui.screens.epg++import android.view.inputmethod.InputMethodManager+import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequester+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Search+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusProperties+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.ui.components.SelectionChip+import com.streamvault.app.ui.components.SelectionChipRow+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import java.text.SimpleDateFormat+import java.util.Calendar+import java.util.Date+import java.util.Locale+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++@Composable+internal fun rememberGuideNow(): Long {+ val currentTime by produceState(initialValue = System.currentTimeMillis()) {+ while (true) {+ value = System.currentTimeMillis()+ delay(30_000L)+ }+ }+ return currentTime+}++@Composable+internal fun GuideDensityRow(+ selectedDensity: GuideDensity,+ onDensitySelected: (GuideDensity) -> Unit+) {+ SelectionChipRow(+ title = stringResource(R.string.epg_density_label),+ subtitle = stringResource(R.string.epg_density_subtitle),+ chips = listOf(+ SelectionChip(+ key = GuideDensity.COMPACT.name,+ label = stringResource(R.string.epg_density_compact),+ supportingText = stringResource(R.string.epg_density_compact_hint)+ ),+ SelectionChip(+ key = GuideDensity.COMFORTABLE.name,+ label = stringResource(R.string.epg_density_comfortable),+ supportingText = stringResource(R.string.epg_density_comfortable_hint)+ ),+ SelectionChip(+ key = GuideDensity.CINEMATIC.name,+ label = stringResource(R.string.epg_density_cinematic),+ supportingText = stringResource(R.string.epg_density_cinematic_hint)+ )+ ),+ selectedKey = selectedDensity.name,+ onChipSelected = { key ->+ GuideDensity.entries.firstOrNull { it.name == key }?.let(onDensitySelected)+ }+ )+}++@Composable+internal fun GuideProgramSearchRow(+ query: String,+ onQueryChange: (String) -> Unit,+ onClear: () -> Unit,+ onSearch: ((String) -> Unit)? = null,+ focusRequester: FocusRequester? = null,+ autoRequestFocus: Boolean = false,+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),+ showLabel: Boolean = true,+ onSearchFieldActivated: (() -> Unit)? = null+) {+ val resolvedFocusRequester = focusRequester ?: remember { FocusRequester() }+ var localQuery by rememberSaveable { mutableStateOf(query) }+ var refocusToken by rememberSaveable { mutableStateOf(0) }++ LaunchedEffect(query) {+ if (query != localQuery) {+ localQuery = query+ }+ }++ LaunchedEffect(localQuery) {+ if (localQuery == query) return@LaunchedEffect+ if (localQuery.isBlank()) {+ onQueryChange("")+ return@LaunchedEffect+ }+ delay(250)+ if (localQuery != query) {+ onQueryChange(localQuery)+ }+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(contentPadding)+ ) {+ if (showLabel) {+ Text(+ text = stringResource(R.string.epg_search_label),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ Spacer(modifier = Modifier.height(8.dp))+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ GuideSearchField(+ value = localQuery,+ onValueChange = { localQuery = it },+ placeholder = stringResource(R.string.epg_search_placeholder),+ modifier = Modifier.weight(1f),+ focusRequester = resolvedFocusRequester,+ autoRequestFocus = autoRequestFocus,+ refocusToken = refocusToken,+ onSearch = { onSearch?.invoke(localQuery.trim()) },+ onActivated = onSearchFieldActivated+ )+ Box(modifier = Modifier.widthIn(min = 104.dp), contentAlignment = Alignment.CenterEnd) {+ if (localQuery.isNotBlank()) {+ GuideShortcutChip(+ label = stringResource(R.string.epg_clear_search),+ onClick = {+ localQuery = ""+ onClear()+ refocusToken += 1+ }+ )+ }+ }+ }+ }+}++@Composable+internal fun GuideSearchField(+ value: String,+ onValueChange: (String) -> Unit,+ placeholder: String,+ modifier: Modifier = Modifier,+ focusRequester: FocusRequester = remember { FocusRequester() },+ autoRequestFocus: Boolean = false,+ refocusToken: Int = 0,+ onSearch: ((String) -> Unit)? = null,+ onActivated: (() -> Unit)? = null+) {+ val isTelevisionDevice = rememberIsTelevisionDevice()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var textFieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ val focusManager = LocalFocusManager.current+ val keyboardController = LocalSoftwareKeyboardController.current+ val view = LocalView.current+ val context = LocalContext.current+ val coroutineScope = rememberCoroutineScope()+ val inputFocusRequester = remember { FocusRequester() }+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ var pendingKeyboardRequest by remember { mutableStateOf(0) }+ val inputMethodManager = remember(context) {+ context.getSystemService(InputMethodManager::class.java)+ }+ val isFocused = hasContainerFocus || hasInputFocus++ fun requestBringIntoView(delayMillis: Long = 0L) {+ coroutineScope.launch {+ if (delayMillis > 0) {+ delay(delayMillis)+ }+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ fun requestKeyboard() {+ if (!isTelevisionDevice) {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ view.post {+ val focusedView = view.findFocus() ?: view+ focusedView.requestFocus()+ keyboardController?.show()+ inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)+ }+ onActivated?.invoke()+ requestBringIntoView()+ requestBringIntoView(180)+ return+ }+ acceptsInput = true+ pendingKeyboardRequest += 1+ onActivated?.invoke()+ requestBringIntoView()+ }++ LaunchedEffect(autoRequestFocus) {+ if (autoRequestFocus) {+ focusRequester.requestFocus()+ }+ }++ LaunchedEffect(refocusToken) {+ if (refocusToken > 0) {+ focusRequester.requestFocus()+ }+ }++ LaunchedEffect(pendingKeyboardRequest) {+ if (!isTelevisionDevice || pendingKeyboardRequest <= 0) return@LaunchedEffect+ inputFocusRequester.requestFocus()+ delay(80)+ view.post {+ val focusedView = view.findFocus() ?: view+ focusedView.requestFocus()+ keyboardController?.show()+ inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)+ }+ requestBringIntoView(120)+ }++ LaunchedEffect(value) {+ if (value != textFieldValue.text) {+ val coercedSelectionStart = textFieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = textFieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = textFieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ textFieldValue = textFieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ TvClickableSurface(+ onClick = { requestKeyboard() },+ modifier = modifier+ .height(40.dp)+ .focusRequester(focusRequester)+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusChanged { hasContainerFocus = it.isFocused },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isFocused) SurfaceHighlight else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight,+ contentColor = OnSurface,+ focusedContentColor = OnSurface+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(10.dp)+ )+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 12.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ androidx.tv.material3.Icon(+ imageVector = Icons.Default.Search,+ contentDescription = null,+ tint = if (isFocused) Primary else OnSurfaceDim+ )+ Box(+ modifier = Modifier.weight(1f),+ contentAlignment = Alignment.CenterStart+ ) {+ if (value.isBlank()) {+ Text(+ text = placeholder,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ BasicTextField(+ value = textFieldValue,+ onValueChange = { updatedValue ->+ textFieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(inputFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = textFieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ val nextCursor = (cursor + 1).coerceAtMost(textFieldValue.text.length)+ textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }+ .onFocusChanged {+ if (it.isFocused) {+ hasInputFocus = true+ requestBringIntoView(120)+ } else {+ hasInputFocus = false+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()+ }+ },+ textStyle = MaterialTheme.typography.bodySmall.copy(color = OnSurface),+ singleLine = true,+ cursorBrush = SolidColor(Primary),+ readOnly = isTelevisionDevice && !acceptsInput,+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ keyboardActions = KeyboardActions(onSearch = {+ focusManager.clearFocus(force = true)+ acceptsInput = false+ keyboardController?.hide()+ onSearch?.invoke(textFieldValue.text.trim())+ })+ )+ }+ }+ }+}++@Composable+internal fun GuideModeRow(+ selectedMode: GuideChannelMode,+ onModeSelected: (GuideChannelMode) -> Unit+) {+ SelectionChipRow(+ title = stringResource(R.string.epg_mode_label),+ subtitle = stringResource(R.string.epg_mode_subtitle),+ chips = listOf(+ SelectionChip(+ key = GuideChannelMode.ALL.name,+ label = stringResource(R.string.epg_mode_all),+ supportingText = stringResource(R.string.epg_mode_all_hint)+ ),+ SelectionChip(+ key = GuideChannelMode.ANCHORED.name,+ label = stringResource(R.string.epg_mode_anchored),+ supportingText = stringResource(R.string.epg_mode_anchored_hint)+ ),+ SelectionChip(+ key = GuideChannelMode.ARCHIVE_READY.name,+ label = stringResource(R.string.epg_mode_archive),+ supportingText = stringResource(R.string.epg_mode_archive_hint)+ )+ ),+ selectedKey = selectedMode.name,+ onChipSelected = { key ->+ GuideChannelMode.entries+ .firstOrNull { it.name == key }+ ?.let(onModeSelected)+ }+ )+}++@Composable+internal fun GuideTimeControlsRow(+ onJumpToPreviousDay: () -> Unit,+ onPageBackward: () -> Unit,+ onJumpBackwardHalfHour: () -> Unit,+ onJumpBackward: () -> Unit,+ onJumpToNow: () -> Unit,+ onJumpForwardHalfHour: () -> Unit,+ onJumpForward: () -> Unit,+ onPageForward: () -> Unit,+ onJumpToPrimeTime: () -> Unit,+ onJumpToTomorrow: () -> Unit,+ onJumpToNextDay: () -> Unit,+ firstChipFocusRequester: FocusRequester? = null,+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),+ showLabel: Boolean = true+) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(contentPadding)+ ) {+ if (showLabel) {+ Text(+ text = stringResource(R.string.epg_time_controls),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ Spacer(modifier = Modifier.height(8.dp))+ }+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ item {+ GuideShortcutChip(+ modifier = firstChipFocusRequester?.let { Modifier.focusRequester(it) } ?: Modifier,+ label = stringResource(R.string.epg_previous_day),+ onClick = onJumpToPreviousDay+ )+ }+ item { GuideShortcutChip(label = stringResource(R.string.epg_page_back), onClick = onPageBackward) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back_half_hour), onClick = onJumpBackwardHalfHour) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back), onClick = onJumpBackward) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_now), onClick = onJumpToNow) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward_half_hour), onClick = onJumpForwardHalfHour) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward), onClick = onJumpForward) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_page_forward), onClick = onPageForward) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_prime_time), onClick = onJumpToPrimeTime) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_tomorrow), onClick = onJumpToTomorrow) }+ item { GuideShortcutChip(label = stringResource(R.string.epg_next_day), onClick = onJumpToNextDay) }+ }+ }+}++@Composable+internal fun GuideDayRow(+ selectedDayStart: Long,+ onDaySelected: (Long) -> Unit,+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 4.dp),+ showLabel: Boolean = true+) {+ val dayFormat = remember { SimpleDateFormat("EEE d MMM", Locale.getDefault()) }+ val dayAnchors = remember(selectedDayStart) {+ (-1L..3L).map { offset ->+ selectedDayStart + (offset * EpgViewModel.DAY_SHIFT_MS)+ }+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(contentPadding)+ ) {+ if (showLabel) {+ Text(+ text = stringResource(R.string.epg_day_selector_label),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ Spacer(modifier = Modifier.height(8.dp))+ }+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ items(dayAnchors, key = { it }) { dayStart ->+ val isSelected = dayStart == selectedDayStart+ TvClickableSurface(+ onClick = { onDaySelected(dayStart) },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight,+ contentColor = if (isSelected) Primary else OnSurface,+ focusedContentColor = OnSurface+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(999.dp)+ )+ )+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(text = dayRelativeLabel(dayStart), style = MaterialTheme.typography.labelLarge)+ Text(+ text = dayFormat.format(Date(dayStart)),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ }+}++@Composable+internal fun GuideViewOptionsRow(+ showScheduledOnly: Boolean,+ onToggleScheduledOnly: () -> Unit+) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 24.dp, vertical = 4.dp)+ ) {+ Text(+ text = stringResource(R.string.epg_view_options_label),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ Spacer(modifier = Modifier.height(8.dp))+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ item {+ TvClickableSurface(+ onClick = onToggleScheduledOnly,+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (showScheduledOnly) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight,+ contentColor = if (showScheduledOnly) Primary else OnSurface,+ focusedContentColor = OnSurface+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(999.dp)+ )+ )+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = stringResource(+ if (showScheduledOnly) R.string.epg_view_scheduled_only_on+ else R.string.epg_view_scheduled_only_off+ ),+ style = MaterialTheme.typography.labelLarge+ )+ Text(+ text = stringResource(R.string.epg_view_scheduled_only_hint),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ }+}++@Composable+internal fun GuideFavoritesRow(+ showFavoritesOnly: Boolean,+ onToggleFavoritesOnly: () -> Unit+) {+ SelectionChipRow(+ title = stringResource(R.string.epg_favorites_filter_title),+ subtitle = stringResource(R.string.epg_favorites_filter_subtitle),+ chips = listOf(+ SelectionChip(+ key = "all",+ label = stringResource(R.string.epg_favorites_filter_all),+ supportingText = stringResource(R.string.epg_favorites_filter_all_hint)+ ),+ SelectionChip(+ key = "favorites",+ label = stringResource(R.string.epg_favorites_filter_favorites),+ supportingText = stringResource(R.string.epg_favorites_filter_favorites_hint)+ )+ ),+ selectedKey = if (showFavoritesOnly) "favorites" else "all",+ onChipSelected = { key ->+ val shouldShowFavorites = key == "favorites"+ if (shouldShowFavorites != showFavoritesOnly) {+ onToggleFavoritesOnly()+ }+ },+ contentPadding = PaddingValues(horizontal = 24.dp)+ )+}++@Composable+internal fun GuideShortcutChip(+ modifier: Modifier = Modifier,+ label: String,+ onClick: () -> Unit,+ isSelected: Boolean = false+) {+ TvClickableSurface(+ onClick = onClick,+ modifier = modifier,+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight,+ contentColor = if (isSelected) Primary else OnSurface,+ focusedContentColor = OnSurface+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(999.dp)+ )+ )+ ) {+ Text(+ text = label,+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp),+ style = MaterialTheme.typography.labelMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+}++internal fun startOfDay(timestamp: Long): Long {+ val calendar = Calendar.getInstance().apply {+ timeInMillis = timestamp+ set(Calendar.HOUR_OF_DAY, 0)+ set(Calendar.MINUTE, 0)+ set(Calendar.SECOND, 0)+ set(Calendar.MILLISECOND, 0)+ }+ return calendar.timeInMillis+}++@Composable+private fun dayRelativeLabel(dayStart: Long): String {+ val todayStart = remember { startOfDay(System.currentTimeMillis()) }+ return when (dayStart) {+ todayStart - EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_yesterday)+ todayStart -> stringResource(R.string.epg_day_today)+ todayStart + EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_tomorrow)+ else -> {+ val format = remember { SimpleDateFormat("EEE", Locale.getDefault()) }+ format.format(Date(dayStart))+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.ktnew file mode 100644index 00000000..43828533--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgGridComponents.kt@@ -0,0 +1,643 @@+package com.streamvault.app.ui.screens.epg++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.tv.material3.Border+import androidx.tv.material3.ButtonDefaults+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.ChannelLogoBadge+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.model.guideLookupKey+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.app.ui.theme.TextPrimary+import com.streamvault.app.ui.theme.TextSecondary+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Program+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import kotlin.math.max++@Composable+internal fun GuideMessageState(+ modifier: Modifier = Modifier,+ title: String,+ subtitle: String?,+ actionLabel: String?,+ onAction: (() -> Unit)?+) {+ Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(10.dp),+ modifier = Modifier.padding(horizontal = 32.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleLarge,+ color = OnSurface+ )+ if (!subtitle.isNullOrBlank()) {+ Text(+ text = subtitle,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ }+ if (actionLabel != null && onAction != null) {+ TvButton(+ onClick = onAction,+ colors = ButtonDefaults.colors(+ containerColor = Primary,+ contentColor = Color.White+ )+ ) {+ Text(actionLabel)+ }+ }+ }+ }+}++@Composable+internal fun EpgGrid(+ modifier: Modifier = Modifier,+ channels: List<Channel>,+ favoriteChannelIds: Set<Long>,+ programsByChannel: Map<String, List<Program>>,+ guideWindowStart: Long,+ guideWindowEnd: Long,+ density: GuideDensity,+ now: Long,+ onChannelClick: (Channel) -> Unit,+ onProgramClick: (Channel, Program) -> Unit,+ onChannelFocused: (Channel, Program?, Boolean) -> Unit,+ onProgramFocused: (Channel, Program, Boolean) -> Unit+) {+ val channelRailWidth = 180.dp+ val timelineGap = 4.dp+ val rowHeight = when (density) {+ GuideDensity.COMPACT -> 38.dp+ GuideDensity.COMFORTABLE -> 44.dp+ GuideDensity.CINEMATIC -> 52.dp+ }+ val horizontalScrollState = rememberScrollState()++ BoxWithConstraints(+ modifier = modifier+ .fillMaxSize()+ .padding(horizontal = 12.dp, vertical = 2.dp)+ ) {+ val timelineViewportWidth = (maxWidth - channelRailWidth - timelineGap).coerceAtLeast(640.dp)+ val totalDuration = (guideWindowEnd - guideWindowStart).coerceAtLeast(1L)+ val visibleDurationMs = 3 * 60 * 60 * 1000L+ val calculatedTimelineWidth = timelineViewportWidth * (totalDuration.toFloat() / visibleDurationMs.toFloat())+ val totalTimelineWidth = if (calculatedTimelineWidth > timelineViewportWidth) {+ calculatedTimelineWidth+ } else {+ timelineViewportWidth+ }+ val markerStepMs = EpgViewModel.HALF_HOUR_SHIFT_MS++ Column(modifier = Modifier.fillMaxSize()) {+ GuideTimelineHeader(+ windowStart = guideWindowStart,+ windowEnd = guideWindowEnd,+ now = now,+ channelRailWidth = channelRailWidth,+ timelineGap = timelineGap,+ timelineViewportWidth = timelineViewportWidth,+ totalTimelineWidth = totalTimelineWidth,+ markerStepMs = markerStepMs,+ scrollState = horizontalScrollState+ )+ Spacer(modifier = Modifier.height(4.dp))+ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ itemsIndexed(+ items = channels,+ key = { index, channel -> epgChannelKey(channel, index) }+ ) { index, channel ->+ val programs = channel.guideLookupKey()?.let { lookupKey ->+ programsByChannel[lookupKey].orEmpty()+ }.orEmpty()+ val isFirstRow = index == 0+ EpgRow(+ channel = channel,+ isFavorite = channel.id in favoriteChannelIds,+ programs = programs,+ now = now,+ windowStart = guideWindowStart,+ windowEnd = guideWindowEnd,+ channelRailWidth = channelRailWidth,+ timelineGap = timelineGap,+ timelineViewportWidth = timelineViewportWidth,+ totalTimelineWidth = totalTimelineWidth,+ density = density,+ rowHeight = rowHeight,+ markerStepMs = markerStepMs,+ scrollState = horizontalScrollState,+ onChannelClick = { onChannelClick(channel) },+ onChannelFocused = { onChannelFocused(channel, it, isFirstRow) },+ onProgramClick = { program -> onProgramClick(channel, program) },+ onProgramFocused = { program -> onProgramFocused(channel, program, isFirstRow) }+ )+ }+ }+ }+ }+}++@Composable+private fun GuideTimelineHeader(+ windowStart: Long,+ windowEnd: Long,+ now: Long,+ channelRailWidth: Dp,+ timelineGap: Dp,+ timelineViewportWidth: Dp,+ totalTimelineWidth: Dp,+ markerStepMs: Long,+ scrollState: androidx.compose.foundation.ScrollState+) {+ val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)+ val clampedNow = now.coerceIn(windowStart, windowEnd)+ val elapsedRatio = ((clampedNow - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ val markerLabel = if (now in windowStart..windowEnd) {+ stringResource(R.string.epg_now_marker, hourFormat.format(Date(now)))+ } else {+ stringResource(R.string.epg_outside_window)+ }+ val hourMarkers = buildList {+ var marker = windowStart+ while (marker <= windowEnd) {+ add(marker)+ marker += markerStepMs+ }+ if (lastOrNull() != windowEnd) {+ add(windowEnd)+ }+ }++ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 2.dp),+ verticalAlignment = Alignment.Bottom+ ) {+ Spacer(modifier = Modifier.width(channelRailWidth + timelineGap))+ Column(+ modifier = Modifier.width(timelineViewportWidth),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.epg_timeline_label),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Text(+ text = stringResource(+ R.string.epg_timeline_range_label,+ formatWindowDuration(totalDuration)+ ),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ }+ Box(+ modifier = Modifier+ .width(timelineViewportWidth)+ .height(20.dp)+ ) {+ Row(+ modifier = Modifier+ .width(totalTimelineWidth)+ .horizontalScroll(scrollState)+ ) {+ Box(+ modifier = Modifier+ .width(totalTimelineWidth)+ .height(20.dp)+ ) {+ hourMarkers.forEach { marker ->+ val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ val markerOffset = totalTimelineWidth * markerRatio+ Column(+ modifier = Modifier.padding(start = markerOffset),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = hourFormat.format(Date(marker)),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Box(+ modifier = Modifier+ .width(1.dp)+ .height(8.dp)+ .background(Color.White.copy(alpha = 0.16f))+ )+ }+ }+ if (now in windowStart..windowEnd) {+ Box(+ modifier = Modifier+ .padding(start = totalTimelineWidth * elapsedRatio)+ .width(2.dp)+ .fillMaxHeight()+ .background(Primary)+ )+ }+ }+ }+ }+ Text(+ text = markerLabel,+ style = MaterialTheme.typography.labelSmall,+ color = if (now in windowStart..windowEnd) Primary else OnSurfaceDim+ )+ }+ }+}++@Composable+fun EpgRow(+ channel: Channel,+ isFavorite: Boolean,+ programs: List<Program>,+ now: Long,+ windowStart: Long,+ windowEnd: Long,+ channelRailWidth: Dp,+ timelineGap: Dp,+ timelineViewportWidth: Dp,+ totalTimelineWidth: Dp,+ density: GuideDensity,+ rowHeight: Dp,+ markerStepMs: Long,+ scrollState: androidx.compose.foundation.ScrollState,+ onChannelClick: () -> Unit,+ onChannelFocused: (Program?) -> Unit,+ onProgramClick: (Program) -> Unit,+ onProgramFocused: (Program) -> Unit+) {+ var isFocused by remember { mutableStateOf(false) }+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)+ val currentProgram = programs.firstOrNull { now in it.startTime..it.endTime }+ val channelPaddingVertical = when (density) {+ GuideDensity.COMPACT -> 3.dp+ GuideDensity.COMFORTABLE -> 4.dp+ GuideDensity.CINEMATIC -> 5.dp+ }+ val channelLogoSize = when (density) {+ GuideDensity.COMPACT -> 22.dp+ GuideDensity.COMFORTABLE -> 24.dp+ GuideDensity.CINEMATIC -> 26.dp+ }++ Row(+ modifier = Modifier+ .fillMaxWidth()+ .height(rowHeight),+ verticalAlignment = Alignment.CenterVertically+ ) {+ TvClickableSurface(+ onClick = onChannelClick,+ modifier = Modifier+ .width(channelRailWidth)+ .fillMaxHeight()+ .onFocusChanged {+ if (it.isFocused && !isFocused) {+ onChannelFocused(currentProgram)+ }+ isFocused = it.isFocused+ },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = SurfaceHighlight+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(8.dp)+ )+ )+ ) {+ Row(+ modifier = Modifier+ .padding(horizontal = 7.dp, vertical = channelPaddingVertical)+ .fillMaxSize(),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ ChannelLogoBadge(+ channelName = channel.name,+ logoUrl = channel.logoUrl,+ modifier = Modifier+ .width(channelLogoSize)+ .height(channelLogoSize),+ shape = RoundedCornerShape(6.dp)+ )+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(0.dp)+ ) {+ Text(+ text = "${channel.number}. ${channel.name}",+ style = MaterialTheme.typography.labelLarge,+ color = if (isFocused) TextPrimary else OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ text = currentProgram?.title ?: stringResource(R.string.epg_no_schedule_short),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ if (isFavorite || channel.catchUpSupported) {+ Box(+ modifier = Modifier+ .background(+ color = Primary.copy(alpha = 0.16f),+ shape = CircleShape+ )+ .padding(horizontal = 5.dp, vertical = 1.dp)+ ) {+ Text(+ text = if (channel.catchUpSupported) stringResource(R.string.player_archive_badge) else stringResource(R.string.epg_favorite_badge),+ style = MaterialTheme.typography.labelSmall,+ color = Primary,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+ }++ Spacer(modifier = Modifier.width(timelineGap))++ Box(+ modifier = Modifier+ .width(timelineViewportWidth)+ .fillMaxHeight()+ .background(SurfaceElevated, RoundedCornerShape(8.dp))+ .clip(RoundedCornerShape(8.dp))+ ) {+ Row(+ modifier = Modifier+ .width(totalTimelineWidth)+ .horizontalScroll(scrollState)+ ) {+ Box(+ modifier = Modifier+ .width(totalTimelineWidth)+ .fillMaxHeight()+ ) {+ val markers = remember(windowStart, windowEnd, markerStepMs) {+ buildList {+ var marker = windowStart+ while (marker <= windowEnd) {+ add(marker)+ marker += markerStepMs+ }+ }+ }+ markers.forEach { marker ->+ val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ Box(+ modifier = Modifier+ .padding(start = totalTimelineWidth * markerRatio)+ .width(1.dp)+ .fillMaxHeight()+ .background(Color.White.copy(alpha = 0.08f))+ )+ }+ if (now in windowStart..windowEnd) {+ val nowRatio = ((now - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ Box(+ modifier = Modifier+ .padding(start = totalTimelineWidth * nowRatio)+ .width(2.dp)+ .fillMaxHeight()+ .background(Primary)+ )+ }+ if (programs.isEmpty()) {+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Text(stringResource(R.string.epg_no_schedule_short), color = OnSurfaceDim)+ }+ } else {+ programs.forEach { program ->+ ProgramItem(+ program = program,+ density = density,+ isCurrent = now in program.startTime until program.endTime,+ now = now,+ windowStart = windowStart,+ windowEnd = windowEnd,+ totalTimelineWidth = totalTimelineWidth,+ onClick = { onProgramClick(program) },+ onFocused = { onProgramFocused(program) }+ )+ }+ }+ }+ }+ }+ }+}++@Composable+fun ProgramItem(+ program: Program,+ density: GuideDensity,+ isCurrent: Boolean,+ now: Long,+ windowStart: Long,+ windowEnd: Long,+ totalTimelineWidth: Dp,+ onClick: () -> Unit,+ onFocused: () -> Unit+) {+ var isFocused by remember { mutableStateOf(false) }++ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ val startStr = format.format(Date(program.startTime))+ val endStr = format.format(Date(program.endTime))+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)+ val visibleStart = max(program.startTime, windowStart)+ val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))+ val startRatio = ((visibleStart - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)+ val itemStart = totalTimelineWidth * startRatio+ val minimumItemWidth = when (density) {+ GuideDensity.COMPACT -> 40.dp+ GuideDensity.COMFORTABLE -> 48.dp+ GuideDensity.CINEMATIC -> 56.dp+ }+ val itemWidth = (totalTimelineWidth * widthRatio).coerceAtLeast(minimumItemWidth)+ val isCompactCell = itemWidth < 148.dp+ val isVeryCompactCell = itemWidth < 116.dp+ val outerVerticalPadding = when (density) {+ GuideDensity.COMPACT -> 2.dp+ GuideDensity.COMFORTABLE -> 2.dp+ GuideDensity.CINEMATIC -> 3.dp+ }+ val innerHorizontalPadding = when {+ isVeryCompactCell -> 5.dp+ isCompactCell -> 6.dp+ else -> 8.dp+ }+ val innerVerticalPadding = when (density) {+ GuideDensity.COMPACT -> 2.dp+ GuideDensity.COMFORTABLE -> 3.dp+ GuideDensity.CINEMATIC -> 4.dp+ }+ val titleStyle = when {+ isVeryCompactCell -> MaterialTheme.typography.labelSmall.copy(+ fontSize = 10.sp,+ lineHeight = 11.sp+ )+ isCompactCell || density == GuideDensity.COMPACT -> MaterialTheme.typography.labelMedium.copy(+ fontSize = 11.sp,+ lineHeight = 12.sp+ )+ else -> MaterialTheme.typography.labelLarge.copy(+ fontSize = 12.sp,+ lineHeight = 14.sp+ )+ }+ val timeStyle = when {+ isCompactCell || density == GuideDensity.COMPACT -> MaterialTheme.typography.labelSmall.copy(+ fontSize = 9.sp,+ lineHeight = 10.sp+ )+ else -> MaterialTheme.typography.labelSmall.copy(+ fontSize = 10.sp,+ lineHeight = 11.sp+ )+ }++ TvClickableSurface(+ onClick = onClick,+ modifier = Modifier+ .padding(start = itemStart, top = outerVerticalPadding, bottom = outerVerticalPadding)+ .width(itemWidth)+ .fillMaxHeight()+ .clip(RoundedCornerShape(8.dp))+ .onFocusChanged {+ if (it.isFocused && !isFocused) {+ onFocused()+ }+ isFocused = it.isFocused+ },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(8.dp)+ )+ )+ ) {+ Column(+ modifier = Modifier+ .padding(horizontal = innerHorizontalPadding, vertical = innerVerticalPadding)+ .fillMaxSize(),+ verticalArrangement = Arrangement.Center+ ) {+ Text(+ text = program.title,+ style = titleStyle,+ color = if (isFocused) TextPrimary else if (isCurrent) Primary else OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ if (!isVeryCompactCell) {+ Text(+ text = "$startStr - $endStr",+ style = timeStyle,+ color = if (isFocused) TextSecondary else OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+}++internal fun formatWindowDuration(durationMs: Long): String {+ val hours = durationMs / (60 * 60 * 1000L)+ val minutes = (durationMs / (60 * 1000L)) % 60+ return if (minutes == 0L) {+ "${hours}h"+ } else {+ "${hours}h ${minutes}m"+ }+}++internal fun epgChannelKey(channel: Channel, index: Int): String {+ val epgId = channel.guideLookupKey().orEmpty()+ return "channel:${channel.id}:${channel.streamId}:${epgId}:${channel.name.trim()}:$index"+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.ktnew file mode 100644index 00000000..b6d792f0--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgHeroComponents.kt@@ -0,0 +1,334 @@+package com.streamvault.app.ui.screens.epg++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.ChannelLogoBadge+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.model.guideLookupKey+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Program+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++internal data class GuideHeroSelection(+ val channel: Channel,+ val program: Program?,+ val isFallbackToChannel: Boolean+)++internal fun resolveGuideHeroSelection(+ uiState: EpgUiState,+ focusedChannel: Channel?,+ focusedProgram: Program?,+ now: Long+): GuideHeroSelection? {+ val resolvedChannel = focusedChannel+ ?.let { current -> uiState.channels.firstOrNull { it.id == current.id } }+ ?: uiState.channels.firstOrNull()+ ?: return null+ val programs = resolvedChannel.guideLookupKey()?.let { lookupKey ->+ uiState.programsByChannel[lookupKey].orEmpty()+ }.orEmpty()+ val resolvedProgram = focusedProgram?.let { focused ->+ programs.firstOrNull {+ it.startTime == focused.startTime &&+ it.endTime == focused.endTime &&+ it.title == focused.title+ }+ } ?: programs.firstOrNull { now in it.startTime until it.endTime } ?: programs.firstOrNull()+ return GuideHeroSelection(+ channel = resolvedChannel,+ program = resolvedProgram,+ isFallbackToChannel = resolvedProgram == null+ )+}++@Composable+internal fun ImmersiveGuideHero(+ selection: GuideHeroSelection?,+ providerLabel: String,+ selectedCategoryName: String,+ isGuideStale: Boolean,+ channelCount: Int,+ channelsWithSchedule: Int,+ lastUpdatedAt: Long?,+ isRefreshing: Boolean,+ modifier: Modifier = Modifier+) {+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ val currentTime = System.currentTimeMillis()+ val lastUpdatedLabel = remember(lastUpdatedAt, currentTime) {+ lastUpdatedAt?.let { updatedAt ->+ val minutes = ((currentTime - updatedAt).coerceAtLeast(0L) / 60_000L).toInt()+ if (minutes <= 0) {+ "Updated just now"+ } else {+ "$minutes min ago"+ }+ }+ }++ Surface(+ modifier = modifier.height(96.dp),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(20.dp)+ ) {+ Row(+ modifier = Modifier+ .fillMaxSize()+ .padding(horizontal = 12.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ val channel = selection?.channel+ ChannelLogoBadge(+ channelName = channel?.name ?: stringResource(R.string.epg_title),+ logoUrl = channel?.logoUrl,+ modifier = Modifier+ .width(54.dp)+ .height(54.dp),+ shape = RoundedCornerShape(12.dp)+ )++ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(1.dp)+ ) {+ val program = selection?.program+ Text(+ text = program?.title ?: channel?.name ?: stringResource(R.string.epg_title),+ style = MaterialTheme.typography.titleMedium.copy(+ fontSize = 15.sp,+ lineHeight = 18.sp+ ),+ color = OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ text = buildString {+ channel?.let { append("${it.number}. ${it.name}") }+ if (providerLabel.isNotBlank()) {+ if (isNotEmpty()) append(" | ")+ append(providerLabel)+ }+ if (selectedCategoryName.isNotBlank()) {+ if (isNotEmpty()) append(" | ")+ append(selectedCategoryName)+ }+ },+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ if (program != null) {+ Text(+ text = "${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",+ style = MaterialTheme.typography.labelSmall.copy(lineHeight = 11.sp),+ color = OnSurface+ )+ if (currentTime in program.startTime until program.endTime) {+ LinearProgressIndicator(+ progress = { ((currentTime - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },+ modifier = Modifier+ .fillMaxWidth()+ .height(4.dp),+ color = Primary,+ trackColor = SurfaceHighlight+ )+ }+ Text(+ text = program.description.ifBlank { stringResource(R.string.epg_hero_no_program_description) },+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ } else {+ Text(+ text = stringResource(R.string.epg_no_schedule),+ style = MaterialTheme.typography.labelLarge,+ color = OnSurface+ )+ Text(+ text = stringResource(R.string.epg_hero_no_schedule_hint),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }++ Column(+ modifier = Modifier.widthIn(min = 176.dp, max = 220.dp),+ verticalArrangement = Arrangement.spacedBy(3.dp)+ ) {+ GuideHeroBadge(text = stringResource(R.string.epg_schedule_summary_short, channelsWithSchedule, channelCount))+ if (isRefreshing) {+ GuideHeroBadge(text = stringResource(R.string.epg_loading))+ }+ if (selection?.program?.hasArchive == true || selection?.channel?.catchUpSupported == true) {+ GuideHeroBadge(+ text = if (selection.program?.hasArchive == true) {+ stringResource(R.string.epg_program_replay_ready)+ } else {+ stringResource(R.string.epg_program_replay_partial)+ },+ highlight = true+ )+ }+ if (isGuideStale) {+ GuideHeroBadge(+ text = stringResource(R.string.epg_stale_short),+ accentColor = Color(0xFFFF6B6B)+ )+ }+ if (!lastUpdatedLabel.isNullOrBlank()) {+ Text(+ text = lastUpdatedLabel,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+}++@Composable+internal fun GuideHeroBadge(+ text: String,+ highlight: Boolean = false,+ accentColor: Color = Primary+) {+ Surface(+ shape = RoundedCornerShape(999.dp),+ colors = SurfaceDefaults.colors(+ containerColor = if (highlight) accentColor.copy(alpha = 0.18f) else SurfaceHighlight+ )+ ) {+ Text(+ text = text,+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),+ style = MaterialTheme.typography.labelMedium,+ color = if (highlight) accentColor else OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+}++@Composable+internal fun GuideToolbarRow(+ selectedCategoryName: String,+ onOpenCategoryPicker: () -> Unit,+ onJumpToNow: () -> Unit,+ onOpenSearch: () -> Unit,+ onOpenOptions: () -> Unit,+ onGuideInteract: () -> Unit,+ modifier: Modifier = Modifier+) {+ Row(+ modifier = modifier,+ horizontalArrangement = Arrangement.spacedBy(5.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ GuideToolbarButton(+ label = selectedCategoryName,+ modifier = Modifier.widthIn(min = 200.dp, max = 280.dp),+ onClick = onOpenCategoryPicker,+ onFocused = onGuideInteract+ )+ GuideToolbarButton(+ label = stringResource(R.string.epg_jump_now),+ onClick = onJumpToNow,+ onFocused = onGuideInteract+ )+ GuideToolbarButton(+ label = stringResource(R.string.epg_search_label),+ onClick = onOpenSearch,+ onFocused = onGuideInteract+ )+ GuideToolbarButton(+ label = stringResource(R.string.epg_options_short),+ onClick = onOpenOptions,+ onFocused = onGuideInteract+ )+ }+}++@Composable+internal fun GuideToolbarButton(+ label: String,+ modifier: Modifier = Modifier,+ onClick: () -> Unit,+ onFocused: () -> Unit+) {+ var focused by remember { mutableStateOf(false) }+ TvClickableSurface(+ onClick = onClick,+ modifier = modifier.onFocusChanged {+ if (it.isFocused && !focused) onFocused()+ focused = it.isFocused+ },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = SurfaceHighlight+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(14.dp)+ )+ )+ ) {+ Text(+ text = label,+ modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.ktindex 8caf58a2..bef7a098 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt@@ -649,2653 +649,7 @@ private fun GuideProviderTroubleshootingCard(}}-@Composable-private fun rememberGuideNow(): Long {- val currentTime by produceState(initialValue = System.currentTimeMillis()) {- while (true) {- value = System.currentTimeMillis()- delay(30_000L)- }- }- return currentTime-}--@Composable-private fun GuideDensityRow(- selectedDensity: GuideDensity,- onDensitySelected: (GuideDensity) -> Unit-) {- SelectionChipRow(- title = stringResource(R.string.epg_density_label),- subtitle = stringResource(R.string.epg_density_subtitle),- chips = listOf(- SelectionChip(- key = GuideDensity.COMPACT.name,- label = stringResource(R.string.epg_density_compact),- supportingText = stringResource(R.string.epg_density_compact_hint)- ),- SelectionChip(- key = GuideDensity.COMFORTABLE.name,- label = stringResource(R.string.epg_density_comfortable),- supportingText = stringResource(R.string.epg_density_comfortable_hint)- ),- SelectionChip(- key = GuideDensity.CINEMATIC.name,- label = stringResource(R.string.epg_density_cinematic),- supportingText = stringResource(R.string.epg_density_cinematic_hint)- )- ),- selectedKey = selectedDensity.name,- onChipSelected = { key ->- GuideDensity.entries.firstOrNull { it.name == key }?.let(onDensitySelected)- }- )-}--@Composable-private fun GuideProgramSearchRow(- query: String,- onQueryChange: (String) -> Unit,- onClear: () -> Unit,- onSearch: ((String) -> Unit)? = null,- focusRequester: FocusRequester? = null,- autoRequestFocus: Boolean = false,- contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),- showLabel: Boolean = true,- onSearchFieldActivated: (() -> Unit)? = null-) {- val resolvedFocusRequester = focusRequester ?: remember { FocusRequester() }- var localQuery by rememberSaveable { mutableStateOf(query) }- var refocusToken by rememberSaveable { mutableStateOf(0) }-- LaunchedEffect(query) {- if (query != localQuery) {- localQuery = query- }- }-- LaunchedEffect(localQuery) {- if (localQuery == query) return@LaunchedEffect- if (localQuery.isBlank()) {- onQueryChange("")- return@LaunchedEffect- }- delay(250)- if (localQuery != query) {- onQueryChange(localQuery)- }- }-- Column(- modifier = Modifier- .fillMaxWidth()- .padding(contentPadding)- ) {- if (showLabel) {- Text(- text = stringResource(R.string.epg_search_label),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- Spacer(modifier = Modifier.height(8.dp))- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- GuideSearchField(- value = localQuery,- onValueChange = { localQuery = it },- placeholder = stringResource(R.string.epg_search_placeholder),- modifier = Modifier.weight(1f),- focusRequester = resolvedFocusRequester,- autoRequestFocus = autoRequestFocus,- refocusToken = refocusToken,- onSearch = { onSearch?.invoke(localQuery.trim()) },- onActivated = onSearchFieldActivated- )- Box(modifier = Modifier.widthIn(min = 104.dp), contentAlignment = Alignment.CenterEnd) {- if (localQuery.isNotBlank()) {- GuideShortcutChip(- label = stringResource(R.string.epg_clear_search),- onClick = {- localQuery = ""- onClear()- refocusToken += 1- }- )- }- }- }- }-}--@Composable-private fun GuideSearchField(- value: String,- onValueChange: (String) -> Unit,- placeholder: String,- modifier: Modifier = Modifier,- focusRequester: FocusRequester = remember { FocusRequester() },- autoRequestFocus: Boolean = false,- refocusToken: Int = 0,- onSearch: ((String) -> Unit)? = null,- onActivated: (() -> Unit)? = null-) {- val isTelevisionDevice = rememberIsTelevisionDevice()- var hasContainerFocus by remember { mutableStateOf(false) }- var hasInputFocus by remember { mutableStateOf(false) }- var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }- var textFieldValue by remember {- mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))- }- val focusManager = LocalFocusManager.current- val keyboardController = LocalSoftwareKeyboardController.current- val view = LocalView.current- val context = LocalContext.current- val coroutineScope = rememberCoroutineScope()- val inputFocusRequester = remember { FocusRequester() }- val bringIntoViewRequester = remember { BringIntoViewRequester() }- var pendingKeyboardRequest by remember { mutableStateOf(0) }- val inputMethodManager = remember(context) {- context.getSystemService(InputMethodManager::class.java)- }- val isFocused = hasContainerFocus || hasInputFocus-- fun requestBringIntoView(delayMillis: Long = 0L) {- coroutineScope.launch {- if (delayMillis > 0) {- kotlinx.coroutines.delay(delayMillis)- }- runCatching { bringIntoViewRequester.bringIntoView() }- }- }-- fun requestKeyboard() {- if (!isTelevisionDevice) {- acceptsInput = true- inputFocusRequester.requestFocus()- view.post {- val focusedView = view.findFocus() ?: view- focusedView.requestFocus()- keyboardController?.show()- inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)- }- onActivated?.invoke()- requestBringIntoView()- requestBringIntoView(180)- return- }- acceptsInput = true- pendingKeyboardRequest += 1- onActivated?.invoke()- requestBringIntoView()- }-- LaunchedEffect(autoRequestFocus) {- if (autoRequestFocus) {- focusRequester.requestFocus()- }- }-- LaunchedEffect(refocusToken) {- if (refocusToken > 0) {- focusRequester.requestFocus()- }- }-- LaunchedEffect(pendingKeyboardRequest) {- if (!isTelevisionDevice || pendingKeyboardRequest <= 0) return@LaunchedEffect- inputFocusRequester.requestFocus()- kotlinx.coroutines.delay(80)- view.post {- val focusedView = view.findFocus() ?: view- focusedView.requestFocus()- keyboardController?.show()- inputMethodManager?.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)- }- requestBringIntoView(120)- }-- LaunchedEffect(value) {- if (value != textFieldValue.text) {- val coercedSelectionStart = textFieldValue.selection.start.coerceIn(0, value.length)- val coercedSelectionEnd = textFieldValue.selection.end.coerceIn(0, value.length)- val coercedComposition = textFieldValue.composition?.let { composition ->- val compositionStart = composition.start.coerceIn(0, value.length)- val compositionEnd = composition.end.coerceIn(0, value.length)- if (compositionStart <= compositionEnd) {- TextRange(compositionStart, compositionEnd)- } else {- null- }- }- textFieldValue = textFieldValue.copy(- text = value,- selection = TextRange(coercedSelectionStart, coercedSelectionEnd),- composition = coercedComposition- )- }- }-- TvClickableSurface(- onClick = {- requestKeyboard()- },- modifier = modifier- .height(40.dp)- .focusRequester(focusRequester)- .bringIntoViewRequester(bringIntoViewRequester)- .onFocusChanged { hasContainerFocus = it.isFocused },- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isFocused) SurfaceHighlight else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(10.dp)- )- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 12.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- androidx.tv.material3.Icon(- imageVector = androidx.compose.material.icons.Icons.Default.Search,- contentDescription = null,- tint = if (isFocused) Primary else OnSurfaceDim- )- Box(- modifier = Modifier.weight(1f),- contentAlignment = Alignment.CenterStart- ) {- if (value.isBlank()) {- Text(- text = placeholder,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- BasicTextField(- value = textFieldValue,- onValueChange = { updatedValue ->- textFieldValue = updatedValue- if (updatedValue.text != value) {- onValueChange(updatedValue.text)- }- },- modifier = Modifier- .fillMaxWidth()- .focusRequester(inputFocusRequester)- .focusProperties {- canFocus = !isTelevisionDevice || acceptsInput- if (isTelevisionDevice && acceptsInput) {- left = FocusRequester.Cancel- right = FocusRequester.Cancel- }- }- .onPreviewKeyEvent { event ->- if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {- return@onPreviewKeyEvent false- }- val cursor = textFieldValue.selection.end- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {- val nextCursor = (cursor - 1).coerceAtLeast(0)- textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))- true- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {- val nextCursor = (cursor + 1).coerceAtMost(textFieldValue.text.length)- textFieldValue = textFieldValue.copy(selection = TextRange(nextCursor))- true- }- else -> false- }- }- .onFocusChanged {- if (it.isFocused) {- hasInputFocus = true- requestBringIntoView(120)- } else {- hasInputFocus = false- if (isTelevisionDevice) {- acceptsInput = false- }- keyboardController?.hide()- }- },- textStyle = MaterialTheme.typography.bodySmall.copy(color = OnSurface),- singleLine = true,- cursorBrush = SolidColor(Primary),- readOnly = isTelevisionDevice && !acceptsInput,- keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),- keyboardActions = KeyboardActions(onSearch = {- focusManager.clearFocus(force = true)- acceptsInput = false- keyboardController?.hide()- onSearch?.invoke(textFieldValue.text.trim())- })- )- }- }- }-}--@Composable-private fun GuideModeRow(- selectedMode: GuideChannelMode,- onModeSelected: (GuideChannelMode) -> Unit-) {- SelectionChipRow(- title = stringResource(R.string.epg_mode_label),- subtitle = stringResource(R.string.epg_mode_subtitle),- chips = listOf(- SelectionChip(- key = GuideChannelMode.ALL.name,- label = stringResource(R.string.epg_mode_all),- supportingText = stringResource(R.string.epg_mode_all_hint)- ),- SelectionChip(- key = GuideChannelMode.ANCHORED.name,- label = stringResource(R.string.epg_mode_anchored),- supportingText = stringResource(R.string.epg_mode_anchored_hint)- ),- SelectionChip(- key = GuideChannelMode.ARCHIVE_READY.name,- label = stringResource(R.string.epg_mode_archive),- supportingText = stringResource(R.string.epg_mode_archive_hint)- )- ),- selectedKey = selectedMode.name,- onChipSelected = { key ->- GuideChannelMode.entries- .firstOrNull { it.name == key }- ?.let(onModeSelected)- }- )-}--@Composable-private fun GuideFilterRow(- categories: List<Category>,- selectedCategoryId: Long,- onCategorySelected: (Long) -> Unit,- contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp),- showLabel: Boolean = true-) {- if (categories.isEmpty()) return-- Column(- modifier = Modifier- .fillMaxWidth()- .padding(contentPadding)- ) {- if (showLabel) {- Text(- text = stringResource(R.string.epg_filter_label),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- Spacer(modifier = Modifier.height(8.dp))- }- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- itemsIndexed(- items = categories,- key = { index, category -> epgCategoryKey(category, index) }- ) { _, category ->- TvClickableSurface(- onClick = { onCategorySelected(category.id) },- colors = ClickableSurfaceDefaults.colors(- containerColor = if (category.id == selectedCategoryId) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = if (category.id == selectedCategoryId) Primary else OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(999.dp)- )- )- ) {- Text(- text = category.name,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }- }- }-}--@Composable-private fun GuideTimeControlsRow(- onJumpToPreviousDay: () -> Unit,- onPageBackward: () -> Unit,- onJumpBackwardHalfHour: () -> Unit,- onJumpBackward: () -> Unit,- onJumpToNow: () -> Unit,- onJumpForwardHalfHour: () -> Unit,- onJumpForward: () -> Unit,- onPageForward: () -> Unit,- onJumpToPrimeTime: () -> Unit,- onJumpToTomorrow: () -> Unit,- onJumpToNextDay: () -> Unit,- firstChipFocusRequester: FocusRequester? = null,- contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),- showLabel: Boolean = true-) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(contentPadding)- ) {- if (showLabel) {- Text(- text = stringResource(R.string.epg_time_controls),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- Spacer(modifier = Modifier.height(8.dp))- }- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- item {- GuideShortcutChip(- modifier = firstChipFocusRequester?.let { Modifier.focusRequester(it) } ?: Modifier,- label = stringResource(R.string.epg_previous_day),- onClick = onJumpToPreviousDay- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_page_back),- onClick = onPageBackward- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_back_half_hour),- onClick = onJumpBackwardHalfHour- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_back),- onClick = onJumpBackward- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_now),- onClick = onJumpToNow- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_forward_half_hour),- onClick = onJumpForwardHalfHour- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_forward),- onClick = onJumpForward- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_page_forward),- onClick = onPageForward- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_prime_time),- onClick = onJumpToPrimeTime- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_jump_tomorrow),- onClick = onJumpToTomorrow- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_next_day),- onClick = onJumpToNextDay- )- }- }- }-}--@Composable-private fun GuideDayRow(- selectedDayStart: Long,- onDaySelected: (Long) -> Unit,- contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 4.dp),- showLabel: Boolean = true-) {- val dayFormat = remember { SimpleDateFormat("EEE d MMM", Locale.getDefault()) }- val dayAnchors = remember(selectedDayStart) {- (-1L..3L).map { offset ->- selectedDayStart + (offset * EpgViewModel.DAY_SHIFT_MS)- }- }-- Column(- modifier = Modifier- .fillMaxWidth()- .padding(contentPadding)- ) {- if (showLabel) {- Text(- text = stringResource(R.string.epg_day_selector_label),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- Spacer(modifier = Modifier.height(8.dp))- }- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- items(dayAnchors, key = { it }) { dayStart ->- val isSelected = dayStart == selectedDayStart- TvClickableSurface(- onClick = { onDaySelected(dayStart) },- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = if (isSelected) Primary else OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(999.dp)- )- )- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = dayRelativeLabel(dayStart),- style = MaterialTheme.typography.labelLarge- )- Text(- text = dayFormat.format(Date(dayStart)),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- }-}--@Composable-private fun GuideViewOptionsRow(- showScheduledOnly: Boolean,- onToggleScheduledOnly: () -> Unit-) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 24.dp, vertical = 4.dp)- ) {- Text(- text = stringResource(R.string.epg_view_options_label),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- Spacer(modifier = Modifier.height(8.dp))- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- item {- TvClickableSurface(- onClick = onToggleScheduledOnly,- colors = ClickableSurfaceDefaults.colors(- containerColor = if (showScheduledOnly) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = if (showScheduledOnly) Primary else OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(999.dp)- )- )- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = stringResource(- if (showScheduledOnly) {- R.string.epg_view_scheduled_only_on- } else {- R.string.epg_view_scheduled_only_off- }- ),- style = MaterialTheme.typography.labelLarge- )- Text(- text = stringResource(R.string.epg_view_scheduled_only_hint),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- }-}--@Composable-private fun GuideFavoritesRow(- showFavoritesOnly: Boolean,- onToggleFavoritesOnly: () -> Unit-) {- SelectionChipRow(- title = stringResource(R.string.epg_favorites_filter_title),- subtitle = stringResource(R.string.epg_favorites_filter_subtitle),- chips = listOf(- SelectionChip(- key = "all",- label = stringResource(R.string.epg_favorites_filter_all),- supportingText = stringResource(R.string.epg_favorites_filter_all_hint)- ),- SelectionChip(- key = "favorites",- label = stringResource(R.string.epg_favorites_filter_favorites),- supportingText = stringResource(R.string.epg_favorites_filter_favorites_hint)- )- ),- selectedKey = if (showFavoritesOnly) "favorites" else "all",- onChipSelected = { key ->- val shouldShowFavorites = key == "favorites"- if (shouldShowFavorites != showFavoritesOnly) {- onToggleFavoritesOnly()- }- },- contentPadding = PaddingValues(horizontal = 24.dp)- )-}--@Composable-private fun GuideShortcutChip(- modifier: Modifier = Modifier,- label: String,- onClick: () -> Unit,- isSelected: Boolean = false-) {- TvClickableSurface(- onClick = onClick,- modifier = modifier,- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = if (isSelected) Primary else OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(999.dp)- )- )- ) {- Text(- text = label,- modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp),- style = MaterialTheme.typography.labelMedium,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }-}--@Composable-private fun GuideOptionsToggleRow(- expanded: Boolean,- onToggle: () -> Unit-) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 24.dp, vertical = 4.dp)- ) {- TvClickableSurface(- onClick = onToggle,- colors = ClickableSurfaceDefaults.colors(- containerColor = SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(999.dp)- )- )- ) {- Text(- text = stringResource(if (expanded) R.string.epg_hide_options else R.string.epg_show_options),- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),- style = MaterialTheme.typography.labelLarge- )- }- }-}--@Composable-private fun GuideSummaryCard(uiState: EpgUiState) {- val lastUpdatedLabel = uiState.lastUpdatedAt?.let { timestamp ->- val minutes = ((System.currentTimeMillis() - timestamp) / 60_000L).coerceAtLeast(0L)- if (minutes <= 1) {- stringResource(R.string.epg_updated_now)- } else {- stringResource(R.string.epg_updated_minutes_ago, minutes)- }- }- val windowFormat = remember { SimpleDateFormat("EEE HH:mm", Locale.getDefault()) }- val windowLabel = stringResource(- R.string.epg_window_label,- windowFormat.format(Date(uiState.guideWindowStart)),- windowFormat.format(Date(uiState.guideWindowEnd))- )-- LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- item {- GuideSummaryPill(- title = stringResource(- R.string.epg_showing_channels,- uiState.channels.size,- uiState.totalChannelCount- ),- subtitle = stringResource(- R.string.epg_schedule_summary_short,- uiState.channelsWithSchedule,- uiState.channels.size- )- )- }- item {- GuideSummaryPill(- title = windowLabel,- subtitle = lastUpdatedLabel ?: stringResource(R.string.epg_updated_now)- )- }- if (uiState.isGuideStale) {- item {- GuideSummaryPill(- title = stringResource(R.string.epg_stale_short),- subtitle = uiState.providerSourceLabel.ifBlank { stringResource(R.string.nav_epg) },- accent = MaterialTheme.colorScheme.error- )- }- }- }-}--private data class GuideHeroSelection(- val channel: Channel,- val program: Program?,- val isFallbackToChannel: Boolean-)--private fun resolveGuideHeroSelection(- uiState: EpgUiState,- focusedChannel: Channel?,- focusedProgram: Program?,- now: Long-): GuideHeroSelection? {- val resolvedChannel = focusedChannel- ?.let { current -> uiState.channels.firstOrNull { it.id == current.id } }- ?: uiState.channels.firstOrNull()- ?: return null- val programs = resolvedChannel.guideLookupKey()?.let { lookupKey ->- uiState.programsByChannel[lookupKey].orEmpty()- }.orEmpty()- val resolvedProgram = focusedProgram?.let { focused ->- programs.firstOrNull {- it.startTime == focused.startTime &&- it.endTime == focused.endTime &&- it.title == focused.title- }- } ?: programs.firstOrNull { now in it.startTime until it.endTime } ?: programs.firstOrNull()- return GuideHeroSelection(- channel = resolvedChannel,- program = resolvedProgram,- isFallbackToChannel = resolvedProgram == null- )-}--@Composable-private fun ImmersiveGuideHero(- selection: GuideHeroSelection?,- providerLabel: String,- selectedCategoryName: String,- isGuideStale: Boolean,- channelCount: Int,- channelsWithSchedule: Int,- lastUpdatedAt: Long?,- isRefreshing: Boolean,- modifier: Modifier = Modifier-) {- val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }- val currentTime = System.currentTimeMillis()- val lastUpdatedLabel = remember(lastUpdatedAt, currentTime) {- lastUpdatedAt?.let { updatedAt ->- val minutes = ((currentTime - updatedAt).coerceAtLeast(0L) / 60_000L).toInt()- if (minutes <= 0) {- "Updated just now"- } else {- "$minutes min ago"- }- }- }-- Surface(- modifier = modifier.height(96.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(20.dp)- ) {- Row(- modifier = Modifier- .fillMaxSize()- .padding(horizontal = 12.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- val channel = selection?.channel- ChannelLogoBadge(- channelName = channel?.name ?: stringResource(R.string.epg_title),- logoUrl = channel?.logoUrl,- modifier = Modifier- .width(54.dp)- .height(54.dp),- shape = RoundedCornerShape(12.dp)- )-- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(1.dp)- ) {- val program = selection?.program- Text(- text = program?.title ?: channel?.name ?: stringResource(R.string.epg_title),- style = MaterialTheme.typography.titleMedium.copy(- fontSize = 15.sp,- lineHeight = 18.sp- ),- color = OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- Text(- text = buildString {- channel?.let { append("${it.number}. ${it.name}") }- if (providerLabel.isNotBlank()) {- if (isNotEmpty()) append(" | ")- append(providerLabel)- }- if (selectedCategoryName.isNotBlank()) {- if (isNotEmpty()) append(" | ")- append(selectedCategoryName)- }- },- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- if (program != null) {- Text(- text = "${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",- style = MaterialTheme.typography.labelSmall.copy(lineHeight = 11.sp),- color = OnSurface- )- if (currentTime in program.startTime until program.endTime) {- LinearProgressIndicator(- progress = { ((currentTime - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },- modifier = Modifier- .fillMaxWidth()- .height(4.dp),- color = Primary,- trackColor = SurfaceHighlight- )- }- Text(- text = program.description.ifBlank { stringResource(R.string.epg_hero_no_program_description) },- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- } else {- Text(- text = stringResource(R.string.epg_no_schedule),- style = MaterialTheme.typography.labelLarge,- color = OnSurface- )- Text(- text = stringResource(R.string.epg_hero_no_schedule_hint),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }-- Column(- modifier = Modifier.widthIn(min = 176.dp, max = 220.dp),- verticalArrangement = Arrangement.spacedBy(3.dp)- ) {- GuideHeroBadge(text = stringResource(R.string.epg_schedule_summary_short, channelsWithSchedule, channelCount))- if (isRefreshing) {- GuideHeroBadge(text = stringResource(R.string.epg_loading))- }- if (selection?.program?.hasArchive == true || selection?.channel?.catchUpSupported == true) {- GuideHeroBadge(- text = if (selection.program?.hasArchive == true) {- stringResource(R.string.epg_program_replay_ready)- } else {- stringResource(R.string.epg_program_replay_partial)- },- highlight = true- )- }- if (isGuideStale) {- GuideHeroBadge(- text = stringResource(R.string.epg_stale_short),- accentColor = Color(0xFFFF6B6B)- )- }- if (!lastUpdatedLabel.isNullOrBlank()) {- Text(- text = lastUpdatedLabel,- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- }- }- }-}--@Composable-private fun GuideHeroBadge(- text: String,- highlight: Boolean = false,- accentColor: Color = Primary-) {- Surface(- shape = RoundedCornerShape(999.dp),- colors = SurfaceDefaults.colors(- containerColor = if (highlight) accentColor.copy(alpha = 0.18f) else SurfaceHighlight- )- ) {- Text(- text = text,- modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),- style = MaterialTheme.typography.labelMedium,- color = if (highlight) accentColor else OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }-}--@Composable-private fun GuideToolbarRow(- selectedCategoryName: String,- onOpenCategoryPicker: () -> Unit,- onJumpToNow: () -> Unit,- onOpenSearch: () -> Unit,- onOpenOptions: () -> Unit,- onGuideInteract: () -> Unit,- modifier: Modifier = Modifier-) {- Row(- modifier = modifier,- horizontalArrangement = Arrangement.spacedBy(5.dp),- verticalAlignment = Alignment.CenterVertically- ) {- GuideToolbarButton(- label = selectedCategoryName,- modifier = Modifier.widthIn(min = 200.dp, max = 280.dp),- onClick = onOpenCategoryPicker,- onFocused = onGuideInteract- )- GuideToolbarButton(- label = stringResource(R.string.epg_jump_now),- onClick = onJumpToNow,- onFocused = onGuideInteract- )- GuideToolbarButton(- label = stringResource(R.string.epg_search_label),- onClick = onOpenSearch,- onFocused = onGuideInteract- )- GuideToolbarButton(- label = stringResource(R.string.epg_options_short),- onClick = onOpenOptions,- onFocused = onGuideInteract- )- }-}--@Composable-private fun GuideToolbarButton(- label: String,- modifier: Modifier = Modifier,- onClick: () -> Unit,- onFocused: () -> Unit-) {- var focused by remember { mutableStateOf(false) }- TvClickableSurface(- onClick = onClick,- modifier = modifier.onFocusChanged {- if (it.isFocused && !focused) onFocused()- focused = it.isFocused- },- colors = ClickableSurfaceDefaults.colors(- containerColor = SurfaceElevated,- focusedContainerColor = SurfaceHighlight- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(14.dp)- )- )- ) {- Text(- text = label,- modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),- style = MaterialTheme.typography.labelMedium,- color = OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }-}--@Composable-private fun GuideModalDialog(- onDismiss: () -> Unit,- contentAlignment: Alignment = Alignment.Center,- content: @Composable BoxScope.() -> Unit-) {- Dialog(- onDismissRequest = onDismiss,- properties = DialogProperties(- usePlatformDefaultWidth = false,- dismissOnBackPress = true,- dismissOnClickOutside = false- )- ) {- Box(- modifier = Modifier.fillMaxSize(),- contentAlignment = contentAlignment- ) {- Box(- modifier = Modifier- .matchParentSize()- .background(Color.Black.copy(alpha = 0.68f))- .clickable(- onClick = onDismiss,- indication = null,- interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }- )- )- content()- }- }-}--@Composable-private fun GuideSearchOverlay(- query: String,- onQueryChange: (String) -> Unit,- onClear: () -> Unit,- onDismiss: () -> Unit-) {- val searchFocusRequester = remember { FocusRequester() }- val applySearchAndClose = remember(onQueryChange, onDismiss) {- { submittedQuery: String ->- onQueryChange(submittedQuery)- onDismiss()- }- }- val clearAndClose = remember(onClear, onDismiss) {- {- onClear()- onDismiss()- }- }-- LaunchedEffect(Unit) {- searchFocusRequester.requestFocus()- }-- GuideModalDialog(- onDismiss = onDismiss,- contentAlignment = Alignment.TopCenter- ) {- Surface(- modifier = Modifier- .fillMaxWidth(0.72f)- .padding(top = 32.dp)- .focusGroup(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(18.dp)- ) {- Column(- modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.epg_search_label),- style = MaterialTheme.typography.titleLarge,- color = OnSurface- )- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- GuideShortcutChip(- label = stringResource(R.string.epg_search_apply),- onClick = { applySearchAndClose(query.trim()) }- )- GuideShortcutChip(- label = stringResource(R.string.epg_clear_search_close),- onClick = clearAndClose- )- }- }- GuideProgramSearchRow(- query = query,- onQueryChange = onQueryChange,- onClear = onClear,- onSearch = applySearchAndClose,- focusRequester = searchFocusRequester,- autoRequestFocus = true,- contentPadding = PaddingValues(0.dp),- showLabel = false- )- }- }- }-}--@Composable-private fun GuideOptionsOverlay(- uiState: EpgUiState,- onDismiss: () -> Unit,- onShowAppNavigation: () -> Unit,- onJumpToPreviousDay: () -> Unit,- onPageBackward: () -> Unit,- onJumpBackwardHalfHour: () -> Unit,- onJumpBackward: () -> Unit,- onJumpToNow: () -> Unit,- onJumpForwardHalfHour: () -> Unit,- onJumpForward: () -> Unit,- onPageForward: () -> Unit,- onJumpToPrimeTime: () -> Unit,- onJumpToTomorrow: () -> Unit,- onJumpToNextDay: () -> Unit,- onDaySelected: (Long) -> Unit,- onModeSelected: (GuideChannelMode) -> Unit,- onDensitySelected: (GuideDensity) -> Unit,- onToggleScheduledOnly: () -> Unit,- onToggleFavoritesOnly: () -> Unit,- onRefresh: () -> Unit-) {- val optionsFocusRequester = remember { FocusRequester() }- LaunchedEffect(Unit) {- optionsFocusRequester.requestFocus()- }- GuideModalDialog(onDismiss = onDismiss) {- Surface(- modifier = Modifier- .fillMaxWidth(0.68f)- .fillMaxHeight(0.78f)- .focusGroup(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(20.dp)- ) {- Column(- modifier = Modifier- .fillMaxSize()- .verticalScroll(rememberScrollState())- .padding(vertical = 18.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 18.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.epg_options_short),- style = MaterialTheme.typography.headlineSmall,- color = OnSurface- )- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- GuideShortcutChip(- label = stringResource(R.string.epg_show_app_navigation),- onClick = onShowAppNavigation- )- GuideShortcutChip(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- }- GuideTimeControlsRow(- onJumpToPreviousDay = onJumpToPreviousDay,- onPageBackward = onPageBackward,- onJumpBackwardHalfHour = onJumpBackwardHalfHour,- onJumpBackward = onJumpBackward,- onJumpToNow = onJumpToNow,- onJumpForwardHalfHour = onJumpForwardHalfHour,- onJumpForward = onJumpForward,- onPageForward = onPageForward,- onJumpToPrimeTime = onJumpToPrimeTime,- onJumpToTomorrow = onJumpToTomorrow,- onJumpToNextDay = onJumpToNextDay,- firstChipFocusRequester = optionsFocusRequester- )- GuideDayRow(- selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),- onDaySelected = onDaySelected- )- GuideModeRow(- selectedMode = uiState.selectedChannelMode,- onModeSelected = onModeSelected- )- GuideDensityRow(- selectedDensity = uiState.selectedDensity,- onDensitySelected = onDensitySelected- )- GuideViewOptionsRow(- showScheduledOnly = uiState.showScheduledOnly,- onToggleScheduledOnly = onToggleScheduledOnly- )- GuideFavoritesRow(- showFavoritesOnly = uiState.showFavoritesOnly,- onToggleFavoritesOnly = onToggleFavoritesOnly- )- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 24.dp),- horizontalArrangement = Arrangement.End- ) {- GuideShortcutChip(- label = stringResource(R.string.epg_refresh_guide),- onClick = onRefresh- )- }- }- }- }-}--@Composable-private fun CompactGuideProgramDialog(- channel: Channel,- program: Program,- providerLabel: String,- now: Long,- onDismiss: () -> Unit,- onWatchLive: () -> Unit,- onWatchArchive: (() -> Unit)?,- onManageEpgMatch: (() -> Unit)?-) {- var showDetails by rememberSaveable(program.startTime, program.endTime, program.title) { mutableStateOf(false) }- val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }- GuideModalDialog(onDismiss = onDismiss) {- Surface(- modifier = Modifier.widthIn(min = 420.dp, max = 640.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(20.dp)- ) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)- ) {- Text(- text = program.title,- style = MaterialTheme.typography.headlineSmall,- color = OnSurface,- maxLines = 2,- overflow = TextOverflow.Ellipsis- )- Text(- text = "${channel.number}. ${channel.name} | ${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim,- maxLines = 2,- overflow = TextOverflow.Ellipsis- )- if (providerLabel.isNotBlank()) {- Text(- text = providerLabel,- style = MaterialTheme.typography.labelMedium,- color = Primary- )- }- if (now in program.startTime until program.endTime) {- LinearProgressIndicator(- progress = { ((now - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },- modifier = Modifier- .fillMaxWidth()- .height(4.dp),- color = Primary,- trackColor = SurfaceHighlight- )- }- if (showDetails) {- Text(- text = program.description.ifBlank { stringResource(R.string.epg_no_info) },- style = MaterialTheme.typography.bodyMedium,- color = OnSurface,- maxLines = 6,- overflow = TextOverflow.Ellipsis- )- }- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- TvButton(- onClick = onWatchLive,- modifier = Modifier.fillMaxWidth()- ) {- Text(stringResource(R.string.epg_watch_live))- }- if (onWatchArchive != null) {- TvButton(- onClick = onWatchArchive,- modifier = Modifier.fillMaxWidth(),- colors = ButtonDefaults.colors(- containerColor = Primary,- contentColor = Color.White- )- ) {- Text(stringResource(R.string.epg_watch_archive))- }- }- if (onManageEpgMatch != null) {- TvButton(- onClick = onManageEpgMatch,- modifier = Modifier.fillMaxWidth(),- colors = ButtonDefaults.colors(- containerColor = SurfaceHighlight,- contentColor = OnSurface- )- ) {- Text(stringResource(R.string.epg_override_manage))- }- }- TvButton(- onClick = { showDetails = !showDetails },- modifier = Modifier.fillMaxWidth(),- colors = ButtonDefaults.colors(- containerColor = SurfaceHighlight,- contentColor = OnSurface- )- ) {- Text(- if (showDetails) stringResource(R.string.epg_program_details_hide)- else stringResource(R.string.epg_program_details_show)- )- }- TextButton(onClick = onDismiss) {- Text(stringResource(R.string.settings_cancel))- }- }- }- }- }-}--@Composable-private fun EpgOverrideDialog(- state: EpgOverrideUiState,- onDismiss: () -> Unit,- onQueryChange: (String) -> Unit,- onCandidateSelected: (EpgOverrideCandidate) -> Unit,- onClearOverride: () -> Unit-) {- val channel = state.channel ?: return- val unknownValue = stringResource(R.string.epg_program_unknown_value)- val currentCandidate = remember(state.currentMapping, state.candidates) {- state.candidates.firstOrNull {- it.epgSourceId == state.currentMapping?.epgSourceId &&- it.xmltvChannelId == state.currentMapping?.xmltvChannelId- }- }- val currentDescriptor = currentCandidate?.let {- "${it.displayName} • ${it.epgSourceName} • ${it.xmltvChannelId}"- } ?: (state.currentMapping?.xmltvChannelId ?: unknownValue)- val currentSummary = when {- state.currentMapping == null || state.currentMapping.sourceType == EpgSourceType.NONE ->- stringResource(R.string.epg_override_current_none)- state.currentMapping.isManualOverride || state.currentMapping.matchType == EpgMatchType.MANUAL ->- stringResource(R.string.epg_override_current_manual, currentDescriptor)- state.currentMapping.sourceType == EpgSourceType.PROVIDER ->- stringResource(R.string.epg_override_current_provider, currentDescriptor)- else ->- stringResource(R.string.epg_override_current_external, currentDescriptor)- }-- GuideModalDialog(onDismiss = onDismiss) {- Surface(- modifier = Modifier.widthIn(min = 560.dp, max = 760.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(20.dp)- ) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)- ) {- Text(- text = stringResource(R.string.epg_override_title),- style = MaterialTheme.typography.headlineSmall,- color = OnSurface- )- Text(- text = "${channel.number}. ${channel.name}",- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(- text = stringResource(R.string.epg_override_current_label),- style = MaterialTheme.typography.labelMedium,- color = Primary- )- Text(- text = currentSummary,- style = MaterialTheme.typography.bodyMedium,- color = OnSurface- )- }- if (!state.error.isNullOrBlank()) {- Text(- text = state.error,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.error- )- }- if (state.isLoading || state.isSaving) {- LinearProgressIndicator(- modifier = Modifier- .fillMaxWidth()- .height(3.dp),- color = Primary,- trackColor = SurfaceHighlight- )- }- GuideSearchField(- value = state.searchQuery,- onValueChange = onQueryChange,- placeholder = stringResource(R.string.epg_override_search_placeholder),- modifier = Modifier.fillMaxWidth(),- onSearch = { onQueryChange(it) }- )- if (state.candidates.isEmpty()) {- Text(- text = if (state.searchQuery.isBlank()) {- stringResource(R.string.epg_override_no_candidates)- } else {- stringResource(R.string.epg_override_no_search_results)- },- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- } else {- LazyColumn(- modifier = Modifier- .fillMaxWidth()- .heightIn(max = 320.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- items(state.candidates) { candidate ->- val isCurrent = state.currentMapping?.epgSourceId == candidate.epgSourceId &&- state.currentMapping?.xmltvChannelId == candidate.xmltvChannelId- TvClickableSurface(- onClick = {- if (!state.isSaving) {- onCandidateSelected(candidate)- }- },- modifier = Modifier.fillMaxWidth(),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isCurrent) SurfaceHighlight else SurfaceElevated,- focusedContainerColor = SurfaceHighlight,- contentColor = OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(14.dp)- )- )- ) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 14.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = candidate.displayName,- style = MaterialTheme.typography.bodyLarge,- color = OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- if (isCurrent) {- Text(- text = stringResource(R.string.epg_override_selected_badge),- style = MaterialTheme.typography.labelSmall,- color = Primary- )- }- }- Text(- text = "${candidate.epgSourceName} • ${candidate.xmltvChannelId}",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- maxLines = 2,- overflow = TextOverflow.Ellipsis- )- }- }- }- }- }- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- if (state.currentMapping?.isManualOverride == true) {- TvButton(- onClick = onClearOverride,- enabled = !state.isSaving,- modifier = Modifier.fillMaxWidth(),- colors = ButtonDefaults.colors(- containerColor = SurfaceHighlight,- contentColor = OnSurface- )- ) {- Text(stringResource(R.string.epg_override_clear))- }- }- TextButton(onClick = onDismiss) {- Text(stringResource(R.string.settings_cancel))- }- }- }- }- }-}--@Composable-private fun GuideSummaryPill(- title: String,- subtitle: String,- modifier: Modifier = Modifier,- accent: Color = Primary-) {- Surface(- modifier = modifier,- colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight),- shape = RoundedCornerShape(14.dp)- ) {- Column(- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.bodyLarge,- color = OnSurface- )- Text(- text = subtitle,- style = MaterialTheme.typography.bodySmall,- color = accent- )- }- }-}--@Composable-private fun GuideMessageState(- modifier: Modifier = Modifier,- title: String,- subtitle: String?,- actionLabel: String?,- onAction: (() -> Unit)?-) {- Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Column(- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(10.dp),- modifier = Modifier.padding(horizontal = 32.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.titleLarge,- color = OnSurface- )- if (!subtitle.isNullOrBlank()) {- Text(- text = subtitle,- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- }- if (actionLabel != null && onAction != null) {- TvButton(- onClick = onAction,- colors = ButtonDefaults.colors(- containerColor = Primary,- contentColor = Color.White- )- ) {- Text(actionLabel)- }- }- }- }-}--@Composable-fun EpgGrid(- modifier: Modifier = Modifier,- channels: List<Channel>,- favoriteChannelIds: Set<Long>,- programsByChannel: Map<String, List<Program>>,- guideWindowStart: Long,- guideWindowEnd: Long,- density: GuideDensity,- now: Long,- onChannelClick: (Channel) -> Unit,- onProgramClick: (Channel, Program) -> Unit,- onChannelFocused: (Channel, Program?, Boolean) -> Unit,- onProgramFocused: (Channel, Program, Boolean) -> Unit-) {- val channelRailWidth = 180.dp- val timelineGap = 4.dp- val rowHeight = when (density) {- GuideDensity.COMPACT -> 38.dp- GuideDensity.COMFORTABLE -> 44.dp- GuideDensity.CINEMATIC -> 52.dp- }- val horizontalScrollState = rememberScrollState()-- BoxWithConstraints(- modifier = modifier- .fillMaxSize()- .padding(horizontal = 12.dp, vertical = 2.dp)- ) {- val timelineViewportWidth = (maxWidth - channelRailWidth - timelineGap).coerceAtLeast(640.dp)- val totalDuration = (guideWindowEnd - guideWindowStart).coerceAtLeast(1L)- val visibleDurationMs = 3 * 60 * 60 * 1000L- val calculatedTimelineWidth = timelineViewportWidth * (totalDuration.toFloat() / visibleDurationMs.toFloat())- val totalTimelineWidth = if (calculatedTimelineWidth > timelineViewportWidth) {- calculatedTimelineWidth- } else {- timelineViewportWidth- }- val markerStepMs = EpgViewModel.HALF_HOUR_SHIFT_MS-- Column(modifier = Modifier.fillMaxSize()) {- GuideTimelineHeader(- windowStart = guideWindowStart,- windowEnd = guideWindowEnd,- now = now,- channelRailWidth = channelRailWidth,- timelineGap = timelineGap,- timelineViewportWidth = timelineViewportWidth,- totalTimelineWidth = totalTimelineWidth,- markerStepMs = markerStepMs,- scrollState = horizontalScrollState- )- Spacer(modifier = Modifier.height(4.dp))- LazyColumn(- modifier = Modifier.fillMaxSize(),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- itemsIndexed(- items = channels,- key = { index, channel -> epgChannelKey(channel, index) }- ) { index, channel ->- val programs = channel.guideLookupKey()?.let { lookupKey ->- programsByChannel[lookupKey].orEmpty()- }.orEmpty()- val isFirstRow = index == 0- EpgRow(- channel = channel,- isFavorite = channel.id in favoriteChannelIds,- programs = programs,- now = now,- windowStart = guideWindowStart,- windowEnd = guideWindowEnd,- channelRailWidth = channelRailWidth,- timelineGap = timelineGap,- timelineViewportWidth = timelineViewportWidth,- totalTimelineWidth = totalTimelineWidth,- density = density,- rowHeight = rowHeight,- markerStepMs = markerStepMs,- scrollState = horizontalScrollState,- onChannelClick = { onChannelClick(channel) },- onChannelFocused = { onChannelFocused(channel, it, isFirstRow) },- onProgramClick = { program -> onProgramClick(channel, program) },- onProgramFocused = { program -> onProgramFocused(channel, program, isFirstRow) }- )- }- }- }- }-}--@Composable-private fun GuideTimelineHeader(- windowStart: Long,- windowEnd: Long,- now: Long,- channelRailWidth: Dp,- timelineGap: Dp,- timelineViewportWidth: Dp,- totalTimelineWidth: Dp,- markerStepMs: Long,- scrollState: androidx.compose.foundation.ScrollState-) {- val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }- val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)- val clampedNow = now.coerceIn(windowStart, windowEnd)- val elapsedRatio = ((clampedNow - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- val markerLabel = if (now in windowStart..windowEnd) {- stringResource(R.string.epg_now_marker, hourFormat.format(Date(now)))- } else {- stringResource(R.string.epg_outside_window)- }- val hourMarkers = buildList {- var marker = windowStart- while (marker <= windowEnd) {- add(marker)- marker += markerStepMs- }- if (lastOrNull() != windowEnd) {- add(windowEnd)- }- }-- Row(- modifier = Modifier- .fillMaxWidth()- .padding(bottom = 2.dp),- verticalAlignment = Alignment.Bottom- ) {- Spacer(modifier = Modifier.width(channelRailWidth + timelineGap))- Column(- modifier = Modifier.width(timelineViewportWidth),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.epg_timeline_label),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- Text(- text = stringResource(- R.string.epg_timeline_range_label,- formatWindowDuration(totalDuration)- ),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- Box(- modifier = Modifier- .width(timelineViewportWidth)- .height(20.dp)- ) {- Row(- modifier = Modifier- .width(totalTimelineWidth)- .horizontalScroll(scrollState)- ) {- Box(- modifier = Modifier- .width(totalTimelineWidth)- .height(20.dp)- ) {- hourMarkers.forEach { marker ->- val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- val markerOffset = totalTimelineWidth * markerRatio- Column(- modifier = Modifier.padding(start = markerOffset),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = hourFormat.format(Date(marker)),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- Box(- modifier = Modifier- .width(1.dp)- .height(8.dp)- .background(Color.White.copy(alpha = 0.16f))- )- }- }- if (now in windowStart..windowEnd) {- Box(- modifier = Modifier- .padding(start = totalTimelineWidth * elapsedRatio)- .width(2.dp)- .fillMaxHeight()- .background(Primary)- )- }- }- }- }- Text(- text = markerLabel,- style = MaterialTheme.typography.labelSmall,- color = if (now in windowStart..windowEnd) Primary else OnSurfaceDim- )- }- }-}--@Composable-fun EpgRow(- channel: Channel,- isFavorite: Boolean,- programs: List<Program>,- now: Long,- windowStart: Long,- windowEnd: Long,- channelRailWidth: Dp,- timelineGap: Dp,- timelineViewportWidth: Dp,- totalTimelineWidth: Dp,- density: GuideDensity,- rowHeight: Dp,- markerStepMs: Long,- scrollState: androidx.compose.foundation.ScrollState,- onChannelClick: () -> Unit,- onChannelFocused: (Program?) -> Unit,- onProgramClick: (Program) -> Unit,- onProgramFocused: (Program) -> Unit-) {- var isFocused by remember { mutableStateOf(false) }- val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)- val currentProgram = programs.firstOrNull { now in it.startTime..it.endTime }- val channelPaddingVertical = when (density) {- GuideDensity.COMPACT -> 3.dp- GuideDensity.COMFORTABLE -> 4.dp- GuideDensity.CINEMATIC -> 5.dp- }- val channelLogoSize = when (density) {- GuideDensity.COMPACT -> 22.dp- GuideDensity.COMFORTABLE -> 24.dp- GuideDensity.CINEMATIC -> 26.dp- }-- Row(- modifier = Modifier- .fillMaxWidth()- .height(rowHeight),- verticalAlignment = Alignment.CenterVertically- ) {- TvClickableSurface(- onClick = onChannelClick,- modifier = Modifier- .width(channelRailWidth)- .fillMaxHeight()- .onFocusChanged {- if (it.isFocused && !isFocused) {- onChannelFocused(currentProgram)- }- isFocused = it.isFocused- },- colors = ClickableSurfaceDefaults.colors(- containerColor = SurfaceElevated,- focusedContainerColor = SurfaceHighlight- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(8.dp)- )- )- ) {- Row(- modifier = Modifier- .padding(horizontal = 7.dp, vertical = channelPaddingVertical)- .fillMaxSize(),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- ChannelLogoBadge(- channelName = channel.name,- logoUrl = channel.logoUrl,- modifier = Modifier- .width(channelLogoSize)- .height(channelLogoSize),- shape = RoundedCornerShape(6.dp)- )- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(0.dp)- ) {- Text(- text = "${channel.number}. ${channel.name}",- style = MaterialTheme.typography.labelLarge,- color = if (isFocused) TextPrimary else OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- Text(- text = currentProgram?.title ?: stringResource(R.string.epg_no_schedule_short),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- if (isFavorite || channel.catchUpSupported) {- Box(- modifier = Modifier- .background(- color = Primary.copy(alpha = 0.16f),- shape = CircleShape- )- .padding(horizontal = 5.dp, vertical = 1.dp)- ) {- Text(- text = if (channel.catchUpSupported) stringResource(R.string.player_archive_badge) else stringResource(R.string.epg_favorite_badge),- style = MaterialTheme.typography.labelSmall,- color = Primary,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }- }- }-- Spacer(modifier = Modifier.width(timelineGap))-- Box(- modifier = Modifier- .width(timelineViewportWidth)- .fillMaxHeight()- .background(SurfaceElevated, RoundedCornerShape(8.dp))- .clip(RoundedCornerShape(8.dp))- ) {- Row(- modifier = Modifier- .width(totalTimelineWidth)- .horizontalScroll(scrollState)- ) {- Box(- modifier = Modifier- .width(totalTimelineWidth)- .fillMaxHeight()- ) {- val markers = remember(windowStart, windowEnd, markerStepMs) {- buildList {- var marker = windowStart- while (marker <= windowEnd) {- add(marker)- marker += markerStepMs- }- }- }- markers.forEach { marker ->- val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- Box(- modifier = Modifier- .padding(start = totalTimelineWidth * markerRatio)- .width(1.dp)- .fillMaxHeight()- .background(Color.White.copy(alpha = 0.08f))- )- }- if (now in windowStart..windowEnd) {- val nowRatio = ((now - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- Box(- modifier = Modifier- .padding(start = totalTimelineWidth * nowRatio)- .width(2.dp)- .fillMaxHeight()- .background(Primary)- )- }- if (programs.isEmpty()) {- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Text(stringResource(R.string.epg_no_schedule_short), color = OnSurfaceDim)- }- } else {- programs.forEach { program ->- ProgramItem(- program = program,- density = density,- isCurrent = now in program.startTime until program.endTime,- now = now,- windowStart = windowStart,- windowEnd = windowEnd,- totalTimelineWidth = totalTimelineWidth,- onClick = { onProgramClick(program) },- onFocused = { onProgramFocused(program) }- )- }- }- }- }- }- }-}--@Composable-fun ProgramItem(- program: Program,- density: GuideDensity,- isCurrent: Boolean,- now: Long,- windowStart: Long,- windowEnd: Long,- totalTimelineWidth: Dp,- onClick: () -> Unit,- onFocused: () -> Unit-) {- var isFocused by remember { mutableStateOf(false) }-- val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }- val startStr = format.format(Date(program.startTime))- val endStr = format.format(Date(program.endTime))- val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)- val visibleStart = max(program.startTime, windowStart)- val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))- val startRatio = ((visibleStart - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)- val itemStart = totalTimelineWidth * startRatio- val minimumItemWidth = when (density) {- GuideDensity.COMPACT -> 40.dp- GuideDensity.COMFORTABLE -> 48.dp- GuideDensity.CINEMATIC -> 56.dp- }- val itemWidth = (totalTimelineWidth * widthRatio).coerceAtLeast(minimumItemWidth)- val isCompactCell = itemWidth < 148.dp- val isVeryCompactCell = itemWidth < 116.dp- val outerVerticalPadding = when (density) {- GuideDensity.COMPACT -> 2.dp- GuideDensity.COMFORTABLE -> 2.dp- GuideDensity.CINEMATIC -> 3.dp- }- val innerHorizontalPadding = when {- isVeryCompactCell -> 5.dp- isCompactCell -> 6.dp- else -> 8.dp- }- val innerVerticalPadding = when (density) {- GuideDensity.COMPACT -> 2.dp- GuideDensity.COMFORTABLE -> 3.dp- GuideDensity.CINEMATIC -> 4.dp- }- val titleStyle = when {- isVeryCompactCell -> MaterialTheme.typography.labelSmall.copy(- fontSize = 10.sp,- lineHeight = 11.sp- )- isCompactCell || density == GuideDensity.COMPACT -> MaterialTheme.typography.labelMedium.copy(- fontSize = 11.sp,- lineHeight = 12.sp- )- else -> MaterialTheme.typography.labelLarge.copy(- fontSize = 12.sp,- lineHeight = 14.sp- )- }- val timeStyle = when {- isCompactCell || density == GuideDensity.COMPACT -> MaterialTheme.typography.labelSmall.copy(- fontSize = 9.sp,- lineHeight = 10.sp- )- else -> MaterialTheme.typography.labelSmall.copy(- fontSize = 10.sp,- lineHeight = 11.sp- )- }-- TvClickableSurface(- onClick = onClick,- modifier = Modifier- .padding(start = itemStart, top = outerVerticalPadding, bottom = outerVerticalPadding)- .width(itemWidth)- .fillMaxHeight()- .clip(RoundedCornerShape(8.dp))- .onFocusChanged {- if (it.isFocused && !isFocused) {- onFocused()- }- isFocused = it.isFocused- },- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,- focusedContainerColor = SurfaceHighlight- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(8.dp)- )- )- ) {- Column(- modifier = Modifier- .padding(horizontal = innerHorizontalPadding, vertical = innerVerticalPadding)- .fillMaxSize(),- verticalArrangement = Arrangement.Center- ) {- Text(- text = program.title,- style = titleStyle,- color = if (isFocused) TextPrimary else if (isCurrent) Primary else OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- if (!isVeryCompactCell) {- Text(- text = "$startStr - $endStr",- style = timeStyle,- color = if (isFocused) TextSecondary else OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }- }-}--private fun formatWindowDuration(durationMs: Long): String {- val hours = durationMs / (60 * 60 * 1000L)- val minutes = (durationMs / (60 * 1000L)) % 60- return if (minutes == 0L) {- "${hours}h"- } else {- "${hours}h ${minutes}m"- }-}--private fun startOfDay(timestamp: Long): Long {- val calendar = Calendar.getInstance().apply {- timeInMillis = timestamp- set(Calendar.HOUR_OF_DAY, 0)- set(Calendar.MINUTE, 0)- set(Calendar.SECOND, 0)- set(Calendar.MILLISECOND, 0)- }- return calendar.timeInMillis-}--@Composable-private fun GuideHeaderDeck(- uiState: EpgUiState,- showSearchBar: Boolean,- showAdvancedOptions: Boolean,- onToggleSearch: () -> Unit,- onOpenCategoryPicker: () -> Unit,- onToggleAdvancedOptions: () -> Unit,- onProgramSearchQueryChange: (String) -> Unit,- onClearProgramSearch: () -> Unit,- onJumpToPreviousDay: () -> Unit,- onJumpBackward: () -> Unit,- onJumpToNow: () -> Unit,- onJumpForward: () -> Unit,- onJumpToPrimeTime: () -> Unit,- onJumpToNextDay: () -> Unit,- onPageBackward: () -> Unit,- onJumpBackwardHalfHour: () -> Unit,- onJumpForwardHalfHour: () -> Unit,- onPageForward: () -> Unit,- onJumpToTomorrow: () -> Unit,- onDaySelected: (Long) -> Unit,- onModeSelected: (GuideChannelMode) -> Unit,- onDensitySelected: (GuideDensity) -> Unit,- onToggleScheduledOnly: () -> Unit,- onToggleFavoritesOnly: () -> Unit-) {- Surface(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 24.dp, vertical = 8.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(18.dp)- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- GuideSummaryCard(uiState = uiState)-- GuidePrimaryControlsRow(- categories = uiState.categories,- selectedCategoryId = uiState.selectedCategoryId,- showSearchBar = showSearchBar,- showAdvancedOptions = showAdvancedOptions,- onJumpToPreviousDay = onJumpToPreviousDay,- onJumpBackward = onJumpBackward,- onJumpToNow = onJumpToNow,- onJumpForward = onJumpForward,- onJumpToPrimeTime = onJumpToPrimeTime,- onJumpToNextDay = onJumpToNextDay,- onOpenCategoryPicker = onOpenCategoryPicker,- onToggleSearch = onToggleSearch,- onToggleAdvancedOptions = onToggleAdvancedOptions- )-- if (showSearchBar) {- GuideProgramSearchRow(- query = uiState.programSearchQuery,- onQueryChange = onProgramSearchQueryChange,- onClear = onClearProgramSearch,- contentPadding = PaddingValues(0.dp),- showLabel = false- )- }-- if (showAdvancedOptions) {- GuideTimeControlsRow(- onJumpToPreviousDay = onJumpToPreviousDay,- onPageBackward = onPageBackward,- onJumpBackwardHalfHour = onJumpBackwardHalfHour,- onJumpBackward = onJumpBackward,- onJumpToNow = onJumpToNow,- onJumpForwardHalfHour = onJumpForwardHalfHour,- onJumpForward = onJumpForward,- onPageForward = onPageForward,- onJumpToPrimeTime = onJumpToPrimeTime,- onJumpToTomorrow = onJumpToTomorrow,- onJumpToNextDay = onJumpToNextDay,- contentPadding = PaddingValues(0.dp),- showLabel = false- )-- GuideDayRow(- selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),- onDaySelected = onDaySelected,- contentPadding = PaddingValues(0.dp),- showLabel = false- )-- GuideModeRow(- selectedMode = uiState.selectedChannelMode,- onModeSelected = onModeSelected- )-- GuideDensityRow(- selectedDensity = uiState.selectedDensity,- onDensitySelected = onDensitySelected- )-- GuideViewOptionsRow(- showScheduledOnly = uiState.showScheduledOnly,- onToggleScheduledOnly = onToggleScheduledOnly- )-- GuideFavoritesRow(- showFavoritesOnly = uiState.showFavoritesOnly,- onToggleFavoritesOnly = onToggleFavoritesOnly- )- }- }- }-}--@Composable-private fun GuidePrimaryControlsRow(- categories: List<Category>,- selectedCategoryId: Long,- showSearchBar: Boolean,- showAdvancedOptions: Boolean,- onJumpToPreviousDay: () -> Unit,- onJumpBackward: () -> Unit,- onJumpToNow: () -> Unit,- onJumpForward: () -> Unit,- onJumpToPrimeTime: () -> Unit,- onJumpToNextDay: () -> Unit,- onOpenCategoryPicker: () -> Unit,- onToggleSearch: () -> Unit,- onToggleAdvancedOptions: () -> Unit-) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- GuideCategoryLauncherRow(- categories = categories,- selectedCategoryId = selectedCategoryId,- onOpenCategoryPicker = onOpenCategoryPicker,- modifier = Modifier.widthIn(min = 220.dp, max = 360.dp)- )-- LazyRow(- modifier = Modifier.weight(1f),- horizontalArrangement = Arrangement.spacedBy(8.dp)- ) {- item { GuideShortcutChip(label = stringResource(R.string.epg_previous_day), onClick = onJumpToPreviousDay) }- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_now), onClick = onJumpToNow) }- item { GuideShortcutChip(label = stringResource(R.string.epg_next_day), onClick = onJumpToNextDay) }- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back), onClick = onJumpBackward) }- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward), onClick = onJumpForward) }- item { GuideShortcutChip(label = stringResource(R.string.epg_jump_prime_time), onClick = onJumpToPrimeTime) }- item {- GuideShortcutChip(- label = if (showSearchBar) stringResource(R.string.epg_clear_search) else stringResource(R.string.epg_search_short),- onClick = onToggleSearch- )- }- item {- GuideShortcutChip(- label = stringResource(R.string.epg_options_short),- onClick = onToggleAdvancedOptions,- isSelected = showAdvancedOptions- )- }- }- }-}--@Composable-private fun GuideCategoryLauncherRow(- categories: List<Category>,- selectedCategoryId: Long,- onOpenCategoryPicker: () -> Unit,- modifier: Modifier = Modifier-) {- val selectedCategory = remember(categories, selectedCategoryId) {- categories.firstOrNull { it.id == selectedCategoryId }- }- TvClickableSurface(- onClick = onOpenCategoryPicker,- modifier = modifier.widthIn(max = 320.dp),- colors = ClickableSurfaceDefaults.colors(- containerColor = SurfaceHighlight,- focusedContainerColor = SurfaceElevated,- contentColor = OnSurface,- focusedContentColor = OnSurface- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(16.dp)- )- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 14.dp, vertical = 10.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(1.dp)- ) {- Text(- text = selectedCategory?.name ?: stringResource(R.string.epg_filter_label),- style = MaterialTheme.typography.labelLarge,- color = OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- Text(- text = "${categories.size} categories",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- Spacer(modifier = Modifier.width(10.dp))- Text(- text = stringResource(R.string.epg_filter_label),- style = MaterialTheme.typography.labelMedium,- color = Primary- )- }- }-}--@Composable-private fun GuideCategoryPickerDialog(- categories: List<Category>,- selectedCategoryId: Long,- parentalControlLevel: Int,- onDismiss: () -> Unit,- onCategorySelected: (Category) -> Unit-) {- var query by rememberSaveable { mutableStateOf("") }- var shouldFocusFirstCategory by rememberSaveable { mutableStateOf(true) }- val searchFocusRequester = remember { FocusRequester() }- val firstCategoryFocusRequester = remember { FocusRequester() }- val filteredCategories = remember(categories, query) {- val trimmed = query.trim()- val baseCategories = if (trimmed.isBlank()) {- categories- } else {- categories.filter { it.name.contains(trimmed, ignoreCase = true) }- }- val selectedCategory = baseCategories.firstOrNull { it.id == selectedCategoryId }- buildList {- if (selectedCategory != null) add(selectedCategory)- addAll(baseCategories.filterNot { it.id == selectedCategoryId })- }- }- GuideModalDialog(onDismiss = onDismiss) {- Surface(- modifier = Modifier- .fillMaxWidth(0.52f)- .fillMaxHeight(0.78f)- .focusGroup(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(22.dp)- ) {- Column(- modifier = Modifier- .fillMaxSize()- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = stringResource(R.string.epg_filter_label),- style = MaterialTheme.typography.headlineSmall,- color = OnSurface- )- Text(- text = "${filteredCategories.size} matches",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- GuideShortcutChip(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }-- GuideProgramSearchRow(- query = query,- onQueryChange = { query = it },- onClear = { query = "" },- focusRequester = searchFocusRequester,- contentPadding = PaddingValues(0.dp),- showLabel = false,- onSearchFieldActivated = {- shouldFocusFirstCategory = false- }- )-- LazyColumn(- modifier = Modifier.fillMaxSize(),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- itemsIndexed(- items = filteredCategories,- key = { index, category -> epgCategoryKey(category, index) }- ) { _, category ->- val isSelected = category.id == selectedCategoryId- val isLocked = isGuideCategoryLocked(category, parentalControlLevel)- TvClickableSurface(- onClick = { onCategorySelected(category) },- modifier = if (category.id == filteredCategories.firstOrNull()?.id) {- Modifier.focusRequester(firstCategoryFocusRequester)- } else {- Modifier- },- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceHighlight,- focusedContainerColor = if (isSelected) {- Primary.copy(alpha = 0.22f)- } else {- SurfaceHighlight- },- contentColor = if (isSelected) Primary else OnSurface,- focusedContentColor = if (isSelected) Primary else OnSurface- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(14.dp)- )- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 14.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = category.name,- style = MaterialTheme.typography.titleMedium,- color = if (isSelected) Primary else OnSurface- )- if (isLocked) {- Text(- text = stringResource(R.string.settings_parental_control),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- } else if (category.count > 0) {- Text(- text = "${category.count} channels",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- if (isSelected) {- Text(- text = stringResource(R.string.epg_jump_now),- style = MaterialTheme.typography.labelLarge,- color = Primary- )- }- }- }- }- }- }- }- }-- LaunchedEffect(filteredCategories, shouldFocusFirstCategory) {- if (shouldFocusFirstCategory && filteredCategories.isNotEmpty()) {- firstCategoryFocusRequester.requestFocus()- shouldFocusFirstCategory = false- }- }-}--private fun epgCategoryKey(category: Category, index: Int): String {- return "category:${category.id}:${category.name.trim()}:$index"-}--private fun epgChannelKey(channel: Channel, index: Int): String {- val epgId = channel.guideLookupKey().orEmpty()- return "channel:${channel.id}:${channel.streamId}:${epgId}:${channel.name.trim()}:$index"-}--private fun isGuideCategoryLocked(category: Category, parentalControlLevel: Int): Boolean =+internal fun isGuideCategoryLocked(category: Category, parentalControlLevel: Int): Boolean =parentalControlLevel == 1 && (category.isAdult || category.isUserProtected)private fun isGuideChannelLocked(@@ -3312,17 +666,4 @@ private fun isGuideChannelLocked(return channel.isAdult || channel.isUserProtected || categoryLocked}-@Composable-private fun dayRelativeLabel(dayStart: Long): String {- val todayStart = remember { startOfDay(System.currentTimeMillis()) }- return when (dayStart) {- todayStart - EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_yesterday)- todayStart -> stringResource(R.string.epg_day_today)- todayStart + EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_tomorrow)- else -> {- val format = remember { SimpleDateFormat("EEE", Locale.getDefault()) }- format.format(Date(dayStart))- }- }-}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.ktnew file mode 100644index 00000000..3066c691--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreenDialogs.kt@@ -0,0 +1,768 @@+package com.streamvault.app.ui.screens.epg++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusGroup+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties+import androidx.tv.material3.Border+import androidx.tv.material3.ButtonDefaults+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.EpgMatchType+import com.streamvault.domain.model.EpgOverrideCandidate+import com.streamvault.domain.model.EpgSourceType+import com.streamvault.domain.model.Program+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++@Composable+private fun GuideModalDialog(+ onDismiss: () -> Unit,+ contentAlignment: Alignment = Alignment.Center,+ content: @Composable BoxScope.() -> Unit+) {+ Dialog(+ onDismissRequest = onDismiss,+ properties = DialogProperties(+ usePlatformDefaultWidth = false,+ dismissOnBackPress = true,+ dismissOnClickOutside = false+ )+ ) {+ Box(+ modifier = Modifier.fillMaxSize(),+ contentAlignment = contentAlignment+ ) {+ Box(+ modifier = Modifier+ .matchParentSize()+ .background(Color.Black.copy(alpha = 0.68f))+ .clickable(+ onClick = onDismiss,+ indication = null,+ interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }+ )+ )+ content()+ }+ }+}++@Composable+internal fun GuideSearchOverlay(+ query: String,+ onQueryChange: (String) -> Unit,+ onClear: () -> Unit,+ onDismiss: () -> Unit+) {+ val searchFocusRequester = remember { FocusRequester() }+ val applySearchAndClose = remember(onQueryChange, onDismiss) {+ { submittedQuery: String ->+ onQueryChange(submittedQuery)+ onDismiss()+ }+ }+ val clearAndClose = remember(onClear, onDismiss) {+ {+ onClear()+ onDismiss()+ }+ }++ LaunchedEffect(Unit) {+ searchFocusRequester.requestFocus()+ }++ GuideModalDialog(+ onDismiss = onDismiss,+ contentAlignment = Alignment.TopCenter+ ) {+ Surface(+ modifier = Modifier+ .fillMaxWidth(0.72f)+ .padding(top = 32.dp)+ .focusGroup(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(18.dp)+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.epg_search_label),+ style = MaterialTheme.typography.titleLarge,+ color = OnSurface+ )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ GuideShortcutChip(+ label = stringResource(R.string.epg_search_apply),+ onClick = { applySearchAndClose(query.trim()) }+ )+ GuideShortcutChip(+ label = stringResource(R.string.epg_clear_search_close),+ onClick = clearAndClose+ )+ }+ }+ GuideProgramSearchRow(+ query = query,+ onQueryChange = onQueryChange,+ onClear = onClear,+ onSearch = applySearchAndClose,+ focusRequester = searchFocusRequester,+ autoRequestFocus = true,+ contentPadding = PaddingValues(0.dp),+ showLabel = false+ )+ }+ }+ }+}++@Composable+internal fun GuideOptionsOverlay(+ uiState: EpgUiState,+ onDismiss: () -> Unit,+ onShowAppNavigation: () -> Unit,+ onJumpToPreviousDay: () -> Unit,+ onPageBackward: () -> Unit,+ onJumpBackwardHalfHour: () -> Unit,+ onJumpBackward: () -> Unit,+ onJumpToNow: () -> Unit,+ onJumpForwardHalfHour: () -> Unit,+ onJumpForward: () -> Unit,+ onPageForward: () -> Unit,+ onJumpToPrimeTime: () -> Unit,+ onJumpToTomorrow: () -> Unit,+ onJumpToNextDay: () -> Unit,+ onDaySelected: (Long) -> Unit,+ onModeSelected: (GuideChannelMode) -> Unit,+ onDensitySelected: (GuideDensity) -> Unit,+ onToggleScheduledOnly: () -> Unit,+ onToggleFavoritesOnly: () -> Unit,+ onRefresh: () -> Unit+) {+ val optionsFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) {+ optionsFocusRequester.requestFocus()+ }+ GuideModalDialog(onDismiss = onDismiss) {+ Surface(+ modifier = Modifier+ .fillMaxWidth(0.68f)+ .fillMaxHeight(0.78f)+ .focusGroup(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(20.dp)+ ) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .verticalScroll(rememberScrollState())+ .padding(vertical = 18.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 18.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.epg_options_short),+ style = MaterialTheme.typography.headlineSmall,+ color = OnSurface+ )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ GuideShortcutChip(+ label = stringResource(R.string.epg_show_app_navigation),+ onClick = onShowAppNavigation+ )+ GuideShortcutChip(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ }+ GuideTimeControlsRow(+ onJumpToPreviousDay = onJumpToPreviousDay,+ onPageBackward = onPageBackward,+ onJumpBackwardHalfHour = onJumpBackwardHalfHour,+ onJumpBackward = onJumpBackward,+ onJumpToNow = onJumpToNow,+ onJumpForwardHalfHour = onJumpForwardHalfHour,+ onJumpForward = onJumpForward,+ onPageForward = onPageForward,+ onJumpToPrimeTime = onJumpToPrimeTime,+ onJumpToTomorrow = onJumpToTomorrow,+ onJumpToNextDay = onJumpToNextDay,+ firstChipFocusRequester = optionsFocusRequester+ )+ GuideDayRow(+ selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),+ onDaySelected = onDaySelected+ )+ GuideModeRow(+ selectedMode = uiState.selectedChannelMode,+ onModeSelected = onModeSelected+ )+ GuideDensityRow(+ selectedDensity = uiState.selectedDensity,+ onDensitySelected = onDensitySelected+ )+ GuideViewOptionsRow(+ showScheduledOnly = uiState.showScheduledOnly,+ onToggleScheduledOnly = onToggleScheduledOnly+ )+ GuideFavoritesRow(+ showFavoritesOnly = uiState.showFavoritesOnly,+ onToggleFavoritesOnly = onToggleFavoritesOnly+ )+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 24.dp),+ horizontalArrangement = Arrangement.End+ ) {+ GuideShortcutChip(+ label = stringResource(R.string.epg_refresh_guide),+ onClick = onRefresh+ )+ }+ }+ }+ }+}++@Composable+internal fun CompactGuideProgramDialog(+ channel: Channel,+ program: Program,+ providerLabel: String,+ now: Long,+ onDismiss: () -> Unit,+ onWatchLive: () -> Unit,+ onWatchArchive: (() -> Unit)?,+ onManageEpgMatch: (() -> Unit)?+) {+ var showDetails by rememberSaveable(program.startTime, program.endTime, program.title) { mutableStateOf(false) }+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ GuideModalDialog(onDismiss = onDismiss) {+ Surface(+ modifier = Modifier.widthIn(min = 420.dp, max = 640.dp),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(20.dp)+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ Text(+ text = program.title,+ style = MaterialTheme.typography.headlineSmall,+ color = OnSurface,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ text = "${channel.number}. ${channel.name} | ${format.format(Date(program.startTime))} - ${format.format(Date(program.endTime))}",+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ if (providerLabel.isNotBlank()) {+ Text(+ text = providerLabel,+ style = MaterialTheme.typography.labelMedium,+ color = Primary+ )+ }+ if (now in program.startTime until program.endTime) {+ LinearProgressIndicator(+ progress = { ((now - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f) },+ modifier = Modifier+ .fillMaxWidth()+ .height(4.dp),+ color = Primary,+ trackColor = SurfaceHighlight+ )+ }+ if (showDetails) {+ Text(+ text = program.description.ifBlank { stringResource(R.string.epg_no_info) },+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface,+ maxLines = 6,+ overflow = TextOverflow.Ellipsis+ )+ }+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ TvButton(+ onClick = onWatchLive,+ modifier = Modifier.fillMaxWidth()+ ) {+ Text(stringResource(R.string.epg_watch_live))+ }+ if (onWatchArchive != null) {+ TvButton(+ onClick = onWatchArchive,+ modifier = Modifier.fillMaxWidth(),+ colors = ButtonDefaults.colors(+ containerColor = Primary,+ contentColor = Color.White+ )+ ) {+ Text(stringResource(R.string.epg_watch_archive))+ }+ }+ if (onManageEpgMatch != null) {+ TvButton(+ onClick = onManageEpgMatch,+ modifier = Modifier.fillMaxWidth(),+ colors = ButtonDefaults.colors(+ containerColor = SurfaceHighlight,+ contentColor = OnSurface+ )+ ) {+ Text(stringResource(R.string.epg_override_manage))+ }+ }+ TvButton(+ onClick = { showDetails = !showDetails },+ modifier = Modifier.fillMaxWidth(),+ colors = ButtonDefaults.colors(+ containerColor = SurfaceHighlight,+ contentColor = OnSurface+ )+ ) {+ Text(+ if (showDetails) stringResource(R.string.epg_program_details_hide)+ else stringResource(R.string.epg_program_details_show)+ )+ }+ TextButton(onClick = onDismiss) {+ Text(stringResource(R.string.settings_cancel))+ }+ }+ }+ }+ }+}++@Composable+internal fun EpgOverrideDialog(+ state: EpgOverrideUiState,+ onDismiss: () -> Unit,+ onQueryChange: (String) -> Unit,+ onCandidateSelected: (EpgOverrideCandidate) -> Unit,+ onClearOverride: () -> Unit+) {+ val channel = state.channel ?: return+ val unknownValue = stringResource(R.string.epg_program_unknown_value)+ val currentCandidate = remember(state.currentMapping, state.candidates) {+ state.candidates.firstOrNull {+ it.epgSourceId == state.currentMapping?.epgSourceId &&+ it.xmltvChannelId == state.currentMapping?.xmltvChannelId+ }+ }+ val currentDescriptor = currentCandidate?.let {+ "${it.displayName} • ${it.epgSourceName} • ${it.xmltvChannelId}"+ } ?: (state.currentMapping?.xmltvChannelId ?: unknownValue)+ val currentSummary = when {+ state.currentMapping == null || state.currentMapping.sourceType == EpgSourceType.NONE ->+ stringResource(R.string.epg_override_current_none)+ state.currentMapping.isManualOverride || state.currentMapping.matchType == EpgMatchType.MANUAL ->+ stringResource(R.string.epg_override_current_manual, currentDescriptor)+ state.currentMapping.sourceType == EpgSourceType.PROVIDER ->+ stringResource(R.string.epg_override_current_provider, currentDescriptor)+ else ->+ stringResource(R.string.epg_override_current_external, currentDescriptor)+ }++ GuideModalDialog(onDismiss = onDismiss) {+ Surface(+ modifier = Modifier.widthIn(min = 560.dp, max = 760.dp),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(20.dp)+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ Text(+ text = stringResource(R.string.epg_override_title),+ style = MaterialTheme.typography.headlineSmall,+ color = OnSurface+ )+ Text(+ text = "${channel.number}. ${channel.name}",+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ text = stringResource(R.string.epg_override_current_label),+ style = MaterialTheme.typography.labelMedium,+ color = Primary+ )+ Text(+ text = currentSummary,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ }+ if (!state.error.isNullOrBlank()) {+ Text(+ text = state.error,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error+ )+ }+ if (state.isLoading || state.isSaving) {+ LinearProgressIndicator(+ modifier = Modifier+ .fillMaxWidth()+ .height(3.dp),+ color = Primary,+ trackColor = SurfaceHighlight+ )+ }+ GuideSearchField(+ value = state.searchQuery,+ onValueChange = onQueryChange,+ placeholder = stringResource(R.string.epg_override_search_placeholder),+ modifier = Modifier.fillMaxWidth(),+ onSearch = { onQueryChange(it) }+ )+ if (state.candidates.isEmpty()) {+ Text(+ text = if (state.searchQuery.isBlank()) {+ stringResource(R.string.epg_override_no_candidates)+ } else {+ stringResource(R.string.epg_override_no_search_results)+ },+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ } else {+ LazyColumn(+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(max = 320.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ items(state.candidates) { candidate ->+ val isCurrent = state.currentMapping?.epgSourceId == candidate.epgSourceId &&+ state.currentMapping?.xmltvChannelId == candidate.xmltvChannelId+ TvClickableSurface(+ onClick = {+ if (!state.isSaving) {+ onCandidateSelected(candidate)+ }+ },+ modifier = Modifier.fillMaxWidth(),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isCurrent) SurfaceHighlight else SurfaceElevated,+ focusedContainerColor = SurfaceHighlight,+ contentColor = OnSurface,+ focusedContentColor = OnSurface+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(14.dp)+ )+ )+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 14.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = candidate.displayName,+ style = MaterialTheme.typography.bodyLarge,+ color = OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ if (isCurrent) {+ Text(+ text = stringResource(R.string.epg_override_selected_badge),+ style = MaterialTheme.typography.labelSmall,+ color = Primary+ )+ }+ }+ Text(+ text = "${candidate.epgSourceName} • ${candidate.xmltvChannelId}",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+ }+ }+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ if (state.currentMapping?.isManualOverride == true) {+ TvButton(+ onClick = onClearOverride,+ enabled = !state.isSaving,+ modifier = Modifier.fillMaxWidth(),+ colors = ButtonDefaults.colors(+ containerColor = SurfaceHighlight,+ contentColor = OnSurface+ )+ ) {+ Text(stringResource(R.string.epg_override_clear))+ }+ }+ TextButton(onClick = onDismiss) {+ Text(stringResource(R.string.settings_cancel))+ }+ }+ }+ }+ }+}++@Composable+internal fun GuideCategoryPickerDialog(+ categories: List<Category>,+ selectedCategoryId: Long,+ parentalControlLevel: Int,+ onDismiss: () -> Unit,+ onCategorySelected: (Category) -> Unit+) {+ var query by rememberSaveable { mutableStateOf("") }+ var shouldFocusFirstCategory by rememberSaveable { mutableStateOf(true) }+ val searchFocusRequester = remember { FocusRequester() }+ val firstCategoryFocusRequester = remember { FocusRequester() }+ val filteredCategories = remember(categories, query) {+ val trimmed = query.trim()+ val baseCategories = if (trimmed.isBlank()) {+ categories+ } else {+ categories.filter { it.name.contains(trimmed, ignoreCase = true) }+ }+ val selectedCategory = baseCategories.firstOrNull { it.id == selectedCategoryId }+ buildList {+ if (selectedCategory != null) add(selectedCategory)+ addAll(baseCategories.filterNot { it.id == selectedCategoryId })+ }+ }+ GuideModalDialog(onDismiss = onDismiss) {+ Surface(+ modifier = Modifier+ .fillMaxWidth(0.52f)+ .fillMaxHeight(0.78f)+ .focusGroup(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(22.dp)+ ) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = stringResource(R.string.epg_filter_label),+ style = MaterialTheme.typography.headlineSmall,+ color = OnSurface+ )+ Text(+ text = "${filteredCategories.size} matches",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ GuideShortcutChip(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }++ GuideProgramSearchRow(+ query = query,+ onQueryChange = { query = it },+ onClear = { query = "" },+ focusRequester = searchFocusRequester,+ contentPadding = PaddingValues(0.dp),+ showLabel = false,+ onSearchFieldActivated = {+ shouldFocusFirstCategory = false+ }+ )++ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ itemsIndexed(+ items = filteredCategories,+ key = { index, category -> epgCategoryKey(category, index) }+ ) { _, category ->+ val isSelected = category.id == selectedCategoryId+ val isLocked = isGuideCategoryLocked(category, parentalControlLevel)+ TvClickableSurface(+ onClick = { onCategorySelected(category) },+ modifier = if (category.id == filteredCategories.firstOrNull()?.id) {+ Modifier.focusRequester(firstCategoryFocusRequester)+ } else {+ Modifier+ },+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceHighlight,+ focusedContainerColor = if (isSelected) {+ Primary.copy(alpha = 0.22f)+ } else {+ SurfaceHighlight+ },+ contentColor = if (isSelected) Primary else OnSurface,+ focusedContentColor = if (isSelected) Primary else OnSurface+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(14.dp)+ )+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 14.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = category.name,+ style = MaterialTheme.typography.titleMedium,+ color = if (isSelected) Primary else OnSurface+ )+ if (isLocked) {+ Text(+ text = stringResource(R.string.settings_parental_control),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ } else if (category.count > 0) {+ Text(+ text = "${category.count} channels",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ if (isSelected) {+ Text(+ text = stringResource(R.string.epg_jump_now),+ style = MaterialTheme.typography.labelLarge,+ color = Primary+ )+ }+ }+ }+ }+ }+ }+ }+ }++ LaunchedEffect(filteredCategories, shouldFocusFirstCategory) {+ if (shouldFocusFirstCategory && filteredCategories.isNotEmpty()) {+ firstCategoryFocusRequester.requestFocus()+ shouldFocusFirstCategory = false+ }+ }+}++internal fun epgCategoryKey(category: Category, index: Int): String {+ return "category:${category.id}:${category.name.trim()}:$index"+}+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 1f8f62fb..0d8db2c0 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@@ -242,140 +242,31 @@ fun HomeScreen(}}- if (showPinDialog) {- PinDialog(- onDismissRequest = {- showPinDialog = false- pinError = null- pendingUnlockCategory = null- pendingUnlockChannel = null- },- onPinEntered = { pin ->- scope.launch {- pendingUnlockCategory?.let { category ->- when (val unlockResult = viewModel.unlockCategoryWithPin(category, pin)) {- is com.streamvault.domain.model.Result.Success -> {- showPinDialog = false- pinError = null- pendingUnlockCategory = null- pendingUnlockChannel = null- }- is com.streamvault.domain.model.Result.Error -> {- pinError = if (unlockResult.message == "Incorrect PIN") {- context.getString(R.string.home_incorrect_pin)- } else {- unlockResult.message- }- }- com.streamvault.domain.model.Result.Loading -> Unit- }- return@launch- }-- if (viewModel.verifyPin(pin)) {- showPinDialog = false- pinError = null-- pendingUnlockChannel?.let { channel ->- viewModel.clearPreview()- onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel))- pendingUnlockChannel = null- }-- pendingLockToggleCategory?.let { category ->- viewModel.toggleCategoryLock(category)- pendingLockToggleCategory = null- }-- pendingUnlockCategory = null- pendingUnlockChannel = null- } else {- pinError = context.getString(R.string.home_incorrect_pin)- }- }- },- error = pinError- )- }-- if (uiState.selectedCategoryForOptions != null) {- val category = uiState.selectedCategoryForOptions!!- val isCategoryLocked =- (category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&- kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds- CategoryOptionsDialog(- category = category,- onDismissRequest = { viewModel.dismissCategoryOptions() },- onSetAsDefault = if (isCategoryLocked) null else {- {- viewModel.setDefaultCategory(category)- viewModel.dismissCategoryOptions()- }- },- isPinned = category.id in uiState.pinnedCategoryIds,- onTogglePinned = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {- { viewModel.toggleCategoryPinned(category) }- } else null,- onHide = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {- { viewModel.hideCategory(category) }- } else null,- onRename = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {- { viewModel.requestRenameGroup(category) }- } else null,- onToggleLock = {- viewModel.dismissCategoryOptions()- pendingLockToggleCategory = category- showPinDialog = true- },- onDelete = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {- {- viewModel.requestDeleteGroup(category)- }- } else null,- onReorderChannels = if (!isCategoryLocked && category.isVirtual && category.id != VirtualCategoryIds.RECENT) {- { viewModel.enterChannelReorderMode(category) }- } else null- )- }-- if (showAddQuickFilterDialog) {- var pendingFilter by rememberSaveable { mutableStateOf("") }- PremiumDialog(- title = stringResource(R.string.home_quick_filters_add_title),- subtitle = stringResource(R.string.home_quick_filters_add_subtitle),- onDismissRequest = { showAddQuickFilterDialog = false },- widthFraction = 0.42f,- content = {- SearchInput(- value = pendingFilter,- onValueChange = { pendingFilter = it },- placeholder = stringResource(R.string.home_quick_filters_add_placeholder),- modifier = Modifier.fillMaxWidth()- )- PremiumDialogActionButton(- label = stringResource(R.string.home_quick_filters_add_action),- enabled = pendingFilter.isNotBlank(),- onClick = {- val normalized = pendingFilter.trim()- val isDuplicate = uiState.savedCategoryFilters.any {- it.equals(normalized, ignoreCase = true)- }- viewModel.addLiveTvCategoryFilter(pendingFilter)- if (normalized.isNotBlank() && !isDuplicate) {- showAddQuickFilterDialog = false- }- }- )- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = { showAddQuickFilterDialog = false }- )- }- )- }+ HomeDialogsHost(+ uiState = uiState,+ multiViewViewModel = multiViewViewModel,+ viewModel = viewModel,+ showPinDialog = showPinDialog,+ pinError = pinError,+ pendingUnlockCategory = pendingUnlockCategory,+ pendingUnlockChannel = pendingUnlockChannel,+ pendingLockToggleCategory = pendingLockToggleCategory,+ showAddQuickFilterDialog = showAddQuickFilterDialog,+ showSplitManagerDialog = showSplitManagerDialog,+ pendingSplitPlannerChannel = pendingSplitPlannerChannel,+ onShowPinDialogChange = { showPinDialog = it },+ onPinErrorChange = { pinError = it },+ onPendingUnlockCategoryChange = { pendingUnlockCategory = it },+ onPendingUnlockChannelChange = { pendingUnlockChannel = it },+ onPendingLockToggleCategoryChange = { pendingLockToggleCategory = it },+ onShowAddQuickFilterDialogChange = { showAddQuickFilterDialog = it },+ onShowSplitManagerDialogChange = { showSplitManagerDialog = it },+ onPendingSplitPlannerChannelChange = { pendingSplitPlannerChannel = it },+ onChannelClick = onChannelClick,+ resolveProviderForChannel = resolveProviderForChannel,+ onNavigate = onNavigate,+ scope = scope+ )Box(modifier = Modifier.fillMaxSize()) {AppScreenScaffold(@@ -602,6 +493,8 @@ fun HomeScreen(restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> FocusRestoreTarget.CATEGORYcanRestoreChannel -> FocusRestoreTarget.CHANNELcanRestoreCategory -> FocusRestoreTarget.CATEGORY+ uiState.filteredChannels.isNotEmpty() -> FocusRestoreTarget.CHANNEL+ uiState.categories.isNotEmpty() -> FocusRestoreTarget.CATEGORYelse -> null}if (pendingRestoreTarget != null) {@@ -652,6 +545,8 @@ fun HomeScreen(restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory -> FocusRestoreTarget.CATEGORYcanRestoreChannel -> FocusRestoreTarget.CHANNELcanRestoreCategory -> FocusRestoreTarget.CATEGORY+ uiState.filteredChannels.isNotEmpty() -> FocusRestoreTarget.CHANNEL+ uiState.categories.isNotEmpty() -> FocusRestoreTarget.CATEGORYelse -> null}if (pendingRestoreTarget != null) {@@ -1273,570 +1168,6 @@ fun HomeScreen()}- if (pendingSplitPlannerChannel != null) {- MultiViewPlannerDialog(- pendingChannel = pendingSplitPlannerChannel,- onDismiss = { pendingSplitPlannerChannel = null },- onLaunch = {- pendingSplitPlannerChannel = null- viewModel.onDismissDialog()- viewModel.clearPreview()- onNavigate(Routes.MULTI_VIEW)- },- viewModel = multiViewViewModel- )- }-- if (uiState.showDialog && uiState.selectedChannelForDialog != null && pendingSplitPlannerChannel == null) {- val channel = uiState.selectedChannelForDialog!!- com.streamvault.app.ui.components.dialogs.AddToGroupDialog(- contentTitle = channel.name,- channel = channel,- groups = uiState.categories.filter { it.isVirtual && it.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT) },- isFavorite = channel.isFavorite,- memberOfGroups = uiState.dialogGroupMemberships,- onDismiss = { viewModel.onDismissDialog() },- onToggleFavorite = {- if (channel.isFavorite) viewModel.removeFavorite(channel) else viewModel.addFavorite(channel)- },- onAddToGroup = { group -> viewModel.addToGroup(channel, group) },- onRemoveFromGroup = { group -> viewModel.removeFromGroup(channel, group) },- onCreateGroup = { name -> viewModel.createCustomGroup(name) },- isQueuedForSplitScreen = multiViewViewModel.isQueued(channel.id),- onOpenSplitScreenPlanner = { pendingSplitPlannerChannel = channel }- )- }-- if (uiState.showRenameGroupDialog && uiState.groupToRename != null) {- RenameGroupDialog(- initialName = uiState.groupToRename!!.name,- errorMessage = uiState.renameGroupError,- onDismissRequest = { viewModel.cancelRenameGroup() },- onConfirm = { name -> viewModel.confirmRenameGroup(name) }- )- }-- // Split Screen manager dialog (opened from the header button)- if (showSplitManagerDialog) {- MultiViewPlannerDialog(- pendingChannel = null,- onDismiss = { showSplitManagerDialog = false },- onLaunch = {- showSplitManagerDialog = false- viewModel.clearPreview()- onNavigate(Routes.MULTI_VIEW)- },- viewModel = multiViewViewModel- )- }-- if (uiState.showDeleteGroupDialog && uiState.groupToDelete != null) {- val group = uiState.groupToDelete!!-- // Fix for ghost clicks: Debounce interaction for 500ms to ignore long-press release- var canInteract by remember { mutableStateOf(false) }- LaunchedEffect(Unit) {- kotlinx.coroutines.delay(500)- canInteract = true- }-- val safeDismiss = {- if (canInteract) viewModel.cancelDeleteGroup()- }-- PremiumDialog(- title = stringResource(R.string.home_delete_group_title),- subtitle = stringResource(R.string.home_delete_group_body, group.name),- onDismissRequest = safeDismiss,- widthFraction = 0.36f,- content = {},- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.home_delete_group_cancel),- onClick = safeDismiss- )- PremiumDialogFooterButton(- label = stringResource(R.string.home_delete_group_confirm),- onClick = { if (canInteract) viewModel.confirmDeleteGroup() },- destructive = true- )- }- )- }--}--@Composable-private fun CompactSplitLauncherButton(- slotCount: Int,- onClick: () -> Unit,- modifier: Modifier = Modifier-) {- TvClickableSurface(- onClick = onClick,- modifier = modifier- .widthIn(min = 112.dp)- .height(34.dp),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.18f),- focusedContainerColor = Primary.copy(alpha = 0.3f),- contentColor = OnBackground- ),- border = ClickableSurfaceDefaults.border(- border = androidx.tv.material3.Border(- border = BorderStroke(1.dp, Primary.copy(alpha = 0.55f))- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier- .padding(horizontal = 10.dp, vertical = 6.dp),- horizontalArrangement = Arrangement.spacedBy(6.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.action_split),- style = MaterialTheme.typography.labelSmall,- color = OnBackground,- maxLines = 1- )- Text(- text = stringResource(R.string.label_slots_count, slotCount),- style = MaterialTheme.typography.labelSmall,- color = PrimaryLight,- maxLines = 1- )- }- }-}--@Composable-private fun LivePreviewPane(- channel: Channel?,- playerEngine: com.streamvault.player.PlayerEngine?,- isLoading: Boolean,- errorMessage: String?,- modifier: Modifier = Modifier-) {- Surface(- modifier = modifier,- shape = RoundedCornerShape(18.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated.copy(alpha = 0.72f))- ) {- Column(- modifier = Modifier- .fillMaxSize()- .padding(12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = stringResource(R.string.live_preview_title),- style = MaterialTheme.typography.titleSmall,- color = Primary- )-- Box(- modifier = Modifier- .fillMaxWidth()- .aspectRatio(16f / 9f)- .background(Color.Black, RoundedCornerShape(16.dp)),- contentAlignment = Alignment.Center- ) {- if (channel != null && playerEngine != null && errorMessage == null) {- AndroidView(- factory = { context ->- playerEngine.createRenderView(- context = context,- resizeMode = PlayerSurfaceResizeMode.FIT- )- },- update = { renderView ->- playerEngine.bindRenderView(- renderView = renderView,- resizeMode = PlayerSurfaceResizeMode.FIT- )- },- onRelease = { renderView ->- playerEngine.releaseRenderView(renderView)- },- modifier = Modifier.fillMaxSize()- )- } else {- Column(- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(8.dp),- modifier = Modifier.padding(horizontal = 20.dp)- ) {- Text(- text = stringResource(R.string.live_preview_placeholder_title),- style = MaterialTheme.typography.titleSmall,- color = OnBackground,- textAlign = androidx.compose.ui.text.style.TextAlign.Center- )- Text(- text = errorMessage ?: stringResource(R.string.live_preview_placeholder_subtitle),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- textAlign = androidx.compose.ui.text.style.TextAlign.Center- )- }- }-- if (isLoading && channel != null) {- Row(- modifier = Modifier- .background(Color.Black.copy(alpha = 0.62f), RoundedCornerShape(12.dp))- .padding(horizontal = 14.dp, vertical = 10.dp),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- CircularProgressIndicator(- color = Primary,- strokeWidth = 2.dp,- modifier = Modifier.size(18.dp)- )- Text(- text = stringResource(R.string.live_preview_loading),- style = MaterialTheme.typography.bodyMedium,- color = Color.White- )- }- }- }-- if (channel != null) {- Text(- text = channel.name,- style = MaterialTheme.typography.titleMedium,- color = OnBackground- )- channel.currentProgram?.let { program ->- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(- text = program.title,- style = MaterialTheme.typography.bodyLarge,- color = OnBackground- )- Text(- text = stringResource(R.string.time_range_format, formatProgramTime(program.startTime), formatProgramTime(program.endTime)),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- LinearProgressIndicator(- progress = { program.progressPercent() },- modifier = Modifier- .fillMaxWidth()- .height(4.dp),- color = Primary,- trackColor = SurfaceHighlight- )- if (program.description.isNotBlank()) {- Text(- text = program.description,- style = MaterialTheme.typography.bodySmall,- color = OnSurface,- maxLines = 4,- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis- )- }- }- } ?: Text(- text = stringResource(R.string.live_preview_no_epg),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )-- Text(- text = stringResource(R.string.live_preview_open_hint),- style = MaterialTheme.typography.labelMedium,- color = Primary- )- }- }- }--}--private fun formatProgramTime(timestampMs: Long): String {- if (timestampMs <= 0L) return "--:--"- return SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(timestampMs))-}--@Composable-private fun CategoryItem(- category: Category,- isSelected: Boolean,- isLocked: Boolean = false,- isPinned: Boolean = false,- focusRequester: FocusRequester,- onClick: () -> Unit,- onLongClick: (() -> Unit)? = null,- onJumpToSearch: () -> Boolean,- onJumpToContent: () -> Boolean,- onFocused: () -> Unit-) {- var isFocused by remember { mutableStateOf(false) }-- TvClickableSurface(- onClick = onClick,- onLongClick = onLongClick,- modifier = Modifier- .fillMaxWidth()- .padding(vertical = 2.dp)- .focusRequester(focusRequester)- .onFocusChanged {- isFocused = it.isFocused- if (it.isFocused) onFocused()- }- .onPreviewKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {- onJumpToSearch()- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {- onJumpToContent()- }- else -> false- }- } else false- },- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,- focusedContainerColor = SurfaceHighlight.copy(alpha = 0.82f),- contentColor = if (isSelected) Primary else OnSurface- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, Primary.copy(alpha = 0.85f)),- shape = RoundedCornerShape(10.dp)- )- )- ) {- Row(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween- ) {- if (isPinned) {- PinnedCategoryGlyph(- tint = if (isFocused) OnBackground else if (isSelected) Primary else OnSurfaceDim,- modifier = Modifier.padding(end = 8.dp)- )- }- Text(- text = category.name,- style = MaterialTheme.typography.bodyMedium,- maxLines = 1,- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,- color = if (isFocused) OnBackground else if (isSelected) Primary else OnSurface,- modifier = Modifier.weight(1f)- )-- Text(- text = category.count.toString(),- style = MaterialTheme.typography.labelMedium,- color = if (isFocused) OnBackground else OnSurfaceDim,- modifier = Modifier.padding(start = 10.dp)- )-- if (isLocked) {- Text(- text = stringResource(R.string.home_locked_short),- style = MaterialTheme.typography.labelSmall,- color = if (isFocused) OnBackground else OnSurfaceDim,- modifier = Modifier.padding(start = 8.dp)- )- }- }- }-}--@Composable-private fun PinnedCategoryGlyph(- tint: Color,- modifier: Modifier = Modifier-) {- Canvas(modifier = modifier.size(12.dp)) {- val headRadius = size.minDimension * 0.18f- val centerX = size.width * 0.45f- val headCenterY = size.height * 0.26f- drawCircle(- color = tint,- radius = headRadius,- center = androidx.compose.ui.geometry.Offset(centerX, headCenterY)- )- drawLine(- color = tint,- start = androidx.compose.ui.geometry.Offset(centerX, headCenterY + headRadius * 0.6f),- end = androidx.compose.ui.geometry.Offset(centerX, size.height * 0.8f),- strokeWidth = size.minDimension * 0.12f- )- drawLine(- color = tint,- start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.38f),- end = androidx.compose.ui.geometry.Offset(size.width * 0.72f, size.height * 0.38f),- strokeWidth = size.minDimension * 0.14f- )- }}// SearchInput moved to its own component file--@Composable-fun ReorderSidePanel(- channels: List<Channel>,- onMoveUp: (Channel) -> Unit,- onMoveDown: (Channel) -> Unit,- onSave: () -> Unit,- onCancel: () -> Unit-) {- val screenWidth = LocalConfiguration.current.screenWidthDp.dp- val isTelevisionDevice = rememberIsTelevisionDevice()- val panelWidth = if (screenWidth < 900.dp) {- (screenWidth * 0.36f).coerceIn(188.dp, 220.dp)- } else if (!isTelevisionDevice && screenWidth < 1280.dp) {- (screenWidth * 0.28f).coerceIn(220.dp, 252.dp)- } else {- 272.dp- }- var draggingChannel by remember { mutableStateOf<Channel?>(null) }-- // Focus requester to trap focus inside the panel- val panelFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }-- LaunchedEffect(Unit) {- panelFocusRequester.requestFocus()- }-- Box(- modifier = Modifier- .fillMaxHeight()- .width(panelWidth)- .background(SurfaceElevated)- .padding(16.dp)- .focusRequester(panelFocusRequester)- .focusGroup() // Traps D-pad focus in this container- ) {- Column(modifier = Modifier.fillMaxSize()) {- // Header- Text(- stringResource(R.string.home_reorder_channels),- style = MaterialTheme.typography.titleMedium,- color = Primary,- modifier = Modifier.padding(bottom = 12.dp)- )-- // Actions- Row(- horizontalArrangement = Arrangement.spacedBy(8.dp),- modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)- ) {- TvButton(- onClick = onSave,- colors = ButtonDefaults.colors(- containerColor = Primary,- contentColor = Color.White- ),- modifier = Modifier.weight(1f)- ) { Text(stringResource(R.string.action_save), maxLines = 1) }-- TvButton(- onClick = onCancel,- colors = ButtonDefaults.colors(- containerColor = MaterialTheme.colorScheme.surfaceVariant,- contentColor = OnSurface- ),- modifier = Modifier.weight(1f)- ) { Text(stringResource(R.string.action_cancel), maxLines = 1) }- }-- // List- androidx.compose.foundation.lazy.LazyColumn(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- items(channels.size, key = { channels[it].id }) { index ->- val channel = channels[index]- var isFocused by remember { mutableStateOf(false) }- val isDraggingThis = draggingChannel == channel-- TvClickableSurface(- onClick = {- draggingChannel = if (isDraggingThis) null else channel- },- modifier = Modifier- .fillMaxWidth()- .onFocusChanged { isFocused = it.isFocused }- .onKeyEvent { event ->- if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {- if (isDraggingThis) {- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_UP -> {- onMoveUp(channel)- true- }- android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {- onMoveDown(channel)- true- }- else -> false- }- } else {- // Trap focus left/right so we don't accidentally exit panel- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT ||- event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT) {- true- } else {- false- }- }- } else false- },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- focusedContainerColor = if (isDraggingThis) Primary else Primary.copy(alpha = 0.2f),- containerColor = if (isDraggingThis) Primary.copy(alpha = 0.5f) else Color.Transparent- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(2.dp, FocusBorder),- shape = RoundedCornerShape(8.dp)- )- )- ) {- Row(- modifier = Modifier.padding(12.dp).fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically- ) {- if (isDraggingThis) {- Text(stringResource(R.string.action_move), color = Color.White, modifier = Modifier.padding(end = 8.dp))- }- Text(- stringResource(R.string.channel_number_name_format, index + 1, channel.name),- modifier = Modifier.weight(1f),- style = MaterialTheme.typography.bodyMedium,- color = if (isDraggingThis) Color.White else if (isFocused) OnBackground else OnSurface,- maxLines = 1,- overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis- )- }- }- }- }- }-- // Helper Text- Text(- if (draggingChannel != null) "UP/DOWN to move.\nOK to drop." else "OK to grab channel.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- modifier = Modifier.padding(top = 16.dp).fillMaxWidth(),- textAlign = androidx.compose.ui.text.style.TextAlign.Center- )- }- }diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.ktnew file mode 100644index 00000000..221e9452--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreenDialogs.kt@@ -0,0 +1,288 @@+package com.streamvault.app.ui.screens.home++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import com.streamvault.app.R+import com.streamvault.app.navigation.Routes+import com.streamvault.app.ui.components.SearchInput+import com.streamvault.app.ui.components.dialogs.AddToGroupDialog+import com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog+import com.streamvault.app.ui.components.dialogs.PinDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButton+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.components.dialogs.RenameGroupDialog+import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog+import com.streamvault.app.ui.screens.multiview.MultiViewViewModel+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.VirtualCategoryIds+import com.streamvault.domain.repository.ChannelRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++@Composable+internal fun HomeDialogsHost(+ uiState: HomeUiState,+ multiViewViewModel: MultiViewViewModel,+ viewModel: HomeViewModel,+ showPinDialog: Boolean,+ pinError: String?,+ pendingUnlockCategory: Category?,+ pendingUnlockChannel: Channel?,+ pendingLockToggleCategory: Category?,+ showAddQuickFilterDialog: Boolean,+ showSplitManagerDialog: Boolean,+ pendingSplitPlannerChannel: Channel?,+ onShowPinDialogChange: (Boolean) -> Unit,+ onPinErrorChange: (String?) -> Unit,+ onPendingUnlockCategoryChange: (Category?) -> Unit,+ onPendingUnlockChannelChange: (Channel?) -> Unit,+ onPendingLockToggleCategoryChange: (Category?) -> Unit,+ onShowAddQuickFilterDialogChange: (Boolean) -> Unit,+ onShowSplitManagerDialogChange: (Boolean) -> Unit,+ onPendingSplitPlannerChannelChange: (Channel?) -> Unit,+ onChannelClick: (Channel, Category?, Provider?) -> Unit,+ resolveProviderForChannel: (Channel) -> Provider?,+ onNavigate: (String) -> Unit,+ scope: CoroutineScope+) {+ val context = LocalContext.current++ if (showPinDialog) {+ PinDialog(+ onDismissRequest = {+ onShowPinDialogChange(false)+ onPinErrorChange(null)+ onPendingUnlockCategoryChange(null)+ onPendingUnlockChannelChange(null)+ },+ onPinEntered = { pin ->+ scope.launch {+ pendingUnlockCategory?.let { category ->+ when (val unlockResult = viewModel.unlockCategoryWithPin(category, pin)) {+ is Result.Success -> {+ onShowPinDialogChange(false)+ onPinErrorChange(null)+ onPendingUnlockCategoryChange(null)+ onPendingUnlockChannelChange(null)+ }+ is Result.Error -> {+ onPinErrorChange(+ if (unlockResult.message == "Incorrect PIN") {+ context.getString(R.string.home_incorrect_pin)+ } else {+ unlockResult.message+ }+ )+ }+ Result.Loading -> Unit+ }+ return@launch+ }++ if (viewModel.verifyPin(pin)) {+ onShowPinDialogChange(false)+ onPinErrorChange(null)++ pendingUnlockChannel?.let { channel ->+ viewModel.clearPreview()+ onChannelClick(channel, uiState.selectedCategory, resolveProviderForChannel(channel))+ onPendingUnlockChannelChange(null)+ }++ pendingLockToggleCategory?.let { category ->+ viewModel.toggleCategoryLock(category)+ onPendingLockToggleCategoryChange(null)+ }++ onPendingUnlockCategoryChange(null)+ onPendingUnlockChannelChange(null)+ } else {+ onPinErrorChange(context.getString(R.string.home_incorrect_pin))+ }+ }+ },+ error = pinError+ )+ }++ if (uiState.selectedCategoryForOptions != null) {+ val category = uiState.selectedCategoryForOptions+ val isCategoryLocked =+ (category.isAdult || category.isUserProtected) &&+ uiState.parentalControlLevel == 1 &&+ kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds+ CategoryOptionsDialog(+ category = category,+ onDismissRequest = { viewModel.dismissCategoryOptions() },+ onSetAsDefault = if (isCategoryLocked) null else {+ {+ viewModel.setDefaultCategory(category)+ viewModel.dismissCategoryOptions()+ }+ },+ isPinned = category.id in uiState.pinnedCategoryIds,+ onTogglePinned = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {+ { viewModel.toggleCategoryPinned(category) }+ } else null,+ onHide = if (!isCategoryLocked && !category.isVirtual && category.id != ChannelRepository.ALL_CHANNELS_ID) {+ { viewModel.hideCategory(category) }+ } else null,+ onRename = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {+ { viewModel.requestRenameGroup(category) }+ } else null,+ onToggleLock = {+ viewModel.dismissCategoryOptions()+ onPendingLockToggleCategoryChange(category)+ onShowPinDialogChange(true)+ },+ onDelete = if (!isCategoryLocked && category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {+ { viewModel.requestDeleteGroup(category) }+ } else null,+ onReorderChannels = if (!isCategoryLocked && category.isVirtual && category.id != VirtualCategoryIds.RECENT) {+ { viewModel.enterChannelReorderMode(category) }+ } else null+ )+ }++ if (showAddQuickFilterDialog) {+ var pendingFilter by rememberSaveable { mutableStateOf("") }+ PremiumDialog(+ title = stringResource(R.string.home_quick_filters_add_title),+ subtitle = stringResource(R.string.home_quick_filters_add_subtitle),+ onDismissRequest = { onShowAddQuickFilterDialogChange(false) },+ widthFraction = 0.42f,+ content = {+ SearchInput(+ value = pendingFilter,+ onValueChange = { pendingFilter = it },+ placeholder = stringResource(R.string.home_quick_filters_add_placeholder),+ modifier = Modifier.fillMaxWidth()+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.home_quick_filters_add_action),+ enabled = pendingFilter.isNotBlank(),+ onClick = {+ val normalized = pendingFilter.trim()+ val isDuplicate = uiState.savedCategoryFilters.any {+ it.equals(normalized, ignoreCase = true)+ }+ viewModel.addLiveTvCategoryFilter(pendingFilter)+ if (normalized.isNotBlank() && !isDuplicate) {+ onShowAddQuickFilterDialogChange(false)+ }+ }+ )+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = { onShowAddQuickFilterDialogChange(false) }+ )+ }+ )+ }++ if (pendingSplitPlannerChannel != null) {+ MultiViewPlannerDialog(+ pendingChannel = pendingSplitPlannerChannel,+ onDismiss = { onPendingSplitPlannerChannelChange(null) },+ onLaunch = {+ onPendingSplitPlannerChannelChange(null)+ viewModel.onDismissDialog()+ viewModel.clearPreview()+ onNavigate(Routes.MULTI_VIEW)+ },+ viewModel = multiViewViewModel+ )+ }++ if (uiState.showDialog && uiState.selectedChannelForDialog != null && pendingSplitPlannerChannel == null) {+ val channel = uiState.selectedChannelForDialog+ AddToGroupDialog(+ contentTitle = channel.name,+ channel = channel,+ groups = uiState.categories.filter {+ it.isVirtual && it.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)+ },+ isFavorite = channel.isFavorite,+ memberOfGroups = uiState.dialogGroupMemberships,+ onDismiss = { viewModel.onDismissDialog() },+ onToggleFavorite = {+ if (channel.isFavorite) viewModel.removeFavorite(channel) else viewModel.addFavorite(channel)+ },+ onAddToGroup = { group -> viewModel.addToGroup(channel, group) },+ onRemoveFromGroup = { group -> viewModel.removeFromGroup(channel, group) },+ onCreateGroup = { name -> viewModel.createCustomGroup(name) },+ isQueuedForSplitScreen = multiViewViewModel.isQueued(channel.id),+ onOpenSplitScreenPlanner = { onPendingSplitPlannerChannelChange(channel) }+ )+ }++ if (uiState.showRenameGroupDialog && uiState.groupToRename != null) {+ RenameGroupDialog(+ initialName = uiState.groupToRename.name,+ errorMessage = uiState.renameGroupError,+ onDismissRequest = { viewModel.cancelRenameGroup() },+ onConfirm = { name -> viewModel.confirmRenameGroup(name) }+ )+ }++ if (showSplitManagerDialog) {+ MultiViewPlannerDialog(+ pendingChannel = null,+ onDismiss = { onShowSplitManagerDialogChange(false) },+ onLaunch = {+ onShowSplitManagerDialogChange(false)+ viewModel.clearPreview()+ onNavigate(Routes.MULTI_VIEW)+ },+ viewModel = multiViewViewModel+ )+ }++ if (uiState.showDeleteGroupDialog && uiState.groupToDelete != null) {+ val group = uiState.groupToDelete+ var canInteract by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) {+ delay(500)+ canInteract = true+ }++ val safeDismiss = {+ if (canInteract) viewModel.cancelDeleteGroup()+ }++ PremiumDialog(+ title = stringResource(R.string.home_delete_group_title),+ subtitle = stringResource(R.string.home_delete_group_body, group.name),+ onDismissRequest = safeDismiss,+ widthFraction = 0.36f,+ content = {},+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.home_delete_group_cancel),+ onClick = safeDismiss+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.home_delete_group_confirm),+ onClick = { if (canInteract) viewModel.confirmDeleteGroup() },+ destructive = true+ )+ }+ )+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.ktnew file mode 100644index 00000000..c64a0bd0--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeSidebarComponents.kt@@ -0,0 +1,543 @@+package com.streamvault.app.ui.screens.home++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.focusGroup+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.input.key.onKeyEvent+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.tv.material3.Border+import androidx.tv.material3.ButtonDefaults+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnBackground+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.PrimaryLight+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.player.PlayerEngine+import com.streamvault.player.PlayerSurfaceResizeMode+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++@Composable+internal fun CompactSplitLauncherButton(+ slotCount: Int,+ onClick: () -> Unit,+ modifier: Modifier = Modifier+) {+ TvClickableSurface(+ onClick = onClick,+ modifier = modifier+ .widthIn(min = 112.dp)+ .height(34.dp),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.18f),+ focusedContainerColor = Primary.copy(alpha = 0.3f),+ contentColor = OnBackground+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, Primary.copy(alpha = 0.55f))+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.action_split),+ style = MaterialTheme.typography.labelSmall,+ color = OnBackground,+ maxLines = 1+ )+ Text(+ text = stringResource(R.string.label_slots_count, slotCount),+ style = MaterialTheme.typography.labelSmall,+ color = PrimaryLight,+ maxLines = 1+ )+ }+ }+}++@Composable+internal fun LivePreviewPane(+ channel: Channel?,+ playerEngine: PlayerEngine?,+ isLoading: Boolean,+ errorMessage: String?,+ modifier: Modifier = Modifier+) {+ Surface(+ modifier = modifier,+ shape = RoundedCornerShape(18.dp),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated.copy(alpha = 0.72f))+ ) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = stringResource(R.string.live_preview_title),+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )++ Box(+ modifier = Modifier+ .fillMaxWidth()+ .aspectRatio(16f / 9f)+ .background(Color.Black, RoundedCornerShape(16.dp)),+ contentAlignment = Alignment.Center+ ) {+ if (channel != null && playerEngine != null && errorMessage == null) {+ AndroidView(+ factory = { context ->+ playerEngine.createRenderView(+ context = context,+ resizeMode = PlayerSurfaceResizeMode.FIT+ )+ },+ update = { renderView ->+ playerEngine.bindRenderView(+ renderView = renderView,+ resizeMode = PlayerSurfaceResizeMode.FIT+ )+ },+ onRelease = { renderView ->+ playerEngine.releaseRenderView(renderView)+ },+ modifier = Modifier.fillMaxSize()+ )+ } else {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.padding(horizontal = 20.dp)+ ) {+ Text(+ text = stringResource(R.string.live_preview_placeholder_title),+ style = MaterialTheme.typography.titleSmall,+ color = OnBackground,+ textAlign = TextAlign.Center+ )+ Text(+ text = errorMessage ?: stringResource(R.string.live_preview_placeholder_subtitle),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ textAlign = TextAlign.Center+ )+ }+ }++ if (isLoading && channel != null) {+ Row(+ modifier = Modifier+ .background(Color.Black.copy(alpha = 0.62f), RoundedCornerShape(12.dp))+ .padding(horizontal = 14.dp, vertical = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ CircularProgressIndicator(+ color = Primary,+ strokeWidth = 2.dp,+ modifier = Modifier.size(18.dp)+ )+ Text(+ text = stringResource(R.string.live_preview_loading),+ style = MaterialTheme.typography.bodyMedium,+ color = Color.White+ )+ }+ }+ }++ if (channel != null) {+ Text(+ text = channel.name,+ style = MaterialTheme.typography.titleMedium,+ color = OnBackground+ )+ channel.currentProgram?.let { program ->+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ text = program.title,+ style = MaterialTheme.typography.bodyLarge,+ color = OnBackground+ )+ Text(+ text = stringResource(+ R.string.time_range_format,+ formatProgramTime(program.startTime),+ formatProgramTime(program.endTime)+ ),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ LinearProgressIndicator(+ progress = { program.progressPercent() },+ modifier = Modifier+ .fillMaxWidth()+ .height(4.dp),+ color = Primary,+ trackColor = SurfaceHighlight+ )+ if (program.description.isNotBlank()) {+ Text(+ text = program.description,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface,+ maxLines = 4,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ } ?: Text(+ text = stringResource(R.string.live_preview_no_epg),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )++ Text(+ text = stringResource(R.string.live_preview_open_hint),+ style = MaterialTheme.typography.labelMedium,+ color = Primary+ )+ }+ }+ }+}++private fun formatProgramTime(timestampMs: Long): String {+ if (timestampMs <= 0L) return "--:--"+ return SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(timestampMs))+}++@Composable+internal fun CategoryItem(+ category: Category,+ isSelected: Boolean,+ isLocked: Boolean = false,+ isPinned: Boolean = false,+ focusRequester: FocusRequester,+ onClick: () -> Unit,+ onLongClick: (() -> Unit)? = null,+ onJumpToSearch: () -> Boolean,+ onJumpToContent: () -> Boolean,+ onFocused: () -> Unit+) {+ var isFocused by remember { mutableStateOf(false) }++ TvClickableSurface(+ onClick = onClick,+ onLongClick = onLongClick,+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 2.dp)+ .focusRequester(focusRequester)+ .onFocusChanged {+ isFocused = it.isFocused+ if (it.isFocused) onFocused()+ }+ .onPreviewKeyEvent { event ->+ if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> onJumpToSearch()+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> onJumpToContent()+ else -> false+ }+ } else false+ },+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,+ focusedContainerColor = SurfaceHighlight.copy(alpha = 0.82f),+ contentColor = if (isSelected) Primary else OnSurface+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, Primary.copy(alpha = 0.85f)),+ shape = RoundedCornerShape(10.dp)+ )+ )+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween+ ) {+ if (isPinned) {+ PinnedCategoryGlyph(+ tint = if (isFocused) OnBackground else if (isSelected) Primary else OnSurfaceDim,+ modifier = Modifier.padding(end = 8.dp)+ )+ }+ Text(+ text = category.name,+ style = MaterialTheme.typography.bodyMedium,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ color = if (isFocused) OnBackground else if (isSelected) Primary else OnSurface,+ modifier = Modifier.weight(1f)+ )++ Text(+ text = category.count.toString(),+ style = MaterialTheme.typography.labelMedium,+ color = if (isFocused) OnBackground else OnSurfaceDim,+ modifier = Modifier.padding(start = 10.dp)+ )++ if (isLocked) {+ Text(+ text = stringResource(R.string.home_locked_short),+ style = MaterialTheme.typography.labelSmall,+ color = if (isFocused) OnBackground else OnSurfaceDim,+ modifier = Modifier.padding(start = 8.dp)+ )+ }+ }+ }+}++@Composable+private fun PinnedCategoryGlyph(+ tint: Color,+ modifier: Modifier = Modifier+) {+ Canvas(modifier = modifier.size(12.dp)) {+ val headRadius = size.minDimension * 0.18f+ val centerX = size.width * 0.45f+ val headCenterY = size.height * 0.26f+ drawCircle(+ color = tint,+ radius = headRadius,+ center = androidx.compose.ui.geometry.Offset(centerX, headCenterY)+ )+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(centerX, headCenterY + headRadius * 0.6f),+ end = androidx.compose.ui.geometry.Offset(centerX, size.height * 0.8f),+ strokeWidth = size.minDimension * 0.12f+ )+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.38f),+ end = androidx.compose.ui.geometry.Offset(size.width * 0.72f, size.height * 0.38f),+ strokeWidth = size.minDimension * 0.14f+ )+ }+}++@Composable+internal fun ReorderSidePanel(+ channels: List<Channel>,+ onMoveUp: (Channel) -> Unit,+ onMoveDown: (Channel) -> Unit,+ onSave: () -> Unit,+ onCancel: () -> Unit+) {+ val screenWidth = LocalConfiguration.current.screenWidthDp.dp+ val isTelevisionDevice = rememberIsTelevisionDevice()+ val panelWidth = if (screenWidth < 900.dp) {+ (screenWidth * 0.36f).coerceIn(188.dp, 220.dp)+ } else if (!isTelevisionDevice && screenWidth < 1280.dp) {+ (screenWidth * 0.28f).coerceIn(220.dp, 252.dp)+ } else {+ 272.dp+ }+ var draggingChannel by remember { mutableStateOf<Channel?>(null) }+ val panelFocusRequester = remember { FocusRequester() }++ LaunchedEffect(Unit) {+ panelFocusRequester.requestFocus()+ }++ Box(+ modifier = Modifier+ .fillMaxHeight()+ .width(panelWidth)+ .background(SurfaceElevated)+ .padding(16.dp)+ .focusRequester(panelFocusRequester)+ .focusGroup()+ ) {+ Column(modifier = Modifier.fillMaxSize()) {+ Text(+ stringResource(R.string.home_reorder_channels),+ style = MaterialTheme.typography.titleMedium,+ color = Primary,+ modifier = Modifier.padding(bottom = 12.dp)+ )++ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier+ .fillMaxWidth()+ .padding(bottom = 16.dp)+ ) {+ TvButton(+ onClick = onSave,+ colors = ButtonDefaults.colors(+ containerColor = Primary,+ contentColor = Color.White+ ),+ modifier = Modifier.weight(1f)+ ) { Text(stringResource(R.string.action_save), maxLines = 1) }++ TvButton(+ onClick = onCancel,+ colors = ButtonDefaults.colors(+ containerColor = MaterialTheme.colorScheme.surfaceVariant,+ contentColor = OnSurface+ ),+ modifier = Modifier.weight(1f)+ ) { Text(stringResource(R.string.action_cancel), maxLines = 1) }+ }++ LazyColumn(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ itemsIndexed(channels, key = { _, channel -> channel.id }) { index, channel ->+ var isFocused by remember { mutableStateOf(false) }+ val isDraggingThis = draggingChannel == channel++ TvClickableSurface(+ onClick = {+ draggingChannel = if (isDraggingThis) null else channel+ },+ modifier = Modifier+ .fillMaxWidth()+ .onFocusChanged { isFocused = it.isFocused }+ .onKeyEvent { event ->+ if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {+ if (isDraggingThis) {+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_UP -> {+ onMoveUp(channel)+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {+ onMoveDown(channel)+ true+ }+ else -> false+ }+ } else if (+ event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT ||+ event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT+ ) {+ true+ } else {+ false+ }+ } else false+ },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ focusedContainerColor = if (isDraggingThis) Primary else Primary.copy(alpha = 0.2f),+ containerColor = if (isDraggingThis) Primary.copy(alpha = 0.5f) else Color.Transparent+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(8.dp)+ )+ )+ ) {+ Row(+ modifier = Modifier+ .padding(12.dp)+ .fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically+ ) {+ if (isDraggingThis) {+ Text(+ stringResource(R.string.action_move),+ color = Color.White,+ modifier = Modifier.padding(end = 8.dp)+ )+ }+ Text(+ stringResource(R.string.channel_number_name_format, index + 1, channel.name),+ modifier = Modifier.weight(1f),+ style = MaterialTheme.typography.bodyMedium,+ color = if (isDraggingThis) Color.White else if (isFocused) OnBackground else OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+ }++ Text(+ if (draggingChannel != null) "UP/DOWN to move.\nOK to drop." else "OK to grab channel.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ modifier = Modifier+ .padding(top = 16.dp)+ .fillMaxWidth(),+ textAlign = TextAlign.Center+ )+ }+ }+}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 b613d514..cc97b392 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@@ -81,10 +81,13 @@ import com.streamvault.app.ui.components.shell.VodClassicContentHeaderimport com.streamvault.app.ui.components.shell.VodClassicSplitLayoutimport com.streamvault.app.ui.components.shell.VodHeroStripimport com.streamvault.app.ui.components.shell.VodSectionHeader+import com.streamvault.app.ui.design.FocusRestoreHost+import com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.ui.screens.vod.HandleVodUserMessageimport com.streamvault.app.ui.screens.vod.ProtectedVodPinDialogimport com.streamvault.app.ui.screens.vod.VodBrowseDefaults+import kotlinx.coroutines.delay@OptIn(ExperimentalFoundationApi::class)@Composable@@ -96,6 +99,7 @@ fun MoviesScreen() {val uiState by viewModel.uiState.collectAsStateWithLifecycle()val snackbarHostState = remember { SnackbarHostState() }+ val initialContentFocusRequester = remember { FocusRequester() }var showPinDialog by remember { mutableStateOf(false) }var pinError by remember { mutableStateOf<String?>(null) }var pendingMovie by remember { mutableStateOf<Movie?>(null) }@@ -135,6 +139,13 @@ fun MoviesScreen()Box(modifier = Modifier.fillMaxSize()) {+ FocusRestoreHost(+ enabled = !uiState.isLoading && uiState.errorMessage == null,+ onRestore = {+ delay(100)+ initialContentFocusRequester.requestFocusSafely(tag = "MoviesScreen", target = "Initial movies content")+ }+ ) {AppScreenScaffold(currentRoute = currentRoute,onNavigate = onNavigate,@@ -221,10 +232,12 @@ fun MoviesScreen(},onLoadMore = viewModel::loadMoreSelectedCategory,onLoadMorePreviewRows = viewModel::loadMorePreviewRows,- onDismissReorder = viewModel::exitCategoryReorderMode+ onDismissReorder = viewModel::exitCategoryReorderMode,+ initialFocusRequester = initialContentFocusRequester)}}+ }SnackbarHost(hostState = snackbarHostState,modifier = Modifier@@ -311,7 +324,8 @@ private fun MoviesVodContent(onOpenFresh: () -> Unit,onLoadMore: () -> Unit,onLoadMorePreviewRows: () -> Unit,- onDismissReorder: () -> Unit+ onDismissReorder: () -> Unit,+ initialFocusRequester: FocusRequester) {val screenWidth = LocalConfiguration.current.screenWidthDp.dpval isTelevisionDevice = rememberIsTelevisionDevice()@@ -376,6 +390,16 @@ private fun MoviesVodContent(category == null || !isCategoryHidden(category)}}+ val catEntries = uiState.moviesByCategory.entries+ .filter { (name, items) ->+ name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()+ }.toList()+ val fallbackMovieId = if (heroMovie == null) {+ favoriteMovies.firstOrNull()?.id+ ?: freshMovies.firstOrNull()?.id+ ?: topRatedMovies.firstOrNull()?.id+ ?: catEntries.firstOrNull()?.value?.firstOrNull()?.id+ } else nullval categoryOptions = remember(visibleCategoryNames, uiState.categoryCounts, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {visibleCategoryNames.map { name ->val matchedCategory = categoryByName[name]@@ -422,7 +446,8 @@ private fun MoviesVodContent(onOpenContinueWatching = onOpenContinueWatching,onOpenFresh = onOpenFresh,onLoadMore = onLoadMore,- onDismissReorder = onDismissReorder+ onDismissReorder = onDismissReorder,+ initialFocusRequester = initialFocusRequester)return}@@ -444,7 +469,9 @@ private fun MoviesVodContent(val isLocked = isMovieLocked(heroMovie)if (isLocked) onProtectedMovieClick(heroMovie) else onMovieClick(heroMovie)},- modifier = Modifier.padding(top = 8.dp, bottom = 6.dp)+ modifier = Modifier+ .padding(top = 8.dp, bottom = 6.dp)+ .focusRequester(initialFocusRequester))}}@@ -586,10 +613,6 @@ private fun MoviesVodContent(}}}- val catEntries = uiState.moviesByCategory.entries- .filter { (name, items) ->- name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()- }.toList()items(catEntries, key = { it.key }) { entry ->val categoryName = entry.keyval movies = entry.value@@ -609,6 +632,8 @@ private fun MoviesVodContent(isLocked = isLocked,onClick = { if (isLocked) onProtectedMovieClick(movie) else onMovieClick(movie) },onLongClick = { onShowDialog(movie) }+ ,+ modifier = if (movie.id == fallbackMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier)}}@@ -642,6 +667,7 @@ private fun MoviesVodContent(var draggingMovie by remember { mutableStateOf<Movie?>(null) }var showBrowseOptions by rememberSaveable(uiState.selectedCategory) { mutableStateOf(false) }var showSearchBar by rememberSaveable(uiState.selectedCategory) { mutableStateOf(searchQuery.isNotBlank()) }+ val initialGridMovieId = filteredGridMovies.firstOrNull()?.idif (showBrowseOptions) {VodBrowseOptionsDialog(@@ -743,6 +769,7 @@ private fun MoviesVodContent(onValueChange = onSearchQueryChange,placeholder = stringResource(R.string.movies_search_placeholder),onSearch = {},+ focusRequester = initialFocusRequester,modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp))}@@ -780,7 +807,8 @@ private fun MoviesVodContent(isDragging = isDraggingThis,modifier = Modifier.fillMaxWidth()- .aspectRatio(2f / 3f),+ .aspectRatio(2f / 3f)+ .then(if (!showSearchBar && movie.id == initialGridMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier),onClick = {if (uiState.isReorderMode) {draggingMovie = if (isDraggingThis) null else movie@@ -832,7 +860,8 @@ private fun MoviesVodClassicContent(onOpenContinueWatching: () -> Unit,onOpenFresh: () -> Unit,onLoadMore: () -> Unit,- onDismissReorder: () -> Unit+ onDismissReorder: () -> Unit,+ initialFocusRequester: FocusRequester) {val allLabel = stringResource(R.string.vod_classic_all)val continueLabel = stringResource(R.string.vod_classic_continue_watching)@@ -889,6 +918,7 @@ private fun MoviesVodClassicContent(if (uiState.isReorderMode) uiState.filteredMovies else baseMovies}var draggingMovie by remember { mutableStateOf<Movie?>(null) }+ val initialGridMovieId = filteredGridMovies.firstOrNull()?.idLaunchedEffect(uiState.vodViewMode, uiState.selectedCategory, uiState.isReorderMode) {if (uiState.vodViewMode == VodViewMode.CLASSIC && uiState.selectedCategory == null && !uiState.isReorderMode) {@@ -1048,6 +1078,7 @@ private fun MoviesVodClassicContent(onValueChange = onSearchQueryChange,placeholder = stringResource(R.string.movies_search_placeholder),onSearch = {},+ focusRequester = initialFocusRequester,modifier = Modifier.fillMaxWidth())}@@ -1099,7 +1130,8 @@ private fun MoviesVodClassicContent(isDragging = isDraggingThis,modifier = Modifier.fillMaxWidth()- .aspectRatio(2f / 3f),+ .aspectRatio(2f / 3f)+ .then(if (!showSearchBar && movie.id == initialGridMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier),onClick = {if (uiState.isReorderMode) {draggingMovie = if (isDraggingThis) null else moviediff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerOverlayActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerOverlayActions.ktnew file mode 100644index 00000000..0a52aaf0--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerOverlayActions.kt@@ -0,0 +1,161 @@+package com.streamvault.app.ui.screens.player++import androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.ContentType+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++fun PlayerViewModel.openChannelListOverlay() {+ clearNumericChannelInput()+ showChannelListOverlayFlow.value = true+ showCategoryListOverlayFlow.value = false+ showEpgOverlayFlow.value = false+ showChannelInfoOverlayFlow.value = false+ showControlsFlow.value = false+ scheduleLiveOverlayAutoHide()+}++fun PlayerViewModel.openCategoryListOverlay() {+ if (currentProviderId <= 0 || availableCategoriesFlow.value.isEmpty()) return+ showCategoryListOverlayFlow.value = true+ showChannelListOverlayFlow.value = false+ scheduleLiveOverlayAutoHide()+}++fun PlayerViewModel.selectCategoryFromOverlay(category: Category) {+ showCategoryListOverlayFlow.value = false+ currentCategoryId = category.id+ activeCategoryIdFlow.value = category.id+ isVirtualCategory = category.isVirtual+ loadPlaylist(+ categoryId = category.id,+ providerId = currentProviderId,+ isVirtual = category.isVirtual,+ initialChannelId = currentContentId+ )+ openChannelListOverlay()+}++fun PlayerViewModel.openEpgOverlay() {+ clearNumericChannelInput()+ showEpgOverlayFlow.value = true+ showChannelListOverlayFlow.value = false+ showChannelInfoOverlayFlow.value = false+ showControlsFlow.value = false+ scheduleLiveOverlayAutoHide()+}++fun PlayerViewModel.openChannelInfoOverlay() {+ clearNumericChannelInput()+ showChannelInfoOverlayFlow.value = true+ showChannelListOverlayFlow.value = false+ showEpgOverlayFlow.value = false+ showControlsFlow.value = false+ channelInfoHideJob?.cancel()+ scheduleLiveOverlayAutoHide()+}++fun PlayerViewModel.closeChannelInfoOverlay() {+ channelInfoHideJob?.cancel()+ showChannelInfoOverlayFlow.value = false+ if (!hasVisibleTransientLiveOverlay()) clearLiveOverlayAutoHide()+}++fun PlayerViewModel.closeOverlays() {+ clearNumericChannelInput()+ showChannelListOverlayFlow.value = false+ showCategoryListOverlayFlow.value = false+ showEpgOverlayFlow.value = false+ showChannelInfoOverlayFlow.value = false+ showDiagnosticsFlow.value = false+ channelInfoHideJob?.cancel()+ clearLiveOverlayAutoHide()+ clearDiagnosticsAutoHide()+}++fun PlayerViewModel.toggleDiagnostics() {+ showDiagnosticsFlow.value = !showDiagnosticsFlow.value+ if (showDiagnosticsFlow.value) {+ scheduleDiagnosticsAutoHide()+ } else {+ clearDiagnosticsAutoHide()+ }+}++fun PlayerViewModel.onLiveOverlayInteraction() {+ if (hasVisibleTransientLiveOverlay()) {+ scheduleLiveOverlayAutoHide()+ }+ if (showDiagnosticsFlow.value) {+ scheduleDiagnosticsAutoHide()+ }+}++fun PlayerViewModel.hideControlsAfterDelay() {+ controlsHideJob?.cancel()+ controlsHideJob = viewModelScope.launch {+ delay(playerControlsTimeoutMs)+ showControlsFlow.value = false+ }+}++fun PlayerViewModel.refreshControlsAutoHide() {+ if (showControlsFlow.value) {+ hideControlsAfterDelay()+ }+}++fun PlayerViewModel.cancelControlsAutoHide() {+ controlsHideJob?.cancel()+ controlsHideJob = null+}++internal fun PlayerViewModel.hideZapOverlayAfterDelay() {+ zapOverlayJob?.cancel()+ zapOverlayJob = viewModelScope.launch {+ delay(liveOverlayTimeoutMs)+ showZapOverlayFlow.value = false+ }+}++internal fun PlayerViewModel.hasVisibleTransientLiveOverlay(): Boolean =+ showChannelInfoOverlayFlow.value ||+ showChannelListOverlayFlow.value ||+ showEpgOverlayFlow.value++internal fun PlayerViewModel.clearLiveOverlayAutoHide() {+ liveOverlayHideJob?.cancel()+ liveOverlayHideJob = null+}++internal fun PlayerViewModel.clearDiagnosticsAutoHide() {+ diagnosticsHideJob?.cancel()+ diagnosticsHideJob = null+}++internal fun PlayerViewModel.scheduleLiveOverlayAutoHide() {+ if (currentContentType != ContentType.LIVE) {+ clearLiveOverlayAutoHide()+ return+ }+ liveOverlayHideJob?.cancel()+ liveOverlayHideJob = viewModelScope.launch {+ delay(liveOverlayTimeoutMs)+ showChannelInfoOverlayFlow.value = false+ showChannelListOverlayFlow.value = false+ showEpgOverlayFlow.value = false+ }+}++internal fun PlayerViewModel.scheduleDiagnosticsAutoHide() {+ if (currentContentType != ContentType.LIVE) {+ clearDiagnosticsAutoHide()+ return+ }+ diagnosticsHideJob?.cancel()+ diagnosticsHideJob = viewModelScope.launch {+ delay(diagnosticsTimeoutMs)+ showDiagnosticsFlow.value = false+ }+}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 6ecc6970..c375d6f9 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@@ -121,8 +121,7 @@ fun PlayerScreen(returnRoute: String? = null,onBack: () -> Unit,onNavigate: ((String) -> Unit)? = null,- viewModel: PlayerViewModel = hiltViewModel(),- multiViewViewModel: MultiViewViewModel = hiltViewModel()+ viewModel: PlayerViewModel = hiltViewModel()) {val screenWidth = LocalConfiguration.current.screenWidthDp.dpval isTelevisionDevice = rememberIsTelevisionDevice()@@ -159,7 +158,11 @@ fun PlayerScreen(val currentEpisode by viewModel.currentEpisode.collectAsStateWithLifecycle()val playbackTitle by viewModel.playbackTitle.collectAsStateWithLifecycle()val resumePrompt by viewModel.resumePrompt.collectAsStateWithLifecycle()- val canOpenEpisodePicker = contentType == "SERIES_EPISODE" && currentSeries?.seasons?.any { it.episodes.isNotEmpty() } == true+ val currentSeriesSeasons = remember(currentSeries) {+ currentSeries?.seasons.sanitizedForPlayer()+ }+ val canOpenEpisodePicker = contentType == "SERIES_EPISODE" &&+ currentSeriesSeasons?.any { it.episodes.isNotEmpty() } == trueval showChannelListOverlay by viewModel.showChannelListOverlay.collectAsStateWithLifecycle()val showCategoryListOverlay by viewModel.showCategoryListOverlay.collectAsStateWithLifecycle()@@ -332,6 +335,7 @@ fun PlayerScreen(// Split Screen Manager dialogif (showSplitDialog && currentChannel != null) {+ val multiViewViewModel: MultiViewViewModel = hiltViewModel()MultiViewPlannerDialog(pendingChannel = currentChannel,onDismiss = { showSplitDialog = false },@@ -915,7 +919,7 @@ fun PlayerScreen(PlayerEpisodeSelectionDialog(visible = showEpisodePicker,seriesTitle = currentSeries?.name ?: playbackTitle.ifBlank { title },- seasons = currentSeries?.seasons.orEmpty(),+ seasons = currentSeriesSeasons.orEmpty(),currentEpisodeId = currentEpisode?.id ?: internalChannelId,currentSeasonNumber = currentEpisode?.seasonNumber ?: seasonNumber,onDismiss = { showEpisodePicker = false },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 7d27d9c7..650f6a0e 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@@ -1,6 +1,5 @@package com.streamvault.app.ui.screens.player-import android.graphics.Bitmapimport android.os.SystemClockimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope@@ -49,73 +48,12 @@ import kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.*import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.coroutines.Dispatchersimport javax.inject.Injectimport java.util.Locale--data class ResumePromptState(- val show: Boolean = false,- val positionMs: Long = 0L,- val title: String = ""-)--data class NumericChannelInputState(- val input: String = "",- val matchedChannelName: String? = null,- val invalid: Boolean = false-)--data class PlayerNoticeState(- val message: String = "",- val recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,- val actions: List<PlayerNoticeAction> = emptyList(),- val isRetryNotice: Boolean = false-)--data class SeekPreviewState(- val visible: Boolean = false,- val positionMs: Long = 0L,- val frameBitmap: Bitmap? = null,- val artworkUrl: String? = null,- val title: String = "",- val isLoading: Boolean = false-)--data class PlayerDiagnosticsUiState(- val providerName: String = "",- val providerSourceLabel: String = "",- val decoderMode: DecoderMode = DecoderMode.AUTO,- val streamClassLabel: String = "Primary",- val playbackStateLabel: String = "Idle",- val alternativeStreamCount: Int = 0,- val channelErrorCount: Int = 0,- val archiveSupportLabel: String = "",- val lastFailureReason: String? = null,- val recentRecoveryActions: List<String> = emptyList(),- val troubleshootingHints: List<String> = emptyList()-)--enum class PlayerRecoveryType {- NETWORK,- SOURCE,- DECODER,- DRM,- CATCH_UP,- BUFFER_TIMEOUT,- UNKNOWN-}--enum class PlayerNoticeAction {- RETRY,- LAST_CHANNEL,- ALTERNATE_STREAM,- OPEN_GUIDE-}--enum class AspectRatio(val modeName: String) {- FIT("Fit"),- FILL("Stretch"),- ZOOM("Zoom")-}+import okhttp3.OkHttpClient+import okhttp3.Request@HiltViewModel@OptIn(ExperimentalCoroutinesApi::class)@@ -123,22 +61,23 @@ class PlayerViewModel @Inject constructor(@param:MainPlayerEngineval playerEngine: PlayerEngine,private val epgRepository: EpgRepository,- private val channelRepository: ChannelRepository,- private val movieRepository: MovieRepository,+ internal val channelRepository: ChannelRepository,+ internal val movieRepository: MovieRepository,private val seriesRepository: SeriesRepository,private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,- private val playbackHistoryRepository: PlaybackHistoryRepository,+ internal val playbackHistoryRepository: PlaybackHistoryRepository,private val providerRepository: com.streamvault.domain.repository.ProviderRepository,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,private val getCustomCategories: GetCustomCategories,private val markAsWatched: MarkAsWatched,- private val scheduleRecordingUseCase: ScheduleRecording,- private val recordingManager: RecordingManager,+ internal val scheduleRecordingUseCase: ScheduleRecording,+ internal val recordingManager: RecordingManager,private val watchNextManager: WatchNextManager,private val launcherRecommendationsManager: LauncherRecommendationsManager,- private val castManager: CastManager,+ internal val castManager: CastManager,private val xtreamStreamUrlResolver: XtreamStreamUrlResolver,- private val seekThumbnailProvider: SeekThumbnailProvider+ private val seekThumbnailProvider: SeekThumbnailProvider,+ private val okHttpClient: OkHttpClient) : ViewModel() {companion object {private const val MUTE_TOGGLE_DEBOUNCE_MS = 250L@@ -147,11 +86,11 @@ class PlayerViewModel @Inject constructor(private const val PLAYER_EPG_REFRESH_INTERVAL_MS = 30_000L}- private val _showControls = MutableStateFlow(false)- val showControls: StateFlow<Boolean> = _showControls.asStateFlow()+ internal val showControlsFlow = MutableStateFlow(false)+ val showControls: StateFlow<Boolean> = showControlsFlow.asStateFlow()- private val _showZapOverlay = MutableStateFlow(false)- val showZapOverlay: StateFlow<Boolean> = _showZapOverlay.asStateFlow()+ internal val showZapOverlayFlow = MutableStateFlow(false)+ val showZapOverlay: StateFlow<Boolean> = showZapOverlayFlow.asStateFlow()private val _currentProgram = MutableStateFlow<Program?>(null)val currentProgram: StateFlow<Program?> = _currentProgram.asStateFlow()@@ -165,8 +104,8 @@ class PlayerViewModel @Inject constructor(private val _upcomingPrograms = MutableStateFlow<List<Program>>(emptyList())val upcomingPrograms: StateFlow<List<Program>> = _upcomingPrograms.asStateFlow()- private val _currentChannel = MutableStateFlow<com.streamvault.domain.model.Channel?>(null)- val currentChannel: StateFlow<com.streamvault.domain.model.Channel?> = _currentChannel.asStateFlow()+ internal val currentChannelFlow = MutableStateFlow<com.streamvault.domain.model.Channel?>(null)+ val currentChannel: StateFlow<com.streamvault.domain.model.Channel?> = currentChannelFlow.asStateFlow()private val _currentSeries = MutableStateFlow<Series?>(null)val currentSeries: StateFlow<Series?> = _currentSeries.asStateFlow()@@ -177,8 +116,8 @@ class PlayerViewModel @Inject constructor(private val _nextEpisode = MutableStateFlow<Episode?>(null)val nextEpisode: StateFlow<Episode?> = _nextEpisode.asStateFlow()- private val _playbackTitle = MutableStateFlow("")- val playbackTitle: StateFlow<String> = _playbackTitle.asStateFlow()+ internal val playbackTitleFlow = MutableStateFlow("")+ val playbackTitle: StateFlow<String> = playbackTitleFlow.asStateFlow()private val _resumePrompt = MutableStateFlow(ResumePromptState())val resumePrompt: StateFlow<ResumePromptState> = _resumePrompt.asStateFlow()@@ -186,41 +125,41 @@ class PlayerViewModel @Inject constructor(private val _aspectRatio = MutableStateFlow(AspectRatio.FIT)val aspectRatio: StateFlow<AspectRatio> = _aspectRatio.asStateFlow()- private val _showChannelListOverlay = MutableStateFlow(false)- val showChannelListOverlay: StateFlow<Boolean> = _showChannelListOverlay.asStateFlow()+ internal val showChannelListOverlayFlow = MutableStateFlow(false)+ val showChannelListOverlay: StateFlow<Boolean> = showChannelListOverlayFlow.asStateFlow()- private val _showEpgOverlay = MutableStateFlow(false)- val showEpgOverlay: StateFlow<Boolean> = _showEpgOverlay.asStateFlow()+ internal val showEpgOverlayFlow = MutableStateFlow(false)+ val showEpgOverlay: StateFlow<Boolean> = showEpgOverlayFlow.asStateFlow()- private val _currentChannelList = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())- val currentChannelList: StateFlow<List<com.streamvault.domain.model.Channel>> = _currentChannelList.asStateFlow()+ private val currentChannelFlowList = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())+ val currentChannelList: StateFlow<List<com.streamvault.domain.model.Channel>> = currentChannelFlowList.asStateFlow()- private val _recentChannels = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())- val recentChannels: StateFlow<List<com.streamvault.domain.model.Channel>> = _recentChannels.asStateFlow()+ internal val recentChannelsFlow = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())+ val recentChannels: StateFlow<List<com.streamvault.domain.model.Channel>> = recentChannelsFlow.asStateFlow()private val _lastVisitedCategory = MutableStateFlow<Category?>(null)val lastVisitedCategory: StateFlow<Category?> = _lastVisitedCategory.asStateFlow()- private val _showCategoryListOverlay = MutableStateFlow(false)- val showCategoryListOverlay: StateFlow<Boolean> = _showCategoryListOverlay.asStateFlow()+ internal val showCategoryListOverlayFlow = MutableStateFlow(false)+ val showCategoryListOverlay: StateFlow<Boolean> = showCategoryListOverlayFlow.asStateFlow()- private val _availableCategories = MutableStateFlow<List<Category>>(emptyList())- val availableCategories: StateFlow<List<Category>> = _availableCategories.asStateFlow()+ internal val availableCategoriesFlow = MutableStateFlow<List<Category>>(emptyList())+ val availableCategories: StateFlow<List<Category>> = availableCategoriesFlow.asStateFlow()- private val _activeCategoryId = MutableStateFlow(-1L)- val activeCategoryId: StateFlow<Long> = _activeCategoryId.asStateFlow()+ internal val activeCategoryIdFlow = MutableStateFlow(-1L)+ val activeCategoryId: StateFlow<Long> = activeCategoryIdFlow.asStateFlow()- private val _displayChannelNumber = MutableStateFlow(0)- val displayChannelNumber: StateFlow<Int> = _displayChannelNumber.asStateFlow()+ internal val displayChannelNumberFlow = MutableStateFlow(0)+ val displayChannelNumber: StateFlow<Int> = displayChannelNumberFlow.asStateFlow()- private val _showChannelInfoOverlay = MutableStateFlow(false)- val showChannelInfoOverlay: StateFlow<Boolean> = _showChannelInfoOverlay.asStateFlow()+ internal val showChannelInfoOverlayFlow = MutableStateFlow(false)+ val showChannelInfoOverlay: StateFlow<Boolean> = showChannelInfoOverlayFlow.asStateFlow()- private val _numericChannelInput = MutableStateFlow<NumericChannelInputState?>(null)- val numericChannelInput: StateFlow<NumericChannelInputState?> = _numericChannelInput.asStateFlow()+ internal val numericChannelInputFlow = MutableStateFlow<NumericChannelInputState?>(null)+ val numericChannelInput: StateFlow<NumericChannelInputState?> = numericChannelInputFlow.asStateFlow()- private val _showDiagnostics = MutableStateFlow(false)- val showDiagnostics: StateFlow<Boolean> = _showDiagnostics.asStateFlow()+ internal val showDiagnosticsFlow = MutableStateFlow(false)+ val showDiagnostics: StateFlow<Boolean> = showDiagnosticsFlow.asStateFlow()private val _playerNotice = MutableStateFlow<PlayerNoticeState?>(null)val playerNotice: StateFlow<PlayerNoticeState?> = _playerNotice.asStateFlow()@@ -230,45 +169,68 @@ class PlayerViewModel @Inject constructor(val seekPreview: StateFlow<SeekPreviewState> = _seekPreview.asStateFlow()private val _recordingItems = MutableStateFlow<List<RecordingItem>>(emptyList())val recordingItems: StateFlow<List<RecordingItem>> = _recordingItems.asStateFlow()- private val _currentChannelRecording = MutableStateFlow<RecordingItem?>(null)- val currentChannelRecording: StateFlow<RecordingItem?> = _currentChannelRecording.asStateFlow()-- private var channelInfoHideJob: Job? = null- private var liveOverlayHideJob: Job? = null- private var diagnosticsHideJob: Job? = null- private var numericInputCommitJob: Job? = null- private var numericInputFeedbackJob: Job? = null+ private val currentChannelFlowRecording = MutableStateFlow<RecordingItem?>(null)+ val currentChannelRecording: StateFlow<RecordingItem?> = currentChannelFlowRecording.asStateFlow()++ internal var channelInfoHideJob: Job? = null+ internal var liveOverlayHideJob: Job? = null+ internal var diagnosticsHideJob: Job? = null+ internal var numericInputCommitJob: Job? = null+ internal var numericInputFeedbackJob: Job? = nullprivate var playerNoticeHideJob: Job? = nullprivate var mutePersistJob: Job? = nullprivate var recoveryJob: Job? = null- private var numericInputBuffer: String = ""- private val triedAlternativeStreams = mutableSetOf<String>()+ internal var numericInputBuffer: String = ""+ internal val triedAlternativeStreams = mutableSetOf<String>()private val failedStreamsThisSession = mutableMapOf<String, Int>()private var hasRetriedWithSoftwareDecoder = false- private var lastRecordedLivePlaybackKey: Pair<Long, Long>? = null+ internal var lastRecordedLivePlaybackKey: Pair<Long, Long>? = nullprivate var currentStreamClassLabel: String = "Primary"private var prepareRequestVersion: Long = 0L- private var currentArtworkUrl: String? = null+ internal var currentArtworkUrl: String? = nullprivate var currentResolvedPlaybackUrl: String = ""- private var pendingCatchUpUrls: List<String> = emptyList()- private var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP+ internal var pendingCatchUpUrls: List<String> = emptyList()+ internal var channelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUPprivate var activeEpgRequestKey: EpgRequestKey? = null- private var playerControlsTimeoutMs: Long = 5_000L- private var liveOverlayTimeoutMs: Long = 4_000L+ internal var playerControlsTimeoutMs: Long = 5_000L+ internal var liveOverlayTimeoutMs: Long = 4_000Lprivate var playerNoticeTimeoutMs: Long = 6_000L- private var diagnosticsTimeoutMs: Long = 15_000L+ internal var diagnosticsTimeoutMs: Long = 15_000Lprivate var preferredDecoderMode: DecoderMode = DecoderMode.AUTO- private data class EpgRequestKey(- val providerId: Long,- val internalChannelId: Long,- val epgChannelId: String?,- val streamId: Long- )+ // Zapping state+ internal var channelList: List<com.streamvault.domain.model.Channel> = emptyList()+ internal var currentChannelIndex = -1+ internal var previousChannelIndex = -1+ internal var currentCategoryId: Long = -1+ internal var currentProviderId: Long = -1L+ internal var currentContentId: Long = -1L+ internal var currentContentType: ContentType = ContentType.LIVE+ internal var currentTitle: String = ""+ private var currentSeriesId: Long? = null+ private var currentSeasonNumber: Int? = null+ private var currentEpisodeNumber: Int? = null+ internal var isVirtualCategory: Boolean = false+ private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLE++ private var epgJob: Job? = null+ private var playlistJob: Job? = null+ private var recentChannelsJob: Job? = null+ private var lastVisitedCategoryJob: Job? = null+ internal var controlsHideJob: Job? = null+ private var seekPreviewJob: Job? = null+ private var progressTrackingJob: Job? = null+ internal var zapOverlayJob: Job? = null+ private var aspectRatioJob: Job? = null+ internal var zapBufferWatchdogJob: Job? = null+ private var isAppInForeground: Boolean = true+ private var shouldResumeAfterForeground: Boolean = false+ private var seekPreviewRequestVersion: Long = 0L+ private var lastMuteToggleAtMs: Long = 0Lval castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState- private fun logRepositoryFailure(operation: String, result: com.streamvault.domain.model.Result<Unit>) {+ internal fun logRepositoryFailure(operation: String, result: com.streamvault.domain.model.Result<Unit>) {if (result is com.streamvault.domain.model.Result.Error) {android.util.Log.w("PlayerVM", "$operation failed: ${result.message}", result.exception)}@@ -293,7 +255,7 @@ class PlayerViewModel @Inject constructor(zapBufferWatchdogJob?.cancel()dismissRecoveredNoticeIfPresent()if (currentContentType == ContentType.LIVE) {- _currentChannel.value?.let { channel ->+ currentChannelFlow.value?.sanitizedForPlayer()?.let { channel ->if (channel.errorCount > 0) {logRepositoryFailure(operation = "Reset channel error count",@@ -364,13 +326,6 @@ class PlayerViewModel @Inject constructor(}}- private data class PlayerUiTimeouts(- val controlsMs: Long,- val liveOverlayMs: Long,- val noticeMs: Long,- val diagnosticsMs: Long- )-private fun handlePlaybackError(error: PlayerError) {val requestVersion = prepareRequestVersionval playbackUrl = currentPlaybackIdentityUrl()@@ -392,7 +347,7 @@ class PlayerViewModel @Inject constructor(return}val recoveryType = classifyPlaybackError(error)- val channel = _currentChannel.value+ val channel = currentChannelFlow.value?.sanitizedForPlayer()if (currentContentType != ContentType.LIVE || channel == null) {if (!isActivePlaybackSession(requestVersion, playbackUrl)) return@@ -484,147 +439,51 @@ class PlayerViewModel @Inject constructor(}}- fun openChannelListOverlay() {- clearNumericChannelInput()- _showChannelListOverlay.value = true- _showCategoryListOverlay.value = false- _showEpgOverlay.value = false- _showChannelInfoOverlay.value = false- _showControls.value = false- scheduleLiveOverlayAutoHide()- }-- fun openCategoryListOverlay() {- if (currentProviderId <= 0 || _availableCategories.value.isEmpty()) return- _showCategoryListOverlay.value = true- _showChannelListOverlay.value = false- scheduleLiveOverlayAutoHide()- }-- fun selectCategoryFromOverlay(category: Category) {- _showCategoryListOverlay.value = false- currentCategoryId = category.id- _activeCategoryId.value = category.id- isVirtualCategory = category.isVirtual- loadPlaylist(- categoryId = category.id,- providerId = currentProviderId,- isVirtual = category.isVirtual,- initialChannelId = currentContentId- )- openChannelListOverlay()- }-- fun openEpgOverlay() {- clearNumericChannelInput()- _showEpgOverlay.value = true- _showChannelListOverlay.value = false- _showChannelInfoOverlay.value = false- _showControls.value = false- scheduleLiveOverlayAutoHide()- }-- fun openChannelInfoOverlay() {- clearNumericChannelInput()- _showChannelInfoOverlay.value = true- _showChannelListOverlay.value = false- _showEpgOverlay.value = false- _showControls.value = false- channelInfoHideJob?.cancel()- scheduleLiveOverlayAutoHide()- }-- fun closeChannelInfoOverlay() {- channelInfoHideJob?.cancel()- _showChannelInfoOverlay.value = false- if (!hasVisibleTransientLiveOverlay()) clearLiveOverlayAutoHide()- }-- fun closeOverlays() {- clearNumericChannelInput()- _showChannelListOverlay.value = false- _showCategoryListOverlay.value = false- _showEpgOverlay.value = false- _showChannelInfoOverlay.value = false- _showDiagnostics.value = false- channelInfoHideJob?.cancel()- clearLiveOverlayAutoHide()- clearDiagnosticsAutoHide()- }-- private fun refreshCurrentChannelRecording(items: List<RecordingItem> = _recordingItems.value) {- val channelId = _currentChannel.value?.id ?: -1L- _currentChannelRecording.value = items.firstOrNull {+ internal fun refreshCurrentChannelRecording(items: List<RecordingItem> = _recordingItems.value) {+ val channelId = currentChannelFlow.value?.id ?: -1L+ currentChannelFlowRecording.value = items.firstOrNull {it.providerId == currentProviderId &&it.channelId == channelId &&(it.status == RecordingStatus.RECORDING || it.status == RecordingStatus.SCHEDULED)}}- fun toggleDiagnostics() {- _showDiagnostics.value = !_showDiagnostics.value- if (_showDiagnostics.value) {- scheduleDiagnosticsAutoHide()- } else {- clearDiagnosticsAutoHide()- }- }-- fun onLiveOverlayInteraction() {- if (hasVisibleTransientLiveOverlay()) {- scheduleLiveOverlayAutoHide()- }- if (_showDiagnostics.value) {- scheduleDiagnosticsAutoHide()- }- }-- // Zapping state- private var channelList: List<com.streamvault.domain.model.Channel> = emptyList()- private var currentChannelIndex = -1- private var previousChannelIndex = -1- private var currentCategoryId: Long = -1- private var currentProviderId: Long = -1L- private var currentContentId: Long = -1L- private var currentContentType: ContentType = ContentType.LIVE- private var currentTitle: String = ""- private var currentSeriesId: Long? = null- private var currentSeasonNumber: Int? = null- private var currentEpisodeNumber: Int? = null- private var isVirtualCategory: Boolean = false- private var lastObservedPlaybackState: PlaybackState = PlaybackState.IDLE-- private var epgJob: Job? = null- private var playlistJob: Job? = null- private var recentChannelsJob: Job? = null- private var lastVisitedCategoryJob: Job? = null- private var controlsHideJob: Job? = null- private var seekPreviewJob: Job? = null- private var progressTrackingJob: Job? = null- private var zapOverlayJob: Job? = null- private var aspectRatioJob: Job? = null- private var zapBufferWatchdogJob: Job? = null- private var isAppInForeground: Boolean = true- private var shouldResumeAfterForeground: Boolean = false- private var seekPreviewRequestVersion: Long = 0L- private var lastMuteToggleAtMs: Long = 0L+ private data class PlaybackProbeFailure(+ val message: String,+ val recoveryType: PlayerRecoveryType+ )- val playerError: StateFlow<PlayerError?> = playerEngine.error- .stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)+ val playerError: StateFlow<PlayerError?> by lazy(LazyThreadSafetyMode.NONE) {+ playerEngine.error+ .stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)+ }val videoFormat: StateFlow<VideoFormat> = playerEngine.videoFormatval playerStats = playerEngine.playerStats- val availableAudioTracks = playerEngine.availableAudioTracks- val availableSubtitleTracks = playerEngine.availableSubtitleTracks- val availableVideoQualities = playerEngine.availableVideoTracks+ val availableAudioTracks: StateFlow<List<com.streamvault.player.PlayerTrack>> by lazy(LazyThreadSafetyMode.NONE) {+ playerEngine.availableAudioTracks+ .map { tracks -> tracks as? List<com.streamvault.player.PlayerTrack> ?: emptyList() }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())+ }+ val availableSubtitleTracks: StateFlow<List<com.streamvault.player.PlayerTrack>> by lazy(LazyThreadSafetyMode.NONE) {+ playerEngine.availableSubtitleTracks+ .map { tracks -> tracks as? List<com.streamvault.player.PlayerTrack> ?: emptyList() }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())+ }+ val availableVideoQualities: StateFlow<List<com.streamvault.player.PlayerTrack>> by lazy(LazyThreadSafetyMode.NONE) {+ playerEngine.availableVideoTracks+ .map { tracks -> tracks as? List<com.streamvault.player.PlayerTrack> ?: emptyList() }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())+ }val isMuted: StateFlow<Boolean> = playerEngine.isMutedval mediaTitle: StateFlow<String?> = playerEngine.mediaTitleval playbackSpeed: StateFlow<Float> = playerEngine.playbackSpeed- val preventStandbyDuringPlayback: StateFlow<Boolean> =+ val preventStandbyDuringPlayback: StateFlow<Boolean> by lazy(LazyThreadSafetyMode.NONE) {preferencesRepository.preventStandbyDuringPlayback.stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), true)+ }fun selectAudioTrack(trackId: String) {playerEngine.selectAudioTrack(trackId)@@ -705,7 +564,7 @@ class PlayerViewModel @Inject constructor(}}- private fun beginPlaybackSession(): Long {+ internal fun beginPlaybackSession(): Long {recoveryJob?.cancel()return ++prepareRequestVersion}@@ -726,6 +585,7 @@ class PlayerViewModel @Inject constructor(episodeNumber: Int?): Episode? {val episodes = series.seasons+ .sanitizedForPlayer().sortedBy { it.seasonNumber }.flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }return episodes.firstOrNull { it.id == episodeId }@@ -734,6 +594,7 @@ class PlayerViewModel @Inject constructor(private fun findNextEpisode(series: Series, episode: Episode): Episode? {val orderedEpisodes = series.seasons+ .sanitizedForPlayer().sortedBy { it.seasonNumber }.flatMap { season -> season.episodes.sortedBy { it.episodeNumber } }val currentIndex = orderedEpisodes.indexOfFirst { it.id == episode.id }@@ -755,7 +616,7 @@ class PlayerViewModel @Inject constructor(when (val result = seriesRepository.getSeriesDetails(providerId, seriesId)) {is Result.Success -> {if (!isActivePlaybackSession(requestVersion)) return@launch- val series = result.data+ val series = result.data.sanitizedForPlayer()val resolvedEpisode = resolveEpisode(series, episodeId, seasonNumber, episodeNumber)_currentSeries.value = series_currentEpisode.value = resolvedEpisode@@ -769,7 +630,7 @@ class PlayerViewModel @Inject constructor(?: series.posterUrl?: series.backdropUrlcurrentTitle = buildEpisodePlaybackTitle(resolvedEpisode)- _playbackTitle.value = currentTitle+ playbackTitleFlow.value = currentTitle}}@@ -838,7 +699,7 @@ class PlayerViewModel @Inject constructor(private fun currentPlaybackIdentityUrl(): String =currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }- private fun isActivePlaybackSession(+ internal fun isActivePlaybackSession(requestVersion: Long,expectedLogicalUrl: String? = null): Boolean {@@ -848,7 +709,7 @@ class PlayerViewModel @Inject constructor(return activeUrl.isBlank() || activeUrl == expectedUrl || currentStreamUrl == expectedUrl}- private fun requestEpg(+ internal fun requestEpg(providerId: Long,epgChannelId: String?,streamId: Long = 0L,@@ -877,11 +738,21 @@ class PlayerViewModel @Inject constructor()}- private suspend fun preparePlayer(+ internal suspend fun preparePlayer(streamInfo: com.streamvault.domain.model.StreamInfo,requestVersion: Long): Boolean {if (!isActivePlaybackSession(requestVersion)) return false+ probePlaybackUrl(streamInfo.url)?.let { failure ->+ if (!isActivePlaybackSession(requestVersion)) return false+ setLastFailureReason(failure.message)+ showPlayerNotice(+ message = failure.message,+ recoveryType = failure.recoveryType,+ actions = buildRecoveryActions(failure.recoveryType)+ )+ return false+ }playerEngine.setMuted(preferencesRepository.playerMuted.first())playerEngine.setPlaybackSpeed(if (currentContentType == ContentType.LIVE) {@@ -906,6 +777,45 @@ class PlayerViewModel @Inject constructor(return true}+ private suspend fun probePlaybackUrl(url: String): PlaybackProbeFailure? {+ if (!shouldProbePlaybackUrl(url)) return null++ return runCatching {+ withContext(Dispatchers.IO) {+ val request = Request.Builder()+ .url(url)+ .get()+ .header("Range", "bytes=0-0")+ .build()+ okHttpClient.newCall(request).execute().use { response ->+ when (response.code) {+ 401, 403 -> PlaybackProbeFailure(+ message = "This Xtream stream was rejected by the provider (${response.code} Unauthorized/Forbidden).",+ recoveryType = PlayerRecoveryType.SOURCE+ )+ 404 -> PlaybackProbeFailure(+ message = "This Xtream stream is unavailable on the provider right now (404).",+ recoveryType = PlayerRecoveryType.SOURCE+ )+ in 500..599 -> PlaybackProbeFailure(+ message = "The provider returned a server error for this stream (${response.code}).",+ recoveryType = PlayerRecoveryType.NETWORK+ )+ else -> null+ }+ }+ }+ }.getOrNull()+ }++ private suspend fun shouldProbePlaybackUrl(url: String): Boolean {+ if (!url.startsWith("http://") && !url.startsWith("https://")) return false+ val providerId = currentProviderId.takeIf { it > 0L } ?: return false+ val provider = providerRepository.getProvider(providerId) ?: return false+ return provider.type == com.streamvault.domain.model.ProviderType.XTREAM_CODES &&+ (xtreamStreamUrlResolver.isInternalStreamUrl(currentStreamUrl) || xtreamStreamUrlResolver.isInternalStreamUrl(url))+ }+fun prepare(streamUrl: String,epgChannelId: String?,@@ -939,7 +849,7 @@ class PlayerViewModel @Inject constructor(currentStreamUrl = streamUrlcurrentContentId = internalChannelIdcurrentTitle = title- _playbackTitle.value = title+ playbackTitleFlow.value = titlecurrentArtworkUrl = artworkUrlcurrentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }currentProviderId = providerId@@ -965,7 +875,7 @@ class PlayerViewModel @Inject constructor(if (currentContentType != ContentType.LIVE) {lastRecordedLivePlaybackKey = nullrecentChannelsJob?.cancel()- _recentChannels.value = emptyList()+ recentChannelsFlow.value = emptyList()lastVisitedCategoryJob?.cancel()_lastVisitedCategory.value = null}@@ -1033,7 +943,7 @@ class PlayerViewModel @Inject constructor(// Load playlist if context changedif (shouldReloadPlaylist) {currentCategoryId = categoryId- _activeCategoryId.value = categoryId+ activeCategoryIdFlow.value = categoryIdisVirtualCategory = isVirtualloadPlaylist(categoryId, providerId, isVirtual, internalChannelId)} else {@@ -1073,7 +983,7 @@ class PlayerViewModel @Inject constructor(requestVersionOverride = requestVersion)} else {- val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = true)+ val reason = resolveCatchUpFailureMessage(currentChannelFlow.value, archiveRequested = true, programHasArchive = true)setLastFailureReason(reason)showPlayerNotice(message = reason,@@ -1115,11 +1025,11 @@ class PlayerViewModel @Inject constructor(viewModelScope.launch {val channel = channelRepository.getChannel(internalChannelId)if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch- _currentChannel.value = channel+ currentChannelFlow.value = channelrefreshCurrentChannelRecording()if (channel != null) {currentTitle = channel.name.ifBlank { currentTitle }- _playbackTitle.value = currentTitle+ playbackTitleFlow.value = currentTitlecurrentStreamUrl = if (currentStreamClassLabel == "Catch-up") currentStreamUrl else channel.streamUrlupdateStreamClass(when {@@ -1209,49 +1119,6 @@ class PlayerViewModel @Inject constructor(playerEngine.release()}- fun castCurrentMedia(onRouteSelectionRequired: () -> Unit) {- viewModelScope.launch {- val request = buildCastRequest()- if (request == null) {- showPlayerNotice(- message = "This item cannot be sent to a Cast receiver.",- recoveryType = PlayerRecoveryType.SOURCE- )- return@launch- }-- when (castManager.startCasting(request)) {- CastStartResult.STARTED -> {- playerEngine.pause()- showPlayerNotice(- message = "Casting to the connected device.",- recoveryType = PlayerRecoveryType.NETWORK- )- }-- CastStartResult.ROUTE_SELECTION_REQUIRED -> onRouteSelectionRequired()-- CastStartResult.UNAVAILABLE -> showPlayerNotice(- message = "Google Cast is unavailable on this device.",- recoveryType = PlayerRecoveryType.SOURCE- )-- CastStartResult.UNSUPPORTED -> showPlayerNotice(- message = "This stream format is not supported by Google Cast.",- recoveryType = PlayerRecoveryType.SOURCE- )- }- }- }-- fun stopCasting() {- castManager.stopCasting()- showPlayerNotice(- message = "Cast session disconnected.",- recoveryType = PlayerRecoveryType.NETWORK- )- }-private fun fetchEpg(providerId: Long,internalChannelId: Long,@@ -1290,7 +1157,7 @@ class PlayerViewModel @Inject constructor(}private fun applyProgramTimeline(programs: List<Program>, now: Long) {- val catchUpSupported = _currentChannel.value?.catchUpSupported == true+ val catchUpSupported = currentChannelFlow.value?.catchUpSupported == trueval sortedPrograms = programs.sortedBy { it.startTime }val current = sortedPrograms.firstOrNull { it.startTime <= now && it.endTime > now }_currentProgram.value = current@@ -1341,7 +1208,7 @@ class PlayerViewModel @Inject constructor(_upcomingPrograms.value = emptyList()}- private fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {+ internal fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {playlistJob?.cancel()playlistJob = viewModelScope.launch {val flows = if (isVirtual) {@@ -1396,11 +1263,11 @@ class PlayerViewModel @Inject constructor(}ChannelNumberingMode.PROVIDER -> channels}- numberingMode to displayedChannels+ numberingMode to displayedChannels.sanitizedChannelsForPlayer()}.collect { (numberingMode, displayedChannels) ->channelNumberingMode = numberingModechannelList = displayedChannels- _currentChannelList.value = displayedChannels+ currentChannelFlowList.value = displayedChannels// Recalculate index based on initial ID or URLif (initialChannelId != -1L) {currentChannelIndex = channelList.indexOfFirst { it.id == initialChannelId }@@ -1410,22 +1277,22 @@ class PlayerViewModel @Inject constructor(}if (currentChannelIndex != -1) {- _currentChannel.value = channelList[currentChannelIndex]+ currentChannelFlow.value = channelList[currentChannelIndex].sanitizedForPlayer()refreshCurrentChannelRecording()val ch = channelList[currentChannelIndex]- _displayChannelNumber.value = resolveChannelNumber(ch, currentChannelIndex)+ displayChannelNumberFlow.value = resolveChannelNumber(ch, currentChannelIndex)}}}}// Store current URL to find index later- private var currentStreamUrl: String = ""+ internal var currentStreamUrl: String = ""private fun observeRecentChannels() {recentChannelsJob?.cancel()if (currentContentType != ContentType.LIVE || currentProviderId <= 0) {- _recentChannels.value = emptyList()+ recentChannelsFlow.value = emptyList()return}@@ -1455,7 +1322,7 @@ class PlayerViewModel @Inject constructor(val currentListNumbers = channelList.withIndex().associate { (index, channel) ->channel.id to resolveChannelNumber(channel, index)}- _recentChannels.value = channels+ recentChannelsFlow.value = channels.filterNot { it.id == currentContentId }.map { channel ->currentListNumbers[channel.id]?.let { number ->@@ -1487,7 +1354,7 @@ class PlayerViewModel @Inject constructor(}Pair(allCategories, lastVisited)}.collect { (allCategories, lastVisited) ->- _availableCategories.value = allCategories+ availableCategoriesFlow.value = allCategories_lastVisitedCategory.value = lastVisited}}@@ -1498,7 +1365,7 @@ class PlayerViewModel @Inject constructor(if (currentContentType != ContentType.LIVE || currentProviderId <= 0) returncurrentCategoryId = category.id- _activeCategoryId.value = category.id+ activeCategoryIdFlow.value = category.idisVirtualCategory = category.isVirtualloadPlaylist(categoryId = category.id,@@ -1532,230 +1399,13 @@ class PlayerViewModel @Inject constructor(return currentChannelIndex}- private fun wrappedChannelIndex(offset: Int): Int {+ internal fun wrappedChannelIndex(offset: Int): Int {val resolvedIndex = resolveCurrentLiveChannelIndex()if (resolvedIndex == -1) return -1val size = channelList.sizereturn ((resolvedIndex + offset) % size + size) % size}- fun playNext() {- clearNumericChannelInput()- if (channelList.isEmpty()) return-- val nextIndex = wrappedChannelIndex(offset = 1)- if (nextIndex == -1) return- changeChannel(nextIndex)- }-- fun playPrevious() {- clearNumericChannelInput()- if (channelList.isEmpty()) return-- val prevIndex = wrappedChannelIndex(offset = -1)- if (prevIndex == -1) return- changeChannel(prevIndex)- }-- fun zapToChannel(channelId: Long) {- clearNumericChannelInput()- if (channelList.isEmpty()) return- val index = channelList.indexOfFirst { it.id == channelId }- if (index != -1) {- changeChannel(index)- closeOverlays()- }- }-- fun zapToLastChannel() {- clearNumericChannelInput()- if (channelList.isEmpty() || previousChannelIndex == -1) return- changeChannel(previousChannelIndex)- }-- fun hasLastChannel(): Boolean =- currentContentType == ContentType.LIVE &&- previousChannelIndex in channelList.indices &&- previousChannelIndex != currentChannelIndex-- fun hasPendingNumericChannelInput(): Boolean = numericInputBuffer.isNotBlank()-- fun inputNumericChannelDigit(digit: Int) {- if (currentContentType != ContentType.LIVE || channelList.isEmpty() || digit !in 0..9) return-- if (numericInputBuffer.isEmpty() && digit == 0) {- zapToLastChannel()- return- }-- numericInputBuffer = if (numericInputBuffer.length >= 4) {- digit.toString()- } else {- numericInputBuffer + digit.toString()- }-- val exactMatch = resolveChannelByNumber(numericInputBuffer.toIntOrNull())- val previewMatch = exactMatch ?: resolveChannelByPrefix(numericInputBuffer)-- _numericChannelInput.value = NumericChannelInputState(- input = numericInputBuffer,- matchedChannelName = previewMatch?.name,- invalid = false- )-- scheduleNumericChannelCommit()- }-- fun commitNumericChannelInput() {- numericInputCommitJob?.cancel()- if (numericInputBuffer.isBlank()) return-- val targetChannel = resolveChannelByNumber(numericInputBuffer.toIntOrNull())- if (targetChannel != null) {- val targetIndex = channelList.indexOfFirst { it.id == targetChannel.id }- if (targetIndex != -1) {- changeChannel(targetIndex)- }- clearNumericChannelInput()- return- }-- _numericChannelInput.value = NumericChannelInputState(- input = numericInputBuffer,- matchedChannelName = null,- invalid = true- )-- numericInputFeedbackJob?.cancel()- numericInputFeedbackJob = viewModelScope.launch {- delay(900)- clearNumericChannelInput()- }- }-- fun clearNumericChannelInput() {- numericInputCommitJob?.cancel()- numericInputFeedbackJob?.cancel()- numericInputBuffer = ""- _numericChannelInput.value = null- }-- private fun changeChannel(index: Int) {- clearNumericChannelInput()- if (currentChannelIndex != -1 && currentChannelIndex != index) {- previousChannelIndex = currentChannelIndex- }- val requestVersion = beginPlaybackSession()- val channel = channelList[index]- currentChannelIndex = index- currentContentId = channel.id- currentTitle = channel.name- _playbackTitle.value = currentTitle- currentStreamUrl = channel.streamUrl- pendingCatchUpUrls = emptyList()- updateStreamClass("Primary")- _currentChannel.value = channel- refreshCurrentChannelRecording()- _displayChannelNumber.value = resolveChannelNumber(channel, index)- _recentChannels.update { channels -> channels.filterNot { it.id == channel.id } }-- // Enable scrubbing mode for fast channel start — key-frame-only decoding- playerEngine.setScrubbingMode(true)-- viewModelScope.launch {- val resolvedUrl = resolvePlaybackUrl(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)- ?: return@launch- if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch- val streamInfo = com.streamvault.domain.model.StreamInfo(- url = resolvedUrl,- title = currentTitle,- streamType = com.streamvault.domain.model.StreamType.UNKNOWN- )- if (!preparePlayer(streamInfo, requestVersion)) return@launch- playerEngine.play()-- // Once the first frame is on screen, turn off scrubbing for full quality- playerEngine.playbackState- .filter { it == com.streamvault.player.PlaybackState.READY }- .take(1)- .collect {- if (isActivePlaybackSession(requestVersion, channel.streamUrl)) {- playerEngine.setScrubbingMode(false)- }- }- }-- // Pre-warm the next channel in sequence so the subsequent zap is near-instant- preloadAdjacentChannel(index)-- requestEpg(- providerId = currentProviderId,- epgChannelId = channel.epgChannelId,- streamId = channel.streamId,- internalChannelId = channel.id- )-- // Show bottom live info overlay- _showZapOverlay.value = false- _showControls.value = false- openChannelInfoOverlay()-- // Reset tried streams for manual switch- triedAlternativeStreams.clear()- triedAlternativeStreams.add(channel.streamUrl)- if (currentContentType == ContentType.LIVE) {- recordLivePlayback(channel)- scheduleZapBufferWatchdog(index)- }- }-- /**- * Pre-warm the next channel's media source so switching is near-instant.- * Only the manifest/first segment is parsed — no full buffering.- */- private fun preloadAdjacentChannel(currentIndex: Int) {- if (channelList.size < 2) return- val nextIndex = (currentIndex + 1) % channelList.size- val nextChannel = channelList[nextIndex]- viewModelScope.launch {- val nextUrl = resolvePlaybackUrl(- nextChannel.streamUrl, nextChannel.id,- nextChannel.providerId, ContentType.LIVE- ) ?: return@launch- playerEngine.preload(- com.streamvault.domain.model.StreamInfo(- url = nextUrl,- title = nextChannel.name,- streamType = com.streamvault.domain.model.StreamType.UNKNOWN- )- )- }- }-- private fun recordLivePlayback(channel: com.streamvault.domain.model.Channel) {- if (currentProviderId <= 0 || currentContentType != ContentType.LIVE) return-- val playbackKey = currentProviderId to channel.id- if (lastRecordedLivePlaybackKey == playbackKey) return- lastRecordedLivePlaybackKey = playbackKey-- viewModelScope.launch {- logRepositoryFailure(- operation = "Record live playback",- result = playbackHistoryRepository.recordPlayback(- PlaybackHistory(- contentId = channel.id,- contentType = ContentType.LIVE,- providerId = currentProviderId,- title = channel.name,- streamUrl = channel.streamUrl,- lastWatchedAt = System.currentTimeMillis()- )- )- )- }- }-private fun classifyPlaybackError(error: PlayerError): PlayerRecoveryType = when (error) {is PlayerError.NetworkError -> {if (error.message.contains("timeout", ignoreCase = true)) {@@ -1786,17 +1436,18 @@ class PlayerViewModel @Inject constructor(PlayerRecoveryType.UNKNOWN -> error.message.ifBlank { "Playback failed for an unknown reason." }}- private fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> = buildList {- add(PlayerNoticeAction.RETRY)+ private fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> {+ val actions = mutableListOf(PlayerNoticeAction.RETRY)if (hasAlternateStream()) {- add(PlayerNoticeAction.ALTERNATE_STREAM)+ actions += PlayerNoticeAction.ALTERNATE_STREAM}if (hasLastChannel()) {- add(PlayerNoticeAction.LAST_CHANNEL)+ actions += PlayerNoticeAction.LAST_CHANNEL}if (recoveryType == PlayerRecoveryType.CATCH_UP && currentContentType == ContentType.LIVE) {- add(PlayerNoticeAction.OPEN_GUIDE)+ actions += PlayerNoticeAction.OPEN_GUIDE}+ return actions}private fun markStreamFailure(streamUrl: String) {@@ -1808,7 +1459,7 @@ class PlayerViewModel @Inject constructor(_playerDiagnostics.update { it.copy(decoderMode = mode) }}- private fun updateStreamClass(label: String) {+ internal fun updateStreamClass(label: String) {currentStreamClassLabel = label_playerDiagnostics.update { it.copy(streamClassLabel = label) }}@@ -1861,7 +1512,8 @@ class PlayerViewModel @Inject constructor((failedStreamsThisSession[altUrl] ?: 0) == 0}}- val channel = _currentChannel.value ?: return false+ if (currentContentType != ContentType.LIVE) return false+ val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return falsereturn channel.alternativeStreams.any { altUrl ->altUrl != currentStreamUrl &&altUrl !in triedAlternativeStreams &&@@ -1873,7 +1525,8 @@ class PlayerViewModel @Inject constructor(if (isCatchUpPlayback()) {return tryNextCatchUpVariantInternal()}- val channel = _currentChannel.value ?: return false+ if (currentContentType != ContentType.LIVE) return false+ val channel = currentChannelFlow.value?.sanitizedForPlayer() ?: return falsereturn tryAlternateStreamInternal(channel)}@@ -1938,7 +1591,7 @@ class PlayerViewModel @Inject constructor(return true}- private fun scheduleZapBufferWatchdog(targetIndex: Int) {+ internal fun scheduleZapBufferWatchdog(targetIndex: Int) {zapBufferWatchdogJob?.cancel()val requestVersion = prepareRequestVersionzapBufferWatchdogJob = viewModelScope.launch {@@ -1975,39 +1628,6 @@ class PlayerViewModel @Inject constructor(return false}- private fun scheduleNumericChannelCommit() {- numericInputCommitJob?.cancel()- numericInputCommitJob = viewModelScope.launch {- delay(1300)- commitNumericChannelInput()- }- }-- private fun resolveChannelByNumber(number: Int?): com.streamvault.domain.model.Channel? {- if (number == null) return null- return channelList- .withIndex()- .firstOrNull { (index, channel) -> resolveChannelNumber(channel, index) == number }- ?.value- }-- private fun resolveChannelByPrefix(prefix: String): com.streamvault.domain.model.Channel? {- return channelList- .withIndex()- .firstOrNull { (index, channel) ->- resolveChannelNumber(channel, index).toString().startsWith(prefix)- }- ?.value- }-- private fun resolveChannelNumber(- channel: com.streamvault.domain.model.Channel,- index: Int- ): Int = when (channelNumberingMode) {- ChannelNumberingMode.GROUP -> if (index >= 0) index + 1 else channel.number.takeIf { number -> number > 0 } ?: 0- ChannelNumberingMode.PROVIDER -> channel.number.takeIf { number -> number > 0 } ?: if (index >= 0) index + 1 else 0- }-fun play() = playerEngine.play()fun pause() = playerEngine.pause()fun seekForward() = playerEngine.seekForward()@@ -2045,8 +1665,8 @@ class PlayerViewModel @Inject constructor(fun toggleControls() {closeChannelInfoOverlay()- _showControls.value = !_showControls.value- if (!_showControls.value) {+ showControlsFlow.value = !showControlsFlow.value+ if (!showControlsFlow.value) {clearSeekPreview()}}@@ -2103,7 +1723,7 @@ class PlayerViewModel @Inject constructor()if (!preparePlayer(catchupStream, requestVersion)) returnplayerEngine.play()- _showControls.value = true+ showControlsFlow.value = true}fun playCatchUp(program: Program) {@@ -2111,7 +1731,7 @@ class PlayerViewModel @Inject constructor(val requestVersion = prepareRequestVersionval start = program.startTime / 1000Lval end = program.endTime / 1000L- val streamId = _currentChannel.value?.id ?: 0L+ val streamId = currentChannelFlow.value?.id ?: 0Lval providerId = currentProviderIdif (providerId == -1L || streamId == 0L) {@@ -2140,11 +1760,11 @@ class PlayerViewModel @Inject constructor(if (catchUpUrls.isNotEmpty()) {startCatchUpPlayback(urls = catchUpUrls,- title = "${_currentChannel.value?.name ?: ""}: ${program.title}",+ title = "${currentChannelFlow.value?.name ?: ""}: ${program.title}",recoveryAction = "Started program replay")} else {- val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = program.hasArchive)+ val reason = resolveCatchUpFailureMessage(currentChannelFlow.value, archiveRequested = true, programHasArchive = program.hasArchive)setLastFailureReason(reason)showPlayerNotice(message = reason,@@ -2173,85 +1793,6 @@ class PlayerViewModel @Inject constructor(}}- fun startManualRecording() {- val channel = _currentChannel.value- if (currentContentType != ContentType.LIVE || channel == null || currentProviderId <= 0) {- showPlayerNotice(message = "Recording needs a valid live channel context.")- return- }- viewModelScope.launch {- val now = System.currentTimeMillis()- val result = recordingManager.startManualRecording(- RecordingRequest(- providerId = currentProviderId,- channelId = channel.id,- channelName = channel.name,- streamUrl = currentStreamUrl,- scheduledStartMs = now,- scheduledEndMs = _currentProgram.value?.endTime ?: (now + 30 * 60_000L),- programTitle = _currentProgram.value?.title- )- )- if (result is com.streamvault.domain.model.Result.Error) {- showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)- } else {- showPlayerNotice(message = "Recording started for ${channel.name}.")- }- }- }-- fun scheduleRecording() {- scheduleRecording(RecordingRecurrence.NONE)- }-- fun scheduleDailyRecording() {- scheduleRecording(RecordingRecurrence.DAILY)- }-- fun scheduleWeeklyRecording() {- scheduleRecording(RecordingRecurrence.WEEKLY)- }-- private fun scheduleRecording(recurrence: RecordingRecurrence) {- viewModelScope.launch {- val result = scheduleRecordingUseCase(- ScheduleRecordingCommand(- contentType = currentContentType,- providerId = currentProviderId,- channel = _currentChannel.value,- streamUrl = currentStreamUrl,- currentProgram = _currentProgram.value,- nextProgram = _nextProgram.value,- recurrence = recurrence- )- )- if (result is com.streamvault.domain.model.Result.Error) {- showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)- } else {- val recurrenceLabel = when (recurrence) {- RecordingRecurrence.NONE -> ""- RecordingRecurrence.DAILY -> " daily"- RecordingRecurrence.WEEKLY -> " weekly"- }- val scheduledItem = (result as? com.streamvault.domain.model.Result.Success)?.data- val title = scheduledItem?.programTitle ?: "Recording"- showPlayerNotice(message = "$title scheduled$recurrenceLabel.")- }- }- }-- fun stopCurrentRecording() {- val recording = _currentChannelRecording.value ?: return- viewModelScope.launch {- val result = recordingManager.stopRecording(recording.id)- if (result is com.streamvault.domain.model.Result.Error) {- showPlayerNotice(message = result.message)- } else {- showPlayerNotice(message = "Recording stopped.")- }- }- }-fun dismissPlayerNotice() {playerNoticeHideJob?.cancel()_playerNotice.value = null@@ -2268,7 +1809,7 @@ class PlayerViewModel @Inject constructor(when (action) {PlayerNoticeAction.RETRY -> {appendRecoveryAction("Manual retry")- retryStream(currentStreamUrl, _currentChannel.value?.epgChannelId)+ retryStream(currentStreamUrl, currentChannelFlow.value?.epgChannelId)}PlayerNoticeAction.LAST_CHANNEL -> {appendRecoveryAction("Returned to last channel")@@ -2286,7 +1827,7 @@ class PlayerViewModel @Inject constructor(dismissPlayerNotice()}- private fun showPlayerNotice(+ internal fun showPlayerNotice(message: String,recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,actions: List<PlayerNoticeAction> = emptyList(),@@ -2330,80 +1871,11 @@ class PlayerViewModel @Inject constructor(fun restartCurrentProgram() {val program = _currentProgram.value ?: return- if (program.hasArchive || (_currentChannel.value?.catchUpSupported == true)) {+ if (program.hasArchive || (currentChannelFlow.value?.catchUpSupported == true)) {playCatchUp(program)}}- fun hideControlsAfterDelay() {- // Cancel previous job to prevent race condition- controlsHideJob?.cancel()- controlsHideJob = viewModelScope.launch {- delay(playerControlsTimeoutMs)- _showControls.value = false- }- }-- fun refreshControlsAutoHide() {- if (_showControls.value) {- hideControlsAfterDelay()- }- }-- fun cancelControlsAutoHide() {- controlsHideJob?.cancel()- controlsHideJob = null- }-- private fun hideZapOverlayAfterDelay() {- zapOverlayJob?.cancel()- zapOverlayJob = viewModelScope.launch {- delay(liveOverlayTimeoutMs)- _showZapOverlay.value = false- }- }-- private fun hasVisibleTransientLiveOverlay(): Boolean =- _showChannelInfoOverlay.value ||- _showChannelListOverlay.value ||- _showEpgOverlay.value-- private fun clearLiveOverlayAutoHide() {- liveOverlayHideJob?.cancel()- liveOverlayHideJob = null- }-- private fun clearDiagnosticsAutoHide() {- diagnosticsHideJob?.cancel()- diagnosticsHideJob = null- }-- private fun scheduleLiveOverlayAutoHide() {- if (currentContentType != ContentType.LIVE) {- clearLiveOverlayAutoHide()- return- }- liveOverlayHideJob?.cancel()- liveOverlayHideJob = viewModelScope.launch {- delay(liveOverlayTimeoutMs)- _showChannelInfoOverlay.value = false- _showChannelListOverlay.value = false- _showEpgOverlay.value = false- }- }-- private fun scheduleDiagnosticsAutoHide() {- if (currentContentType != ContentType.LIVE) {- clearDiagnosticsAutoHide()- return- }- diagnosticsHideJob?.cancel()- diagnosticsHideJob = viewModelScope.launch {- delay(diagnosticsTimeoutMs)- _showDiagnostics.value = false- }- }-fun retryStream(streamUrl: String, epgChannelId: String?) {if (isCatchUpPlayback()) {val requestVersion = beginPlaybackSession()@@ -2461,6 +1933,7 @@ class PlayerViewModel @Inject constructor(_currentEpisode.value?.id == internalContentId -> _currentEpisode.valueelse -> _currentSeries.value?.seasons+ .sanitizedForPlayer()?.asSequence()?.flatMap { it.episodes.asSequence() }?.firstOrNull { it.id == internalContentId }@@ -2507,7 +1980,7 @@ class PlayerViewModel @Inject constructor(}}- private suspend fun resolvePlaybackUrl(+ internal suspend fun resolvePlaybackUrl(logicalUrl: String,internalContentId: Long,providerId: Long,@@ -2519,90 +1992,6 @@ class PlayerViewModel @Inject constructor(contentType = contentType)?.url- private suspend fun buildCastRequest(): CastMediaRequest? {- return when (currentContentType) {- ContentType.LIVE -> {- val channel = _currentChannel.value ?: return null- val streamInfo = channelRepository.getStreamInfo(channel).getOrNull() ?: return null- streamInfo.toCastRequest(- title = mediaTitle.value ?: channel.name,- subtitle = _currentProgram.value?.title,- artworkUrl = channel.logoUrl ?: currentArtworkUrl,- isLive = true,- startPositionMs = 0L- )- }-- ContentType.MOVIE -> {- val movie = movieRepository.getMovie(currentContentId)- val streamInfo = movie?.let { movieRepository.getStreamInfo(it).getOrNull() }- ?: return directCastRequest()- streamInfo.toCastRequest(- title = currentTitle.ifBlank { movie.name },- subtitle = movie.genre,- artworkUrl = currentArtworkUrl ?: movie.posterUrl ?: movie.backdropUrl,- isLive = false,- startPositionMs = playerEngine.currentPosition.value- )- }-- ContentType.SERIES,- ContentType.SERIES_EPISODE -> directCastRequest()- }- }-- private fun directCastRequest(): CastMediaRequest? {- val url = currentStreamUrl.takeIf { it.isNotBlank() } ?: return null- return com.streamvault.domain.model.StreamInfo(url = url).toCastRequest(- title = currentTitle,- subtitle = null,- artworkUrl = currentArtworkUrl,- isLive = false,- startPositionMs = playerEngine.currentPosition.value- )- }-- private fun com.streamvault.domain.model.StreamInfo.toCastRequest(- title: String,- subtitle: String?,- artworkUrl: String?,- isLive: Boolean,- startPositionMs: Long- ): CastMediaRequest? {- val resolvedUrl = url.takeIf { it.isNotBlank() } ?: return null- val mimeType = when (inferCastStreamType(this)) {- com.streamvault.domain.model.StreamType.HLS -> "application/x-mpegURL"- com.streamvault.domain.model.StreamType.DASH -> "application/dash+xml"- com.streamvault.domain.model.StreamType.MPEG_TS -> "video/mp2t"- com.streamvault.domain.model.StreamType.RTSP -> return null- com.streamvault.domain.model.StreamType.PROGRESSIVE,- com.streamvault.domain.model.StreamType.UNKNOWN -> "video/*"- }- return CastMediaRequest(- url = resolvedUrl,- title = title.ifBlank { this.title ?: "StreamVault" },- subtitle = subtitle,- artworkUrl = artworkUrl,- mimeType = mimeType,- isLive = isLive,- startPositionMs = if (isLive) 0L else startPositionMs- )- }-- private fun inferCastStreamType(streamInfo: com.streamvault.domain.model.StreamInfo): com.streamvault.domain.model.StreamType {- if (streamInfo.streamType != com.streamvault.domain.model.StreamType.UNKNOWN) {- return streamInfo.streamType- }- val url = streamInfo.url.lowercase()- return when {- url.endsWith(".m3u8") -> com.streamvault.domain.model.StreamType.HLS- url.endsWith(".mpd") -> com.streamvault.domain.model.StreamType.DASH- url.endsWith(".ts") -> com.streamvault.domain.model.StreamType.MPEG_TS- url.startsWith("rtsp") -> com.streamvault.domain.model.StreamType.RTSP- else -> com.streamvault.domain.model.StreamType.PROGRESSIVE- }- }-fun dismissResumePrompt(resume: Boolean) {val prompt = _resumePrompt.value_resumePrompt.value = ResumePromptState() // hide@@ -2633,16 +2022,3 @@ class PlayerViewModel @Inject constructor(playerEngine.release()}}--private fun resolvePreferredAudioLanguage(preferredAudioLanguage: String?, appLanguage: String): String? {- val normalizedPreference = preferredAudioLanguage- ?.trim()- ?.takeIf { it.isNotBlank() && !it.equals("auto", ignoreCase = true) }- val effectiveTag = normalizedPreference ?: appLanguage.takeIf { it.isNotBlank() && it != "system" }- ?: Locale.getDefault().toLanguageTag()- return effectiveTag- .takeIf { it.isNotBlank() }- ?.let { Locale.forLanguageTag(it) }- ?.takeIf { it.language.isNotBlank() }- ?.toLanguageTag()-}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.ktnew file mode 100644index 00000000..1e1ddc68--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt@@ -0,0 +1,219 @@+package com.streamvault.app.ui.screens.player++import androidx.lifecycle.viewModelScope+import com.streamvault.app.cast.CastMediaRequest+import com.streamvault.app.cast.CastStartResult+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import com.streamvault.domain.usecase.ScheduleRecordingCommand+import kotlinx.coroutines.launch++fun PlayerViewModel.castCurrentMedia(onRouteSelectionRequired: () -> Unit) {+ viewModelScope.launch {+ val request = buildCastRequest()+ if (request == null) {+ showPlayerNotice(+ message = "This item cannot be sent to a Cast receiver.",+ recoveryType = PlayerRecoveryType.SOURCE+ )+ return@launch+ }++ when (castManager.startCasting(request)) {+ CastStartResult.STARTED -> {+ playerEngine.pause()+ showPlayerNotice(+ message = "Casting to the connected device.",+ recoveryType = PlayerRecoveryType.NETWORK+ )+ }++ CastStartResult.ROUTE_SELECTION_REQUIRED -> onRouteSelectionRequired()++ CastStartResult.UNAVAILABLE -> showPlayerNotice(+ message = "Google Cast is unavailable on this device.",+ recoveryType = PlayerRecoveryType.SOURCE+ )++ CastStartResult.UNSUPPORTED -> showPlayerNotice(+ message = "This stream format is not supported by Google Cast.",+ recoveryType = PlayerRecoveryType.SOURCE+ )+ }+ }+}++fun PlayerViewModel.stopCasting() {+ castManager.stopCasting()+ showPlayerNotice(+ message = "Cast session disconnected.",+ recoveryType = PlayerRecoveryType.NETWORK+ )+}++fun PlayerViewModel.startManualRecording() {+ val channel = currentChannel.value+ if (currentContentType != ContentType.LIVE || channel == null || currentProviderId <= 0) {+ showPlayerNotice(message = "Recording needs a valid live channel context.")+ return+ }+ viewModelScope.launch {+ val now = System.currentTimeMillis()+ val result = recordingManager.startManualRecording(+ RecordingRequest(+ providerId = currentProviderId,+ channelId = channel.id,+ channelName = channel.name,+ streamUrl = currentStreamUrl,+ scheduledStartMs = now,+ scheduledEndMs = currentProgram.value?.endTime ?: (now + 30 * 60_000L),+ programTitle = currentProgram.value?.title+ )+ )+ if (result is Result.Error) {+ showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)+ } else {+ showPlayerNotice(message = "Recording started for ${channel.name}.")+ }+ }+}++fun PlayerViewModel.scheduleRecording() {+ scheduleRecordingInternal(RecordingRecurrence.NONE)+}++fun PlayerViewModel.scheduleDailyRecording() {+ scheduleRecordingInternal(RecordingRecurrence.DAILY)+}++fun PlayerViewModel.scheduleWeeklyRecording() {+ scheduleRecordingInternal(RecordingRecurrence.WEEKLY)+}++private fun PlayerViewModel.scheduleRecordingInternal(recurrence: RecordingRecurrence) {+ viewModelScope.launch {+ val result = scheduleRecordingUseCase(+ ScheduleRecordingCommand(+ contentType = currentContentType,+ providerId = currentProviderId,+ channel = currentChannel.value,+ streamUrl = currentStreamUrl,+ currentProgram = currentProgram.value,+ nextProgram = nextProgram.value,+ recurrence = recurrence+ )+ )+ if (result is Result.Error) {+ showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)+ } else {+ val recurrenceLabel = when (recurrence) {+ RecordingRecurrence.NONE -> ""+ RecordingRecurrence.DAILY -> " daily"+ RecordingRecurrence.WEEKLY -> " weekly"+ }+ val scheduledItem = (result as? Result.Success)?.data+ val title = scheduledItem?.programTitle ?: "Recording"+ showPlayerNotice(message = "$title scheduled$recurrenceLabel.")+ }+ }+}++fun PlayerViewModel.stopCurrentRecording() {+ val recording = currentChannelRecording.value ?: return+ viewModelScope.launch {+ val result = recordingManager.stopRecording(recording.id)+ if (result is Result.Error) {+ showPlayerNotice(message = result.message)+ } else {+ showPlayerNotice(message = "Recording stopped.")+ }+ }+}++internal suspend fun PlayerViewModel.buildCastRequest(): CastMediaRequest? {+ return when (currentContentType) {+ ContentType.LIVE -> {+ val channel = currentChannel.value ?: return null+ val streamInfo = channelRepository.getStreamInfo(channel).getOrNull() ?: return null+ streamInfo.toCastRequest(+ title = mediaTitle.value ?: channel.name,+ subtitle = currentProgram.value?.title,+ artworkUrl = channel.logoUrl ?: currentArtworkUrl,+ isLive = true,+ startPositionMs = 0L+ )+ }++ ContentType.MOVIE -> {+ val movie = movieRepository.getMovie(currentContentId)+ val streamInfo = movie?.let { movieRepository.getStreamInfo(it).getOrNull() }+ ?: return directCastRequest()+ streamInfo.toCastRequest(+ title = currentTitle.ifBlank { movie.name },+ subtitle = movie.genre,+ artworkUrl = currentArtworkUrl ?: movie.posterUrl ?: movie.backdropUrl,+ isLive = false,+ startPositionMs = playerEngine.currentPosition.value+ )+ }++ ContentType.SERIES,+ ContentType.SERIES_EPISODE -> directCastRequest()+ }+}++internal fun PlayerViewModel.directCastRequest(): CastMediaRequest? {+ val url = currentStreamUrl.takeIf { it.isNotBlank() } ?: return null+ return StreamInfo(url = url).toCastRequest(+ title = currentTitle,+ subtitle = null,+ artworkUrl = currentArtworkUrl,+ isLive = false,+ startPositionMs = playerEngine.currentPosition.value+ )+}++internal fun StreamInfo.toCastRequest(+ title: String,+ subtitle: String?,+ artworkUrl: String?,+ isLive: Boolean,+ startPositionMs: Long+): CastMediaRequest? {+ val resolvedUrl = url.takeIf { it.isNotBlank() } ?: return null+ val mimeType = when (inferCastStreamType()) {+ StreamType.HLS -> "application/x-mpegURL"+ StreamType.DASH -> "application/dash+xml"+ StreamType.MPEG_TS -> "video/mp2t"+ StreamType.RTSP -> return null+ StreamType.PROGRESSIVE,+ StreamType.UNKNOWN -> "video/*"+ }+ return CastMediaRequest(+ url = resolvedUrl,+ title = title.ifBlank { this.title ?: "StreamVault" },+ subtitle = subtitle,+ artworkUrl = artworkUrl,+ mimeType = mimeType,+ isLive = isLive,+ startPositionMs = if (isLive) 0L else startPositionMs+ )+}++internal fun StreamInfo.inferCastStreamType(): StreamType {+ if (streamType != StreamType.UNKNOWN) {+ return streamType+ }+ val normalizedUrl = url.lowercase()+ return when {+ normalizedUrl.endsWith(".m3u8") -> StreamType.HLS+ normalizedUrl.endsWith(".mpd") -> StreamType.DASH+ normalizedUrl.endsWith(".ts") -> StreamType.MPEG_TS+ normalizedUrl.startsWith("rtsp") -> StreamType.RTSP+ else -> StreamType.PROGRESSIVE+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.ktnew file mode 100644index 00000000..90e8a710--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt@@ -0,0 +1,127 @@+package com.streamvault.app.ui.screens.player++import android.graphics.Bitmap+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ChannelQualityOption+import com.streamvault.domain.model.Season+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.DecoderMode+import java.util.Locale++data class ResumePromptState(+ val show: Boolean = false,+ val positionMs: Long = 0L,+ val title: String = ""+)++data class NumericChannelInputState(+ val input: String = "",+ val matchedChannelName: String? = null,+ val invalid: Boolean = false+)++data class PlayerNoticeState(+ val message: String = "",+ val recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,+ val actions: List<PlayerNoticeAction> = emptyList(),+ val isRetryNotice: Boolean = false+)++data class SeekPreviewState(+ val visible: Boolean = false,+ val positionMs: Long = 0L,+ val frameBitmap: Bitmap? = null,+ val artworkUrl: String? = null,+ val title: String = "",+ val isLoading: Boolean = false+)++data class PlayerDiagnosticsUiState(+ val providerName: String = "",+ val providerSourceLabel: String = "",+ val decoderMode: DecoderMode = DecoderMode.AUTO,+ val streamClassLabel: String = "Primary",+ val playbackStateLabel: String = "Idle",+ val alternativeStreamCount: Int = 0,+ val channelErrorCount: Int = 0,+ val archiveSupportLabel: String = "",+ val lastFailureReason: String? = null,+ val recentRecoveryActions: List<String> = emptyList(),+ val troubleshootingHints: List<String> = emptyList()+)++enum class PlayerRecoveryType {+ NETWORK,+ SOURCE,+ DECODER,+ DRM,+ CATCH_UP,+ BUFFER_TIMEOUT,+ UNKNOWN+}++enum class PlayerNoticeAction {+ RETRY,+ LAST_CHANNEL,+ ALTERNATE_STREAM,+ OPEN_GUIDE+}++enum class AspectRatio(val modeName: String) {+ FIT("Fit"),+ FILL("Stretch"),+ ZOOM("Zoom")+}++internal data class EpgRequestKey(+ val providerId: Long,+ val internalChannelId: Long,+ val epgChannelId: String?,+ val streamId: Long+)++internal data class PlayerUiTimeouts(+ val controlsMs: Long,+ val liveOverlayMs: Long,+ val noticeMs: Long,+ val diagnosticsMs: Long+)++internal fun resolvePreferredAudioLanguage(preferredAudioLanguage: String?, appLanguage: String): String? {+ val normalizedPreference = preferredAudioLanguage+ ?.trim()+ ?.takeIf { it.isNotBlank() && !it.equals("auto", ignoreCase = true) }+ val effectiveTag = normalizedPreference ?: appLanguage.takeIf { it.isNotBlank() && it != "system" }+ ?: Locale.getDefault().toLanguageTag()+ return effectiveTag+ .takeIf { it.isNotBlank() }+ ?.let { Locale.forLanguageTag(it) }+ ?.takeIf { it.language.isNotBlank() }+ ?.toLanguageTag()+}++internal fun Series.sanitizedForPlayer(): Series = copy(+ seasons = seasons.sanitizedForPlayer()+)++internal fun List<Season>?.sanitizedForPlayer(): List<Season> = this.orEmpty().map { season ->+ val sanitizedEpisodes = season.episodes.orEmpty()+ season.copy(+ episodes = sanitizedEpisodes,+ episodeCount = season.episodeCount.takeIf { it > 0 } ?: sanitizedEpisodes.size+ )+}++internal fun Channel.sanitizedForPlayer(): Channel {+ val sanitizedQualityOptions = qualityOptions.orEmpty()+ val sanitizedAlternativeStreams = alternativeStreams.orEmpty()+ .filter { it.isNotBlank() }+ .distinct()+ return copy(+ qualityOptions = sanitizedQualityOptions,+ alternativeStreams = sanitizedAlternativeStreams+ )+}++internal fun List<Channel>?.sanitizedChannelsForPlayer(): List<Channel> =+ this.orEmpty().map(Channel::sanitizedForPlayer)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.ktnew file mode 100644index 00000000..29e26cbf--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerZapActions.kt@@ -0,0 +1,258 @@+package com.streamvault.app.ui.screens.player++import androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.ChannelNumberingMode+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.flow.filter+import kotlinx.coroutines.flow.take+import kotlinx.coroutines.launch++fun PlayerViewModel.playNext() {+ clearNumericChannelInput()+ if (channelList.isEmpty()) return+ val nextIndex = wrappedChannelIndex(1)+ if (nextIndex == -1) return+ changeChannel(nextIndex)+}++fun PlayerViewModel.playPrevious() {+ clearNumericChannelInput()+ if (channelList.isEmpty()) return+ val prevIndex = wrappedChannelIndex(-1)+ if (prevIndex == -1) return+ changeChannel(prevIndex)+}++fun PlayerViewModel.zapToChannel(channelId: Long) {+ clearNumericChannelInput()+ if (currentContentType != ContentType.LIVE || channelList.isEmpty()) return+ val index = channelList.indexOfFirst { it.id == channelId }+ if (index != -1) {+ changeChannel(index)+ closeOverlays()+ }+}++fun PlayerViewModel.zapToLastChannel() {+ clearNumericChannelInput()+ if (currentContentType != ContentType.LIVE || channelList.isEmpty()) return+ if (previousChannelIndex in channelList.indices && previousChannelIndex != currentChannelIndex) {+ changeChannel(previousChannelIndex)+ }+}++fun PlayerViewModel.hasLastChannel(): Boolean {+ if (currentContentType != ContentType.LIVE) return false+ val channels = channelList+ if (channels.isEmpty()) return false+ return previousChannelIndex in channels.indices && previousChannelIndex != currentChannelIndex+}++fun PlayerViewModel.hasPendingNumericChannelInput(): Boolean = numericInputBuffer.isNotBlank()++fun PlayerViewModel.inputNumericChannelDigit(digit: Int) {+ if (currentContentType != ContentType.LIVE || channelList.isEmpty()) return+ if (digit !in 0..9) return++ if (numericInputBuffer.isBlank() && digit == 0 && hasLastChannel()) {+ zapToLastChannel()+ return+ }++ numericInputBuffer = if (numericInputBuffer.length >= 4) {+ digit.toString()+ } else {+ numericInputBuffer + digit.toString()+ }+ val exactMatch = resolveChannelByNumber(numericInputBuffer.toIntOrNull())+ val previewMatch = exactMatch ?: resolveChannelByPrefix(numericInputBuffer)++ numericChannelInputFlow.value = NumericChannelInputState(+ input = numericInputBuffer,+ matchedChannelName = previewMatch?.name,+ invalid = false+ )++ scheduleNumericChannelCommit()+}++fun PlayerViewModel.commitNumericChannelInput() {+ numericInputCommitJob?.cancel()+ if (numericInputBuffer.isBlank()) return++ val targetChannel = resolveChannelByNumber(numericInputBuffer.toIntOrNull())+ if (targetChannel != null) {+ val targetIndex = channelList.indexOfFirst { it.id == targetChannel.id }+ if (targetIndex != -1) {+ changeChannel(targetIndex)+ }+ clearNumericChannelInput()+ return+ }++ numericChannelInputFlow.value = NumericChannelInputState(+ input = numericInputBuffer,+ matchedChannelName = null,+ invalid = true+ )++ numericInputFeedbackJob?.cancel()+ numericInputFeedbackJob = viewModelScope.launch {+ delay(900)+ clearNumericChannelInput()+ }+}++fun PlayerViewModel.clearNumericChannelInput() {+ numericInputCommitJob?.cancel()+ numericInputFeedbackJob?.cancel()+ numericInputBuffer = ""+ numericChannelInputFlow.value = null+}++internal fun PlayerViewModel.changeChannel(index: Int) {+ clearNumericChannelInput()+ if (currentChannelIndex != -1 && currentChannelIndex != index) {+ previousChannelIndex = currentChannelIndex+ }+ val requestVersion = beginPlaybackSession()+ val channel = channelList[index]+ currentChannelIndex = index+ currentContentId = channel.id+ currentTitle = channel.name+ playbackTitleFlow.value = currentTitle+ currentStreamUrl = channel.streamUrl+ pendingCatchUpUrls = emptyList()+ updateStreamClass("Primary")+ currentChannelFlow.value = channel+ refreshCurrentChannelRecording()+ displayChannelNumberFlow.value = resolveChannelNumber(channel, index)+ recentChannelsFlow.update { channels -> channels.filterNot { it.id == channel.id } }++ playerEngine.setScrubbingMode(true)++ viewModelScope.launch {+ val resolvedUrl = resolvePlaybackUrl(channel.streamUrl, channel.id, channel.providerId, ContentType.LIVE)+ ?: return@launch+ if (!isActivePlaybackSession(requestVersion, channel.streamUrl)) return@launch+ val streamInfo = StreamInfo(+ url = resolvedUrl,+ title = currentTitle,+ streamType = StreamType.UNKNOWN+ )+ if (!preparePlayer(streamInfo, requestVersion)) return@launch+ playerEngine.play()++ playerEngine.playbackState+ .filter { it == com.streamvault.player.PlaybackState.READY }+ .take(1)+ .collect {+ if (isActivePlaybackSession(requestVersion, channel.streamUrl)) {+ playerEngine.setScrubbingMode(false)+ }+ }+ }++ preloadAdjacentChannel(index)++ requestEpg(+ providerId = currentProviderId,+ epgChannelId = channel.epgChannelId,+ streamId = channel.streamId,+ internalChannelId = channel.id+ )++ showZapOverlayFlow.value = false+ showControlsFlow.value = false+ openChannelInfoOverlay()++ triedAlternativeStreams.clear()+ triedAlternativeStreams.add(channel.streamUrl)+ if (currentContentType == ContentType.LIVE) {+ recordLivePlayback(channel)+ scheduleZapBufferWatchdog(index)+ }+}++internal fun PlayerViewModel.preloadAdjacentChannel(currentIndex: Int) {+ if (channelList.size < 2) return+ val nextIndex = (currentIndex + 1) % channelList.size+ val nextChannel = channelList[nextIndex]+ viewModelScope.launch {+ val nextUrl = resolvePlaybackUrl(+ nextChannel.streamUrl,+ nextChannel.id,+ nextChannel.providerId,+ ContentType.LIVE+ ) ?: return@launch+ playerEngine.preload(+ StreamInfo(+ url = nextUrl,+ title = nextChannel.name,+ streamType = StreamType.UNKNOWN+ )+ )+ }+}++internal fun PlayerViewModel.recordLivePlayback(channel: com.streamvault.domain.model.Channel) {+ if (currentProviderId <= 0 || currentContentType != ContentType.LIVE) return++ val playbackKey = currentProviderId to channel.id+ if (lastRecordedLivePlaybackKey == playbackKey) return+ lastRecordedLivePlaybackKey = playbackKey++ viewModelScope.launch {+ logRepositoryFailure(+ operation = "Record live playback",+ result = playbackHistoryRepository.recordPlayback(+ PlaybackHistory(+ contentId = channel.id,+ contentType = ContentType.LIVE,+ providerId = currentProviderId,+ title = channel.name,+ streamUrl = channel.streamUrl,+ lastWatchedAt = System.currentTimeMillis()+ )+ )+ )+ }+}++internal fun PlayerViewModel.scheduleNumericChannelCommit() {+ numericInputCommitJob?.cancel()+ numericInputCommitJob = viewModelScope.launch {+ delay(1300)+ commitNumericChannelInput()+ }+}++internal fun PlayerViewModel.resolveChannelByNumber(number: Int?): com.streamvault.domain.model.Channel? {+ if (number == null) return null+ return channelList+ .withIndex()+ .firstOrNull { (index, channel) -> resolveChannelNumber(channel, index) == number }+ ?.value+}++internal fun PlayerViewModel.resolveChannelByPrefix(prefix: String): com.streamvault.domain.model.Channel? {+ return channelList+ .withIndex()+ .firstOrNull { (index, channel) ->+ resolveChannelNumber(channel, index).toString().startsWith(prefix)+ }+ ?.value+}++internal fun PlayerViewModel.resolveChannelNumber(+ channel: com.streamvault.domain.model.Channel,+ index: Int+): Int = when (channelNumberingMode) {+ ChannelNumberingMode.GROUP -> if (index >= 0) index + 1 else channel.number.takeIf { it > 0 } ?: 0+ ChannelNumberingMode.PROVIDER -> channel.number.takeIf { it > 0 } ?: if (index >= 0) index + 1 else 0+}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 b490218d..7a6419b0 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@@ -82,10 +82,13 @@ import com.streamvault.app.ui.components.shell.VodClassicContentHeaderimport com.streamvault.app.ui.components.shell.VodClassicSplitLayoutimport com.streamvault.app.ui.components.shell.VodHeroStripimport com.streamvault.app.ui.components.shell.VodSectionHeader+import com.streamvault.app.ui.design.FocusRestoreHost+import com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.model.VodViewModeimport com.streamvault.app.ui.screens.vod.HandleVodUserMessageimport com.streamvault.app.ui.screens.vod.ProtectedVodPinDialogimport com.streamvault.app.ui.screens.vod.VodBrowseDefaults+import kotlinx.coroutines.delay@OptIn(ExperimentalFoundationApi::class)@Composable@@ -97,6 +100,7 @@ fun SeriesScreen() {val uiState by viewModel.uiState.collectAsStateWithLifecycle()val snackbarHostState = remember { SnackbarHostState() }+ val initialContentFocusRequester = remember { FocusRequester() }var showPinDialog by remember { mutableStateOf(false) }var pinError by remember { mutableStateOf<String?>(null) }var pendingSeriesId by remember { mutableStateOf<Long?>(null) }@@ -136,6 +140,13 @@ fun SeriesScreen()Box(modifier = Modifier.fillMaxSize()) {+ FocusRestoreHost(+ enabled = !uiState.isLoading && uiState.errorMessage == null,+ onRestore = {+ delay(100)+ initialContentFocusRequester.requestFocusSafely(tag = "SeriesScreen", target = "Initial series content")+ }+ ) {AppScreenScaffold(currentRoute = currentRoute,onNavigate = onNavigate,@@ -222,10 +233,12 @@ fun SeriesScreen(},onLoadMore = viewModel::loadMoreSelectedCategory,onLoadMorePreviewRows = viewModel::loadMorePreviewRows,- onDismissReorder = viewModel::exitCategoryReorderMode+ onDismissReorder = viewModel::exitCategoryReorderMode,+ initialFocusRequester = initialContentFocusRequester)}}+ }SnackbarHost(hostState = snackbarHostState,modifier = Modifier@@ -310,7 +323,8 @@ private fun SeriesVodContent(onOpenFresh: () -> Unit,onLoadMore: () -> Unit,onLoadMorePreviewRows: () -> Unit,- onDismissReorder: () -> Unit+ onDismissReorder: () -> Unit,+ initialFocusRequester: FocusRequester) {val screenWidth = LocalConfiguration.current.screenWidthDp.dpval isTelevisionDevice = rememberIsTelevisionDevice()@@ -375,6 +389,16 @@ private fun SeriesVodContent(category == null || !isCategoryHidden(category)}}+ val catEntries = uiState.seriesByCategory.entries+ .filter { (name, items) ->+ name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()+ }.toList()+ val fallbackSeriesId = if (heroSeries == null) {+ favoriteSeries.firstOrNull()?.id+ ?: freshSeries.firstOrNull()?.id+ ?: topRatedSeries.firstOrNull()?.id+ ?: catEntries.firstOrNull()?.value?.firstOrNull()?.id+ } else nullval categoryOptions = remember(visibleCategoryNames, uiState.categoryCounts, categoryByName, uiState.parentalControlLevel, uiState.unlockedCategoryIds) {visibleCategoryNames.map { name ->val matchedCategory = categoryByName[name]@@ -421,7 +445,8 @@ private fun SeriesVodContent(onOpenContinueWatching = onOpenContinueWatching,onOpenFresh = onOpenFresh,onLoadMore = onLoadMore,- onDismissReorder = onDismissReorder+ onDismissReorder = onDismissReorder,+ initialFocusRequester = initialFocusRequester)return}@@ -443,7 +468,9 @@ private fun SeriesVodContent(val isLocked = isSeriesLocked(heroSeries)if (isLocked) onProtectedSeriesClick(heroSeries.id) else onSeriesClick(heroSeries.id)},- modifier = Modifier.padding(top = 8.dp, bottom = 6.dp)+ modifier = Modifier+ .padding(top = 8.dp, bottom = 6.dp)+ .focusRequester(initialFocusRequester))}}@@ -573,10 +600,6 @@ private fun SeriesVodContent(}}}- val catEntries = uiState.seriesByCategory.entries- .filter { (name, items) ->- name != uiState.favoriteCategoryName && name in visibleCategoryNames && items.isNotEmpty()- }.toList()items(catEntries, key = { it.key }) { entry ->val categoryName = entry.keyval seriesList = entry.value@@ -595,7 +618,8 @@ private fun SeriesVodContent(series = series,isLocked = isLocked,onClick = { if (isLocked) onProtectedSeriesClick(series.id) else onSeriesClick(series.id) },- onLongClick = { onShowDialog(series) }+ onLongClick = { onShowDialog(series) },+ modifier = if (series.id == fallbackSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier)}}@@ -629,6 +653,7 @@ private fun SeriesVodContent(var draggingSeries by remember { mutableStateOf<Series?>(null) }var showBrowseOptions by rememberSaveable(uiState.selectedCategory) { mutableStateOf(false) }var showSearchBar by rememberSaveable(uiState.selectedCategory) { mutableStateOf(searchQuery.isNotBlank()) }+ val initialGridSeriesId = filteredGridSeries.firstOrNull()?.idif (showBrowseOptions) {VodBrowseOptionsDialog(@@ -730,6 +755,7 @@ private fun SeriesVodContent(onValueChange = onSearchQueryChange,placeholder = stringResource(R.string.series_search_placeholder),onSearch = {},+ focusRequester = initialFocusRequester,modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp))}@@ -767,7 +793,8 @@ private fun SeriesVodContent(isDragging = isDraggingThis,modifier = Modifier.fillMaxWidth()- .aspectRatio(2f / 3f),+ .aspectRatio(2f / 3f)+ .then(if (!showSearchBar && series.id == initialGridSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier),onClick = {if (uiState.isReorderMode) {draggingSeries = if (isDraggingThis) null else series@@ -819,7 +846,8 @@ private fun SeriesVodClassicContent(onOpenContinueWatching: () -> Unit,onOpenFresh: () -> Unit,onLoadMore: () -> Unit,- onDismissReorder: () -> Unit+ onDismissReorder: () -> Unit,+ initialFocusRequester: FocusRequester) {val allLabel = stringResource(R.string.vod_classic_all)val continueLabel = stringResource(R.string.vod_classic_continue_watching)@@ -876,6 +904,7 @@ private fun SeriesVodClassicContent(if (uiState.isReorderMode) uiState.filteredSeries else baseSeries}var draggingSeries by remember { mutableStateOf<Series?>(null) }+ val initialGridSeriesId = filteredGridSeries.firstOrNull()?.idLaunchedEffect(uiState.vodViewMode, uiState.selectedCategory, uiState.isReorderMode) {if (uiState.vodViewMode == VodViewMode.CLASSIC && uiState.selectedCategory == null && !uiState.isReorderMode) {@@ -1035,6 +1064,7 @@ private fun SeriesVodClassicContent(onValueChange = onSearchQueryChange,placeholder = stringResource(R.string.series_search_placeholder),onSearch = {},+ focusRequester = initialFocusRequester,modifier = Modifier.fillMaxWidth())}@@ -1086,7 +1116,8 @@ private fun SeriesVodClassicContent(isDragging = isDraggingThis,modifier = Modifier.fillMaxWidth()- .aspectRatio(2f / 3f),+ .aspectRatio(2f / 3f)+ .then(if (!showSearchBar && series.id == initialGridSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier),onClick = {if (uiState.isReorderMode) {draggingSeries = if (isDraggingThis) null else seriesdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.ktnew file mode 100644index 00000000..9b90dc7a--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsAppUpdateActions.kt@@ -0,0 +1,137 @@+package com.streamvault.app.ui.screens.settings++import android.app.Application+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import com.streamvault.app.R+import com.streamvault.app.update.AppUpdateInstaller+import com.streamvault.app.update.GitHubReleaseChecker+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Result++internal class SettingsAppUpdateActions(+ private val appContext: Application,+ private val preferencesRepository: PreferencesRepository,+ private val gitHubReleaseChecker: GitHubReleaseChecker,+ private val appUpdateInstaller: AppUpdateInstaller,+ private val uiState: MutableStateFlow<SettingsUiState>+) {+ private var updateCheckInFlight = false++ fun shouldAutoCheckForUpdates(lastCheckedAt: Long?): Boolean {+ val now = System.currentTimeMillis()+ val checkIntervalMs = 24L * 60L * 60L * 1000L+ return lastCheckedAt == null || now - lastCheckedAt >= checkIntervalMs+ }++ fun checkForAppUpdates(+ scope: CoroutineScope,+ manual: Boolean,+ isRemoteVersionNewer: (Int?, String) -> Boolean+ ) {+ if (updateCheckInFlight) return+ updateCheckInFlight = true+ scope.launch {+ val checkedAt = System.currentTimeMillis()+ uiState.update {+ it.copy(+ isCheckingForUpdates = true,+ appUpdate = it.appUpdate.copy(errorMessage = null)+ )+ }+ preferencesRepository.setLastAppUpdateCheckTimestamp(checkedAt)+ when (val result = gitHubReleaseChecker.fetchLatestRelease()) {+ is Result.Error -> {+ uiState.update {+ it.copy(+ isCheckingForUpdates = false,+ userMessage = if (manual) result.message else it.userMessage,+ appUpdate = it.appUpdate.copy(+ lastCheckedAt = checkedAt,+ errorMessage = result.message+ )+ )+ }+ }+ is Result.Success -> {+ val release = result.data+ preferencesRepository.setCachedAppUpdateRelease(+ versionName = release.versionName,+ versionCode = release.versionCode,+ releaseUrl = release.releaseUrl,+ downloadUrl = release.downloadUrl,+ releaseNotes = release.releaseNotes,+ publishedAt = release.publishedAt+ )+ val updateAvailable = isRemoteVersionNewer(+ release.versionCode,+ release.versionName+ )+ uiState.update {+ it.copy(+ isCheckingForUpdates = false,+ userMessage = if (manual) {+ if (updateAvailable) {+ appContext.getString(R.string.settings_update_available_message, release.versionName)+ } else {+ appContext.getString(R.string.settings_update_current_message)+ }+ } else {+ it.userMessage+ },+ appUpdate = AppUpdateUiModel(+ latestVersionName = release.versionName,+ latestVersionCode = release.versionCode,+ releaseUrl = release.releaseUrl,+ downloadUrl = release.downloadUrl,+ releaseNotes = release.releaseNotes,+ publishedAt = release.publishedAt,+ isUpdateAvailable = updateAvailable,+ lastCheckedAt = checkedAt,+ errorMessage = null+ ).withDownloadState(it.appUpdate.toDownloadState())+ )+ }+ appUpdateInstaller.refreshState()+ }+ Result.Loading -> {+ uiState.update { it.copy(isCheckingForUpdates = false) }+ }+ }+ updateCheckInFlight = false+ }+ }++ fun downloadLatestUpdate(scope: CoroutineScope) {+ val latestRelease = uiState.value.appUpdate.toReleaseInfoOrNull() ?: run {+ uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_update_download_unavailable))+ }+ return+ }++ scope.launch {+ when (val result = appUpdateInstaller.startDownload(latestRelease)) {+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ is Result.Success -> uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_update_download_started))+ }+ Result.Loading -> Unit+ }+ }+ }++ fun installDownloadedUpdate(scope: CoroutineScope) {+ scope.launch {+ when (val result = appUpdateInstaller.installDownloadedUpdate()) {+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ is Result.Success -> uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_update_install_started))+ }+ Result.Loading -> Unit+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.ktnew file mode 100644index 00000000..bcb0451c--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt@@ -0,0 +1,120 @@+package com.streamvault.app.ui.screens.settings++import com.streamvault.domain.manager.BackupConflictStrategy+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.usecase.ExportBackup+import com.streamvault.domain.usecase.ExportBackupCommand+import com.streamvault.domain.usecase.ExportBackupResult+import com.streamvault.domain.usecase.ImportBackup+import com.streamvault.domain.usecase.ImportBackupCommand+import com.streamvault.domain.usecase.ImportBackupResult+import com.streamvault.domain.usecase.InspectBackupCommand+import com.streamvault.domain.usecase.InspectBackupResult+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class SettingsBackupActions(+ private val exportBackup: ExportBackup,+ private val importBackup: ImportBackup,+ private val uiState: MutableStateFlow<SettingsUiState>+) {+ fun exportConfig(scope: CoroutineScope, uriString: String) {+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ val result = exportBackup(ExportBackupCommand(uriString))+ uiState.update { state ->+ state.copy(+ isSyncing = false,+ userMessage = if (result is ExportBackupResult.Error) {+ "Export failed: ${result.message}"+ } else {+ "Configuration exported successfully"+ }+ )+ }+ }+ }++ fun inspectBackup(scope: CoroutineScope, uriString: String) {+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ val result = importBackup.inspect(InspectBackupCommand(uriString))+ uiState.update { state ->+ when (result) {+ is InspectBackupResult.Error -> state.copy(+ isSyncing = false,+ userMessage = "Import failed: ${result.message}"+ )+ is InspectBackupResult.Success -> state.copy(+ isSyncing = false,+ pendingBackupUri = result.uriString,+ backupPreview = result.preview,+ backupImportPlan = result.defaultPlan+ )+ }+ }+ }+ }++ fun dismissBackupPreview() {+ uiState.update {+ it.copy(+ backupPreview = null,+ pendingBackupUri = null,+ backupImportPlan = BackupImportPlan()+ )+ }+ }++ fun setBackupConflictStrategy(strategy: BackupConflictStrategy) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(conflictStrategy = strategy)) }+ }++ fun setImportPreferences(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPreferences = enabled)) }+ }++ fun setImportProviders(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importProviders = enabled)) }+ }++ fun setImportSavedLibrary(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importSavedLibrary = enabled)) }+ }++ fun setImportPlaybackHistory(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPlaybackHistory = enabled)) }+ }++ fun setImportMultiViewPresets(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importMultiViewPresets = enabled)) }+ }++ fun setImportRecordingSchedules(enabled: Boolean) {+ uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importRecordingSchedules = enabled)) }+ }++ fun confirmBackupImport(scope: CoroutineScope) {+ val uriString = uiState.value.pendingBackupUri ?: return+ val plan = uiState.value.backupImportPlan+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ val result = importBackup.confirm(ImportBackupCommand(uriString, plan))+ uiState.update { state ->+ state.copy(+ isSyncing = false,+ userMessage = if (result is ImportBackupResult.Error) {+ "Import failed: ${result.message}"+ } else {+ "Configuration imported: ${(result as ImportBackupResult.Success).importedSummary}"+ },+ backupPreview = null,+ pendingBackupUri = null,+ backupImportPlan = BackupImportPlan()+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.ktnew file mode 100644index 00000000..95bfa263--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDialogComponents.kt@@ -0,0 +1,1356 @@+package com.streamvault.app.ui.screens.settings++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.RadioButton+import androidx.compose.material3.Switch+import androidx.compose.runtime.*+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusProperties+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import androidx.tv.material3.*+import com.streamvault.app.R+import com.streamvault.app.localization.localeForLanguageTag+import com.streamvault.app.localization.supportedAppLanguageTags+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButton+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.design.FocusSpec+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode+import com.streamvault.app.ui.model.VodViewMode+import com.streamvault.app.ui.theme.*+import com.streamvault.domain.model.CategorySortMode+import com.streamvault.domain.model.ChannelNumberingMode+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.DecoderMode+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingSourceType+import kotlinx.coroutines.launch+import java.text.DateFormat+import java.util.Locale++internal enum class ParentalAction {+ ChangeLevel, ChangePin, SetNewPin+}++@Composable+internal fun PremiumSelectionDialog(+ title: String,+ onDismiss: () -> Unit,+ content: @Composable ColumnScope.() -> Unit+) {+ val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()+ Dialog(onDismissRequest = onDismiss) {+ val dialogContent: @Composable (Modifier) -> Unit = { resolvedModifier ->+ androidx.compose.material3.Surface(+ shape = RoundedCornerShape(14.dp),+ color = SurfaceElevated,+ modifier = resolvedModifier+ .border(1.dp, Primary.copy(alpha = 0.4f), RoundedCornerShape(14.dp))+ ) {+ Column(+ modifier = Modifier.padding(18.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleMedium,+ color = Primary+ )+ HorizontalDivider(color = Color.White.copy(alpha = 0.1f))+ Column(+ verticalArrangement = Arrangement.spacedBy(6.dp),+ modifier = Modifier.padding(top = 6.dp)+ ) {+ content()+ }+ Row(+ modifier = Modifier.fillMaxWidth().padding(top = 8.dp),+ horizontalArrangement = Arrangement.End+ ) {+ TvClickableSurface(+ onClick = onDismiss,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.2f),+ focusedContainerColor = Primary.copy(alpha = 0.4f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_cancel),+ style = MaterialTheme.typography.labelMedium,+ color = Primary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)+ )+ }+ }+ }+ }+ }++ if (isTelevisionDevice) {+ dialogContent(Modifier.fillMaxWidth(0.62f))+ } else {+ BoxWithConstraints(+ modifier = Modifier.fillMaxWidth(),+ contentAlignment = Alignment.Center+ ) {+ val dialogWidthFraction = when {+ maxWidth < 700.dp -> 0.92f+ maxWidth < 1000.dp -> 0.78f+ else -> 0.62f+ }+ dialogContent(Modifier.fillMaxWidth(dialogWidthFraction))+ }+ }+ }+}++@Composable+internal fun TimeoutValueDialog(+ title: String,+ subtitle: String,+ initialValue: Int,+ onDismiss: () -> Unit,+ onConfirm: (Int) -> Unit+) {+ var value by rememberSaveable(initialValue) { mutableStateOf(initialValue.toString()) }+ val parsedValue = value.toIntOrNull()+ val isValid = parsedValue != null && parsedValue in 2..60++ PremiumDialog(+ title = title,+ subtitle = subtitle,+ onDismissRequest = onDismiss,+ widthFraction = 0.42f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(+ text = stringResource(R.string.settings_timeout_seconds_label),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ NumericSettingsTextField(+ value = value,+ onValueChange = { updated -> value = updated.filter(Char::isDigit).take(2) },+ placeholder = stringResource(R.string.settings_timeout_seconds_placeholder)+ )+ Text(+ text = if (isValid) {+ formatTimeoutSecondsLabel(parsedValue ?: initialValue, androidx.compose.ui.platform.LocalContext.current)+ } else {+ stringResource(R.string.settings_timeout_validation)+ },+ style = MaterialTheme.typography.bodySmall,+ color = if (isValid) OnSurfaceDim else Color(0xFFFF8A80)+ )+ }+ },+ footer = {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)+ ) {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_timeout_apply),+ onClick = { parsedValue?.let(onConfirm) },+ enabled = isValid+ )+ }+ }+ )+}++@Composable+internal fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clickable(onClick = onSelect)+ .padding(vertical = 12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ RadioButton(+ selected = level == currentLevel,+ onClick = onSelect+ )+ Spacer(modifier = Modifier.width(8.dp))+ Text(text, style = MaterialTheme.typography.bodyMedium, color = OnBackground)+ }+}++@Composable+private fun NumericSettingsTextField(+ value: String,+ onValueChange: (String) -> Unit,+ placeholder: String+) {+ val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()+ val focusRequester = remember { FocusRequester() }+ val keyboardController = LocalSoftwareKeyboardController.current+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var fieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ val isFocused = hasContainerFocus || hasInputFocus++ LaunchedEffect(value) {+ if (value != fieldValue.text) {+ fieldValue = TextFieldValue(text = value, selection = TextRange(value.length))+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) return@LaunchedEffect+ focusRequester.requestFocus()+ keyboardController?.show()+ pendingInputActivation = false+ }++ TvClickableSurface(+ onClick = {+ if (!isTelevisionDevice) {+ focusRequester.requestFocus()+ keyboardController?.show()+ return@TvClickableSurface+ }+ acceptsInput = true+ pendingInputActivation = true+ },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.12f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .onFocusChanged { hasContainerFocus = it.isFocused }+ ) {+ Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {+ if (value.isEmpty() && !isFocused) {+ Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)+ }+ BasicTextField(+ value = fieldValue,+ onValueChange = { updatedValue ->+ val digitsOnly = updatedValue.text.filter(Char::isDigit).take(2)+ fieldValue = updatedValue.copy(+ text = digitsOnly,+ selection = TextRange(digitsOnly.length.coerceAtMost(digitsOnly.length))+ )+ if (digitsOnly != value) {+ onValueChange(digitsOnly)+ }+ },+ textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),+ singleLine = true,+ cursorBrush = SolidColor(Primary),+ keyboardOptions = KeyboardOptions(+ keyboardType = KeyboardType.Number,+ imeAction = ImeAction.Done+ ),+ keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onFocusChanged {+ hasInputFocus = it.isFocused+ if (!it.isFocused) {+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()+ }+ },+ readOnly = isTelevisionDevice && !acceptsInput+ )+ }+ }+}++@Composable+internal fun QualityCapSelectionDialog(+ title: String,+ currentValue: Int?,+ onDismiss: () -> Unit,+ onSelect: (Int?) -> Unit+) {+ val context = androidx.compose.ui.platform.LocalContext.current+ val options = remember(context) {+ listOf<Int?>(null, 2160, 1080, 720, 480)+ }+ PremiumSelectionDialog(+ title = title,+ onDismiss = onDismiss+ ) {+ options.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = formatQualityCapLabel(option, context.getString(R.string.settings_quality_cap_auto)),+ currentLevel = if (option == currentValue) index else -1,+ onSelect = { onSelect(option) }+ )+ }+ }+}++@Composable+internal fun CategorySortModeDialog(+ type: ContentType,+ currentMode: CategorySortMode,+ onDismiss: () -> Unit,+ onModeSelected: (CategorySortMode) -> Unit+) {+ val context = androidx.compose.ui.platform.LocalContext.current+ PremiumDialog(+ title = categoryTypeLabel(type, context),+ subtitle = categoryTypeDescription(type, context),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ CategorySortMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == currentMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = formatCategorySortModeLabel(mode, context),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == currentMode) Primary else OnBackground+ )+ Text(+ text = sortModeLabel(mode, context),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun ParentalControlCard(+ level: Int,+ hasParentalPin: Boolean,+ hasActiveProvider: Boolean,+ onChangeLevel: () -> Unit,+ onChangePin: () -> Unit+) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(SurfaceElevated, RoundedCornerShape(8.dp))+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column {+ Text(stringResource(R.string.settings_protection_level), style = MaterialTheme.typography.bodyLarge, color = OnBackground)+ Text(+ text = when(level) {+ 0 -> stringResource(R.string.settings_level_off)+ 1 -> stringResource(R.string.settings_level_locked)+ 2 -> stringResource(R.string.settings_level_hidden)+ else -> stringResource(R.string.settings_level_unknown)+ },+ style = MaterialTheme.typography.bodyMedium,+ color = if (level == 0) ErrorColor else Primary+ )+ }++ // Custom Focusable Button for "Change"+ TvClickableSurface(+ onClick = onChangeLevel,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.2f),+ focusedContainerColor = Secondary.copy(alpha = 0.5f),+ contentColor = Secondary,+ focusedContentColor = Secondary+ )+ ) {+ Text(+ text = stringResource(R.string.settings_change),+ style = MaterialTheme.typography.labelMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ }++ HorizontalDivider(color = Color.White.copy(alpha = 0.1f))++ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(stringResource(R.string.settings_parental_pin), style = MaterialTheme.typography.bodyLarge, color = OnBackground)++ // Custom Focusable Button for "Change PIN"+ TvClickableSurface(+ onClick = onChangePin,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.2f),+ focusedContainerColor = Primary.copy(alpha = 0.5f),+ contentColor = Primary,+ focusedContentColor = Primary+ )+ ) {+ Text(+ text = stringResource(if (hasParentalPin) R.string.settings_change_pin else R.string.settings_set_pin),+ style = MaterialTheme.typography.labelMedium,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ }+ }+}++@Composable+internal fun LiveTvChannelModeDialog(+ selectedMode: LiveTvChannelMode,+ onDismiss: () -> Unit,+ onModeSelected: (LiveTvChannelMode) -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_live_tv_channel_mode),+ subtitle = stringResource(R.string.settings_live_tv_channel_mode_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ LiveTvChannelMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(mode.labelResId()),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == selectedMode) Primary else OnBackground+ )+ Text(+ text = stringResource(mode.descriptionResId()),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun LiveTvQuickFilterVisibilityDialog(+ selectedMode: LiveTvQuickFilterVisibilityMode,+ onDismiss: () -> Unit,+ onModeSelected: (LiveTvQuickFilterVisibilityMode) -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_live_tv_quick_filter_visibility),+ subtitle = stringResource(R.string.settings_live_tv_quick_filter_visibility_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ LiveTvQuickFilterVisibilityMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(mode.labelResId()),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == selectedMode) Primary else OnBackground+ )+ Text(+ text = stringResource(mode.descriptionResId()),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun SettingsSectionHeader(+ title: String,+ subtitle: String+) {+ Column(+ modifier = Modifier.fillMaxWidth(),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleMedium,+ color = Primary+ )+ Text(+ text = subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+}++@Composable+internal fun VodViewModeDialog(+ selectedMode: VodViewMode,+ onDismiss: () -> Unit,+ onModeSelected: (VodViewMode) -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_vod_view_mode),+ subtitle = stringResource(R.string.settings_vod_view_mode_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ VodViewMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(mode.labelResId()),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == selectedMode) Primary else OnBackground+ )+ Text(+ text = stringResource(mode.descriptionResId()),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun LiveChannelNumberingModeDialog(+ selectedMode: ChannelNumberingMode,+ onDismiss: () -> Unit,+ onModeSelected: (ChannelNumberingMode) -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_live_channel_numbering_mode),+ subtitle = stringResource(R.string.settings_live_channel_numbering_mode_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ ChannelNumberingMode.entries.forEach { mode ->+ TvClickableSurface(+ onClick = { onModeSelected(mode) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(mode.labelResId()),+ style = MaterialTheme.typography.titleSmall,+ color = if (mode == selectedMode) Primary else OnBackground+ )+ Text(+ text = stringResource(mode.descriptionResId()),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun SettingsRow(label: String, value: String) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = {},+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .mouseClickable(+ focusRequester = focusRequester,+ onClick = {}+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = value, style = MaterialTheme.typography.bodyMedium, color = OnBackground)+ }+ }+}++@Composable+internal fun ClickableSettingsRow(label: String, value: String, onClick: () -> Unit) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .mouseClickable(+ focusRequester = focusRequester,+ onClick = onClick+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = value, style = MaterialTheme.typography.bodyMedium, color = Primary)+ }+ }+}++@Composable+internal fun SwitchSettingsRow(label: String, value: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = { onCheckedChange(!checked) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .mouseClickable(+ focusRequester = focusRequester,+ onClick = { onCheckedChange(!checked) }+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 8.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(text = value, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ }+ Switch(+ checked = checked,+ onCheckedChange = { onCheckedChange(it) }+ )+ }+ }+}++internal fun formatLatestReleaseLabel(update: AppUpdateUiModel, context: android.content.Context): String {+ val versionName = update.latestVersionName ?: return context.getString(R.string.settings_update_not_checked)+ val versionCodeSuffix = update.latestVersionCode?.let { " ($it)" }.orEmpty()+ return "$versionName$versionCodeSuffix"+}++internal fun formatUpdateStatusLabel(update: AppUpdateUiModel, context: android.content.Context): String {+ val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&+ (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)+ return when {+ update.errorMessage != null -> context.getString(R.string.settings_update_status_check_failed)+ update.downloadStatus == com.streamvault.app.update.AppUpdateDownloadStatus.Downloading -> context.getString(R.string.settings_update_status_downloading)+ update.downloadStatus == com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded && downloadedReleaseMatchesLatest -> context.getString(R.string.settings_update_status_ready_to_install)+ update.latestVersionName == null -> context.getString(R.string.settings_update_not_checked)+ update.isUpdateAvailable -> context.getString(R.string.settings_update_status_available)+ else -> context.getString(R.string.settings_update_status_current)+ }+}++internal fun formatUpdateCheckTimeLabel(timestamp: Long?, context: android.content.Context): String {+ if (timestamp == null || timestamp <= 0L) {+ return context.getString(R.string.settings_update_not_checked)+ }+ return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(java.util.Date(timestamp))+}++internal fun shouldShowUpdateDownloadAction(update: AppUpdateUiModel): Boolean {+ val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&+ (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)+ return when (update.downloadStatus) {+ com.streamvault.app.update.AppUpdateDownloadStatus.Downloading,+ com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded -> downloadedReleaseMatchesLatest || (update.isUpdateAvailable && !update.downloadUrl.isNullOrBlank())+ else -> update.isUpdateAvailable && !update.downloadUrl.isNullOrBlank()+ }+}++internal fun formatUpdateDownloadLabel(update: AppUpdateUiModel, context: android.content.Context): String {+ val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&+ (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)+ return when (update.downloadStatus) {+ com.streamvault.app.update.AppUpdateDownloadStatus.Downloading -> context.getString(R.string.settings_update_download_in_progress)+ com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded -> {+ if (downloadedReleaseMatchesLatest) {+ context.getString(R.string.settings_update_install_action)+ } else {+ context.getString(R.string.settings_update_download_action)+ }+ }+ else -> context.getString(R.string.settings_update_download_action)+ }+}+@Composable+internal fun LiveTvQuickFiltersDialog(+ filters: List<String>,+ onDismiss: () -> Unit,+ onAddFilter: (String) -> Unit,+ onRemoveFilter: (String) -> Unit+) {+ var pendingFilter by rememberSaveable { mutableStateOf("") }++ PremiumDialog(+ title = stringResource(R.string.settings_live_tv_quick_filters_dialog_title),+ subtitle = stringResource(R.string.settings_live_tv_quick_filters_dialog_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.5f,+ content = {+ EpgSourceTextField(+ value = pendingFilter,+ onValueChange = { pendingFilter = it },+ placeholder = stringResource(R.string.settings_live_tv_quick_filters_placeholder)+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.settings_live_tv_quick_filters_add),+ enabled = pendingFilter.isNotBlank(),+ onClick = {+ onAddFilter(pendingFilter)+ pendingFilter = ""+ }+ )+ if (filters.isEmpty()) {+ Text(+ text = stringResource(R.string.settings_live_tv_quick_filters_empty),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ } else {+ Text(+ text = stringResource(R.string.settings_live_tv_quick_filters_saved),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim+ )+ LazyColumn(+ modifier = Modifier.heightIn(max = 260.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ items(filters, key = { it }) { filter ->+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .background(Color.White.copy(alpha = 0.06f), RoundedCornerShape(12.dp))+ .padding(horizontal = 14.dp, vertical = 10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = filter,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface,+ modifier = Modifier.weight(1f)+ )+ TvButton(onClick = { onRemoveFilter(filter) }) {+ Text(stringResource(R.string.settings_live_tv_quick_filters_remove))+ }+ }+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ }+ )+}++internal fun formatLiveTvQuickFiltersValue(filters: List<String>, context: android.content.Context): String {+ if (filters.isEmpty()) {+ return context.getString(R.string.settings_live_tv_quick_filters_none)+ }+ return context.resources.getQuantityString(+ R.plurals.settings_live_tv_quick_filters_count,+ filters.size,+ filters.size+ )+}++@Composable+internal fun SettingsNavItem(+ label: String,+ badgeChar: String,+ accentColor: Color,+ isSelected: Boolean,+ modifier: Modifier = Modifier,+ onClick: () -> Unit+) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(0.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.11f) else Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.22f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .mouseClickable(focusRequester = focusRequester, onClick = onClick)+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 10.dp, vertical = 12.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Box(+ Modifier+ .width(3.dp)+ .height(22.dp)+ .background(+ color = if (isSelected) Primary else Color.Transparent,+ shape = RoundedCornerShape(2.dp)+ )+ )+ Box(+ Modifier+ .size(28.dp)+ .background(accentColor.copy(alpha = 0.18f), RoundedCornerShape(7.dp)),+ contentAlignment = Alignment.Center+ ) {+ Text(+ text = badgeChar,+ style = MaterialTheme.typography.labelSmall,+ color = accentColor,+ fontWeight = FontWeight.Bold+ )+ }+ Text(+ text = label,+ style = MaterialTheme.typography.labelLarge,+ color = if (isSelected) Primary else OnBackground,+ fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal+ )+ }+ }+}++internal fun formatBytes(bytes: Long): String {+ if (bytes <= 0L) return "0 B"+ val kb = 1024.0+ val mb = kb * 1024.0+ val gb = mb * 1024.0+ return when {+ bytes >= gb -> String.format(Locale.getDefault(), "%.1f GB", bytes / gb)+ bytes >= mb -> String.format(Locale.getDefault(), "%.1f MB", bytes / mb)+ bytes >= kb -> String.format(Locale.getDefault(), "%.1f KB", bytes / kb)+ else -> "$bytes B"+ }+}++internal fun formatTimestamp(timestampMs: Long): String {+ if (timestampMs <= 0L) return "--:--"+ return java.text.SimpleDateFormat("MMM d, HH:mm", Locale.getDefault()).format(java.util.Date(timestampMs))+}++internal data class AppLanguageOption(+ val tag: String,+ val label: String+)++internal fun supportedAppLanguages(systemDefaultLabel: String): List<AppLanguageOption> {+ val localeTags = listOf("system") + supportedAppLanguageTags()++ return localeTags.map { tag ->+ AppLanguageOption(+ tag = tag,+ label = if (tag == "system") {+ systemDefaultLabel+ } else {+ val locale = localeForLanguageTag(tag)+ locale.getDisplayLanguage(locale)+ .replaceFirstChar { character ->+ if (character.isLowerCase()) {+ character.titlecase(locale)+ } else {+ character.toString()+ }+ }+ }+ )+ }+}++internal fun supportedAudioLanguages(autoLabel: String): List<AppLanguageOption> {+ return buildList {+ add(AppLanguageOption(tag = "auto", label = autoLabel))+ addAll(supportedAppLanguages(autoLabel).filterNot { it.tag == "system" })+ }+}++internal data class SubtitleScaleOption(+ val scale: Float,+ val label: (android.content.Context) -> String+)++internal data class SubtitleColorOption(+ val colorArgb: Int,+ val label: String+)++internal fun subtitleSizeOptions(): List<SubtitleScaleOption> {+ return listOf(+ SubtitleScaleOption(0.85f) { it.getString(R.string.settings_subtitle_size_small) },+ SubtitleScaleOption(1f) { it.getString(R.string.settings_subtitle_size_default) },+ SubtitleScaleOption(1.15f) { it.getString(R.string.settings_subtitle_size_large) },+ SubtitleScaleOption(1.3f) { it.getString(R.string.settings_subtitle_size_extra_large) }+ )+}++internal fun subtitleTextColorOptions(context: android.content.Context): List<SubtitleColorOption> {+ return listOf(+ SubtitleColorOption(0xFFFFFFFF.toInt(), context.getString(R.string.settings_subtitle_color_white)),+ SubtitleColorOption(0xFFFFEB3B.toInt(), context.getString(R.string.settings_subtitle_color_yellow)),+ SubtitleColorOption(0xFF80DEEA.toInt(), context.getString(R.string.settings_subtitle_color_cyan)),+ SubtitleColorOption(0xFFA5D6A7.toInt(), context.getString(R.string.settings_subtitle_color_green))+ )+}++internal fun subtitleBackgroundColorOptions(context: android.content.Context): List<SubtitleColorOption> {+ return listOf(+ SubtitleColorOption(0x00000000, context.getString(R.string.settings_subtitle_background_transparent)),+ SubtitleColorOption(0x80000000.toInt(), context.getString(R.string.settings_subtitle_background_dim)),+ SubtitleColorOption(0xCC000000.toInt(), context.getString(R.string.settings_subtitle_background_black)),+ SubtitleColorOption(0xCC102A43.toInt(), context.getString(R.string.settings_subtitle_background_blue))+ )+}++internal fun displayLanguageLabel(languageTag: String, defaultLabel: String): String {+ if (languageTag.isBlank() || languageTag == "system" || languageTag == "auto") return defaultLabel+ val locale = localeForLanguageTag(languageTag)+ if (locale.language.isBlank()) return defaultLabel+ return locale.getDisplayLanguage(Locale.getDefault())+ .replaceFirstChar { character ->+ if (character.isLowerCase()) {+ character.titlecase(Locale.getDefault())+ } else {+ character.toString()+ }+ }+}++internal fun formatPlaybackSpeedLabel(speed: Float): String {+ return if (speed % 1f == 0f) {+ "${speed.toInt()}x"+ } else {+ "${("%.2f".format(Locale.US, speed)).trimEnd('0').trimEnd('.')}x"+ }+}++@Composable+internal fun RecordingMetaPill(label: String, value: String) {+ Column(+ modifier = Modifier+ .widthIn(min = 92.dp, max = 160.dp)+ .background(Color.White.copy(alpha = 0.05f), RoundedCornerShape(10.dp))+ .padding(horizontal = 7.dp, vertical = 5.dp)+ ) {+ Text(text = label, style = MaterialTheme.typography.labelSmall, color = OnSurfaceDim)+ Text(text = value, style = MaterialTheme.typography.labelMedium, color = OnBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+}++internal fun summarizeRecordingOutputPath(path: String): String {+ val trimmed = path.trim()+ if (trimmed.isBlank()) return trimmed+ val decoded = runCatching { android.net.Uri.decode(trimmed) }.getOrDefault(trimmed)+ return decoded+ .substringAfterLast('/')+ .substringAfterLast('\\')+ .ifBlank { decoded }+}++@Composable+internal fun RecordingActionButton(label: String, accent: Color, onClick: () -> Unit) {+ TvButton(+ onClick = onClick,+ modifier = Modifier+ .widthIn(min = 190.dp, max = 260.dp)+ .heightIn(min = 52.dp),+ shape = ButtonDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ButtonDefaults.colors(+ containerColor = accent.copy(alpha = 0.14f),+ focusedContainerColor = accent.copy(alpha = 0.28f),+ contentColor = accent,+ focusedContentColor = accent+ ),+ scale = ButtonDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = label,+ color = accent,+ style = MaterialTheme.typography.labelMedium,+ maxLines = 2,+ modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)+ )+ }+}++@Composable+internal fun SimpleTextValueDialog(+ title: String,+ subtitle: String,+ initialValue: String,+ onDismiss: () -> Unit,+ onConfirm: (String) -> Unit+) {+ var value by remember(initialValue) { mutableStateOf(initialValue) }+ PremiumDialog(+ title = title,+ subtitle = subtitle,+ onDismissRequest = onDismiss,+ widthFraction = 0.58f,+ content = {+ EpgSourceTextField(+ value = value,+ onValueChange = { value = it },+ placeholder = initialValue+ )+ },+ footer = {+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.settings_save),+ onClick = { onConfirm(value.trim()) }+ )+ }+ }+ )+}++internal fun formatRecordingSourceType(sourceType: RecordingSourceType): String = when (sourceType) {+ RecordingSourceType.TS -> "TS"+ RecordingSourceType.HLS -> "HLS"+ RecordingSourceType.DASH -> "DASH"+ RecordingSourceType.UNKNOWN -> "Auto"+}++internal fun formatRecordingFailureCategory(category: RecordingFailureCategory): String = when (category) {+ RecordingFailureCategory.NONE -> "None"+ RecordingFailureCategory.NETWORK -> "Network"+ RecordingFailureCategory.STORAGE -> "Storage"+ RecordingFailureCategory.AUTH -> "Auth"+ RecordingFailureCategory.TOKEN_EXPIRED -> "Token"+ RecordingFailureCategory.DRM_UNSUPPORTED -> "DRM"+ RecordingFailureCategory.FORMAT_UNSUPPORTED -> "Format"+ RecordingFailureCategory.SCHEDULE_CONFLICT -> "Conflict"+ RecordingFailureCategory.PROVIDER_LIMIT -> "Connection limit"+ RecordingFailureCategory.UNKNOWN -> "Unknown"+}++internal fun playerTimeoutOptions(): List<Int> = listOf(2, 3, 4, 5, 6, 8, 10, 15, 20, 30)++internal fun formatDecoderModeLabel(mode: DecoderMode, context: android.content.Context): String {+ return when (mode) {+ DecoderMode.AUTO -> context.getString(R.string.settings_decoder_auto)+ DecoderMode.HARDWARE -> context.getString(R.string.settings_decoder_hardware)+ DecoderMode.SOFTWARE -> context.getString(R.string.settings_decoder_software)+ }+}++internal fun formatTimeoutSecondsLabel(seconds: Int, context: android.content.Context): String {+ return context.resources.getQuantityString(+ R.plurals.settings_timeout_seconds,+ seconds,+ seconds+ )+}++internal fun formatSubtitleSizeLabel(scale: Float, context: android.content.Context): String {+ return subtitleSizeOptions().firstOrNull { it.scale == scale }?.label?.invoke(context)+ ?: context.getString(R.string.settings_subtitle_size_default)+}++internal fun formatSubtitleColorLabel(colorArgb: Int, options: List<SubtitleColorOption>): String {+ return options.firstOrNull { it.colorArgb == colorArgb }?.label ?: options.first().label+}++internal fun formatQualityCapLabel(maxHeight: Int?, autoLabel: String): String {+ return maxHeight?.let { "${it}p" } ?: autoLabel+}++internal fun formatSpeedTestValueLabel(speedTest: InternetSpeedTestUiModel): String {+ return String.format(Locale.getDefault(), "%.1f Mbps", speedTest.megabitsPerSecond)+}++internal fun formatSpeedTestSummary(+ speedTest: InternetSpeedTestUiModel,+ context: android.content.Context+): String {+ val transportLabel = when (speedTest.transportLabel) {+ InternetSpeedTestTransport.WIFI.name -> context.getString(R.string.settings_speed_test_transport_wifi)+ InternetSpeedTestTransport.ETHERNET.name -> context.getString(R.string.settings_speed_test_transport_ethernet)+ InternetSpeedTestTransport.CELLULAR.name -> context.getString(R.string.settings_speed_test_transport_cellular)+ InternetSpeedTestTransport.OTHER.name -> context.getString(R.string.settings_speed_test_transport_other)+ else -> context.getString(R.string.settings_speed_test_transport_unknown)+ }+ val measuredAtLabel = formatTimestamp(speedTest.measuredAtMs)+ return if (speedTest.isEstimated) {+ context.getString(R.string.settings_speed_test_summary_estimated, transportLabel, measuredAtLabel)+ } else {+ context.getString(R.string.settings_speed_test_summary_measured, transportLabel, measuredAtLabel)+ }+}++internal fun sortModeLabel(mode: CategorySortMode, context: android.content.Context): String {+ return when (mode) {+ CategorySortMode.DEFAULT -> context.getString(R.string.settings_category_sort_default)+ CategorySortMode.TITLE_ASC -> context.getString(R.string.settings_category_sort_az)+ CategorySortMode.TITLE_DESC -> context.getString(R.string.settings_category_sort_za)+ CategorySortMode.COUNT_DESC -> context.getString(R.string.settings_category_sort_most_items)+ CategorySortMode.COUNT_ASC -> context.getString(R.string.settings_category_sort_least_items)+ }+}++internal fun formatCategorySortModeLabel(mode: CategorySortMode, context: android.content.Context): String {+ return sortModeLabel(mode, context)+}++internal fun categoryTypeLabel(type: ContentType, context: android.content.Context): String {+ return when (type) {+ ContentType.LIVE -> context.getString(R.string.settings_category_sort_live)+ ContentType.MOVIE -> context.getString(R.string.settings_category_sort_movies)+ ContentType.SERIES -> context.getString(R.string.settings_category_sort_series)+ ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_sort_series)+ }+}++internal fun categoryTypeDescription(type: ContentType, context: android.content.Context): String {+ return when (type) {+ ContentType.LIVE -> context.getString(R.string.settings_category_type_live_description)+ ContentType.MOVIE -> context.getString(R.string.settings_category_type_movies_description)+ ContentType.SERIES -> context.getString(R.string.settings_category_type_series_description)+ ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_type_series_description)+ }+}++internal fun LiveTvChannelMode.labelResId(): Int = when (this) {+ LiveTvChannelMode.COMFORTABLE -> R.string.settings_live_tv_mode_comfortable+ LiveTvChannelMode.COMPACT -> R.string.settings_live_tv_mode_compact+ LiveTvChannelMode.PRO -> R.string.settings_live_tv_mode_pro+}++internal fun LiveTvChannelMode.descriptionResId(): Int = when (this) {+ LiveTvChannelMode.COMFORTABLE -> R.string.settings_live_tv_mode_comfortable_desc+ LiveTvChannelMode.COMPACT -> R.string.settings_live_tv_mode_compact_desc+ LiveTvChannelMode.PRO -> R.string.settings_live_tv_mode_pro_desc+}++internal fun LiveTvQuickFilterVisibilityMode.labelResId(): Int = when (this) {+ LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide+ LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available+ LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always+}++internal fun LiveTvQuickFilterVisibilityMode.descriptionResId(): Int = when (this) {+ LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide_desc+ LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available_desc+ LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always_desc+}++internal fun VodViewMode.labelResId(): Int = when (this) {+ VodViewMode.MODERN -> R.string.settings_vod_view_mode_modern+ VodViewMode.CLASSIC -> R.string.settings_vod_view_mode_classic+}++internal fun VodViewMode.descriptionResId(): Int = when (this) {+ VodViewMode.MODERN -> R.string.settings_vod_view_mode_modern_desc+ VodViewMode.CLASSIC -> R.string.settings_vod_view_mode_classic_desc+}++internal fun ChannelNumberingMode.labelResId(): Int = when (this) {+ ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_group+ ChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider+}++internal fun ChannelNumberingMode.descriptionResId(): Int = when (this) {+ ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_group_desc+ ChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider_desc+}+diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.ktnew file mode 100644index 00000000..f6990692--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgActions.kt@@ -0,0 +1,142 @@+package com.streamvault.app.ui.screens.settings++import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.EpgSourceRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class SettingsEpgActions(+ private val epgSourceRepository: EpgSourceRepository,+ private val uiState: MutableStateFlow<SettingsUiState>+) {+ fun loadEpgSources(scope: CoroutineScope) {+ scope.launch {+ epgSourceRepository.getAllSources().collect { sources ->+ uiState.update { it.copy(epgSources = sources) }+ }+ }+ }++ fun loadEpgAssignments(scope: CoroutineScope, providerId: Long) {+ scope.launch {+ epgSourceRepository.getAssignmentsForProvider(providerId).collect { assignments ->+ val summary = epgSourceRepository.getResolutionSummary(providerId)+ uiState.update {+ it.copy(+ epgSourceAssignments = it.epgSourceAssignments + (providerId to assignments),+ epgResolutionSummaries = it.epgResolutionSummaries + (providerId to summary)+ )+ }+ }+ }+ }++ fun addEpgSource(scope: CoroutineScope, name: String, url: String) {+ scope.launch {+ val result = epgSourceRepository.addSource(name, url)+ if (result is Result.Error) {+ uiState.update { it.copy(userMessage = result.message) }+ }+ }+ }++ fun deleteEpgSource(scope: CoroutineScope, sourceId: Long) {+ scope.launch {+ val affectedProviders = loadedProvidersForSource(sourceId)+ epgSourceRepository.deleteSource(sourceId)+ refreshLoadedResolutionSummaries(affectedProviders)+ }+ }++ fun toggleEpgSourceEnabled(scope: CoroutineScope, sourceId: Long, enabled: Boolean) {+ scope.launch {+ val affectedProviders = loadedProvidersForSource(sourceId)+ epgSourceRepository.setSourceEnabled(sourceId, enabled)+ refreshLoadedResolutionSummaries(affectedProviders)+ }+ }++ fun refreshEpgSource(scope: CoroutineScope, sourceId: Long) {+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ val affectedProviders = loadedProvidersForSource(sourceId)+ val result = epgSourceRepository.refreshSource(sourceId)+ if (result !is Result.Error) {+ refreshLoadedResolutionSummaries(affectedProviders)+ }+ uiState.update {+ it.copy(+ isSyncing = false,+ userMessage = if (result is Result.Error) result.message else "EPG source refreshed"+ )+ }+ }+ }++ fun assignEpgSourceToProvider(scope: CoroutineScope, providerId: Long, epgSourceId: Long) {+ scope.launch {+ val existingAssignments = uiState.value.epgSourceAssignments[providerId].orEmpty()+ val nextPriority = (existingAssignments.maxOfOrNull { it.priority } ?: 0) + 1+ val result = epgSourceRepository.assignSourceToProvider(providerId, epgSourceId, nextPriority)+ if (result is Result.Error) {+ uiState.update { it.copy(userMessage = result.message) }+ } else {+ refreshProviderEpgSummary(providerId)+ }+ }+ }++ fun unassignEpgSourceFromProvider(scope: CoroutineScope, providerId: Long, epgSourceId: Long) {+ scope.launch {+ epgSourceRepository.unassignSourceFromProvider(providerId, epgSourceId)+ refreshProviderEpgSummary(providerId)+ }+ }++ fun moveEpgSourceAssignmentUp(scope: CoroutineScope, providerId: Long, epgSourceId: Long) {+ scope.launch {+ val assignments = uiState.value.epgSourceAssignments[providerId].orEmpty().sortedBy { it.priority }+ val index = assignments.indexOfFirst { it.epgSourceId == epgSourceId }+ if (index <= 0) return@launch+ val current = assignments[index]+ val previous = assignments[index - 1]+ epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, previous.priority)+ epgSourceRepository.updateAssignmentPriority(providerId, previous.epgSourceId, current.priority)+ refreshProviderEpgSummary(providerId)+ }+ }++ fun moveEpgSourceAssignmentDown(scope: CoroutineScope, providerId: Long, epgSourceId: Long) {+ scope.launch {+ val assignments = uiState.value.epgSourceAssignments[providerId].orEmpty().sortedBy { it.priority }+ val index = assignments.indexOfFirst { it.epgSourceId == epgSourceId }+ if (index == -1 || index >= assignments.lastIndex) return@launch+ val current = assignments[index]+ val next = assignments[index + 1]+ epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, next.priority)+ epgSourceRepository.updateAssignmentPriority(providerId, next.epgSourceId, current.priority)+ refreshProviderEpgSummary(providerId)+ }+ }++ private suspend fun refreshProviderEpgSummary(providerId: Long) {+ val summary = epgSourceRepository.getResolutionSummary(providerId)+ uiState.update {+ it.copy(epgResolutionSummaries = it.epgResolutionSummaries + (providerId to summary))+ }+ }++ private fun loadedProvidersForSource(sourceId: Long): List<Long> =+ uiState.value.epgSourceAssignments+ .filterValues { assignments -> assignments.any { it.epgSourceId == sourceId } }+ .keys+ .toList()++ private suspend fun refreshLoadedResolutionSummaries(providerIds: Iterable<Long>) {+ providerIds.asSequence().distinct().forEach { providerId ->+ refreshProviderEpgSummary(providerId)+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.ktnew file mode 100644index 00000000..971d1604--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsEpgSection.kt@@ -0,0 +1,336 @@+package com.streamvault.app.ui.screens.settings++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import androidx.compose.foundation.lazy.items+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary++internal fun LazyListScope.epgSourcesSection(+ uiState: SettingsUiState,+ viewModel: SettingsViewModel+) {+ val epgSources = uiState.epgSources+ val providers = uiState.providers++ item {+ Text(+ text = "EPG Sources",+ style = MaterialTheme.typography.titleMedium,+ color = Color(0xFF66BB6A),+ modifier = Modifier.padding(bottom = 8.dp)+ )+ Text(+ text = "Add external XMLTV EPG sources and assign them to providers. External sources are matched to channels by ID or name and override provider-native EPG data.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ modifier = Modifier.padding(bottom = 16.dp)+ )+ }++ item {+ AddEpgSourceCard(viewModel = viewModel)+ }++ if (epgSources.isEmpty()) {+ item {+ Text(+ text = "No external EPG sources configured. Add a source above to get started.",+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim,+ modifier = Modifier.padding(vertical = 16.dp)+ )+ }+ } else {+ items(epgSources, key = { it.id }) { source ->+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(12.dp))+ .background(Color.White.copy(alpha = 0.06f))+ ) {+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(modifier = Modifier.weight(1f)) {+ Text(source.name, style = MaterialTheme.typography.titleSmall, color = Color.White)+ Text(displayableEpgUrl(source.url), style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, maxLines = 1)+ if (source.lastError != null) {+ Text("Error: ${source.lastError}", style = MaterialTheme.typography.bodySmall, color = Color(0xFFEF5350))+ }+ if (source.lastSuccessAt != null) {+ val ago = (System.currentTimeMillis() - source.lastSuccessAt) / 60000+ Text("Last synced: ${ago}m ago", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ }+ }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ TvClickableSurface(+ onClick = { viewModel.toggleEpgSourceEnabled(source.id, !source.enabled) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.2f) else Color.White.copy(alpha = 0.08f),+ focusedContainerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.4f) else Color.White.copy(alpha = 0.15f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ if (source.enabled) "ON" else "OFF",+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),+ style = MaterialTheme.typography.labelSmall,+ color = if (source.enabled) Color(0xFF66BB6A) else OnSurfaceDim+ )+ }+ TvClickableSurface(+ onClick = { viewModel.refreshEpgSource(source.id) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.15f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Refresh", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Primary)+ }+ TvClickableSurface(+ onClick = { viewModel.deleteEpgSource(source.id) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),+ focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Delete", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))+ }+ }+ }+ }+ }+ }+ }++ if (providers.isNotEmpty() && epgSources.isNotEmpty()) {+ item {+ Text(+ text = "Provider Assignments",+ style = MaterialTheme.typography.titleMedium,+ color = Color(0xFF66BB6A),+ modifier = Modifier.padding(top = 24.dp, bottom = 8.dp)+ )+ Text(+ text = "Assign EPG sources to providers. Channels will be matched automatically by ID or name.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ modifier = Modifier.padding(bottom = 8.dp)+ )+ }+ items(providers, key = { it.id }) { provider ->+ val assignments = uiState.epgSourceAssignments[provider.id].orEmpty()+ val resolutionSummary = uiState.epgResolutionSummaries[provider.id]+ val assignedSourceIds = assignments.map { it.epgSourceId }.toSet()+ val unassignedSources = epgSources.filter { it.id !in assignedSourceIds }++ LaunchedEffect(provider.id) {+ viewModel.loadEpgAssignments(provider.id)+ }++ Box(+ modifier = Modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(12.dp))+ .background(Color.White.copy(alpha = 0.06f))+ ) {+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(provider.name, style = MaterialTheme.typography.titleSmall, color = Color.White)+ if (resolutionSummary != null) {+ val matchedChannels = (resolutionSummary.totalChannels - resolutionSummary.unresolvedChannels).coerceAtLeast(0)+ Text(+ text = "Matched $matchedChannels/${resolutionSummary.totalChannels} channels - ${resolutionSummary.exactIdMatches} exact - ${resolutionSummary.normalizedNameMatches} name - ${resolutionSummary.providerNativeMatches} provider",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }++ if (assignments.isEmpty()) {+ Text("No EPG sources assigned", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ } else {+ assignments.sortedBy { it.priority }.forEachIndexed { assignmentIndex, assignment ->+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Text(+ "${assignment.epgSourceName} (priority: ${assignment.priority})",+ style = MaterialTheme.typography.bodySmall,+ color = Color.White,+ modifier = Modifier.weight(1f)+ )+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {+ TvClickableSurface(+ onClick = { viewModel.moveEpgSourceAssignmentUp(provider.id, assignment.epgSourceId) },+ enabled = assignmentIndex > 0,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.16f),+ disabledContainerColor = Color.White.copy(alpha = 0.04f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Up", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)+ }+ TvClickableSurface(+ onClick = { viewModel.moveEpgSourceAssignmentDown(provider.id, assignment.epgSourceId) },+ enabled = assignmentIndex < assignments.lastIndex,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.16f),+ disabledContainerColor = Color.White.copy(alpha = 0.04f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Down", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)+ }+ }+ Spacer(modifier = Modifier.width(6.dp))+ TvClickableSurface(+ onClick = { viewModel.unassignEpgSourceFromProvider(provider.id, assignment.epgSourceId) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),+ focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Remove", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))+ }+ }+ }+ }++ if (unassignedSources.isNotEmpty()) {+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ unassignedSources.forEach { source ->+ TvClickableSurface(+ onClick = { viewModel.assignEpgSourceToProvider(provider.id, source.id) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFF66BB6A).copy(alpha = 0.12f),+ focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.25f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("+ ${source.name}", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFF66BB6A))+ }+ }+ }+ }+ }+ }+ }+ }+}++@Composable+private fun AddEpgSourceCard(viewModel: SettingsViewModel) {+ var newName by remember { mutableStateOf("") }+ var newUrl by remember { mutableStateOf("") }+ val context = LocalContext.current+ val filePickerLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.OpenDocument()+ ) { uri ->+ if (uri != null) {+ try {+ context.contentResolver.takePersistableUriPermission(+ uri,+ android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION+ )+ } catch (_: SecurityException) {+ }+ newUrl = uri.toString()+ }+ }++ Box(+ modifier = Modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(12.dp))+ .background(Color.White.copy(alpha = 0.06f))+ ) {+ Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text("Add EPG Source", style = MaterialTheme.typography.titleSmall, color = Color.White)+ EpgSourceTextField(value = newName, onValueChange = { newName = it }, placeholder = "Source name")+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(modifier = Modifier.weight(1f)) {+ EpgSourceTextField(+ value = newUrl,+ onValueChange = { newUrl = it },+ placeholder = "XMLTV URL (HTTPS) or browse file"+ )+ }+ TvClickableSurface(+ onClick = { filePickerLauncher.launch(arrayOf("*/*")) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.15f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Browse", modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), style = MaterialTheme.typography.labelMedium, color = Primary)+ }+ }+ TvClickableSurface(+ onClick = {+ if (newName.isNotBlank() && newUrl.isNotBlank()) {+ viewModel.addEpgSource(newName.trim(), newUrl.trim())+ newName = ""+ newUrl = ""+ }+ },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color(0xFF66BB6A).copy(alpha = 0.2f),+ focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.4f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text("Add Source", modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = Color(0xFF66BB6A), fontWeight = FontWeight.Medium)+ }+ }+ }+}++private fun displayableEpgUrl(url: String): String = when {+ url.startsWith("content://") -> {+ val lastSegment = try { android.net.Uri.parse(url).lastPathSegment } catch (_: Exception) { null }+ val decoded = lastSegment?.let { android.net.Uri.decode(it) }?.substringAfterLast("/")?.substringAfterLast("\\")+ if (!decoded.isNullOrBlank() && decoded.length < 60) "local: $decoded" else "local file"+ }+ else -> url+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.ktnew file mode 100644index 00000000..a408ec1e--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderActions.kt@@ -0,0 +1,189 @@+package com.streamvault.app.ui.screens.settings++import com.streamvault.app.tvinput.TvInputChannelSyncManager+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.CombinedM3uRepository+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.SyncMetadataRepository+import com.streamvault.domain.usecase.SyncProvider+import com.streamvault.domain.usecase.SyncProviderCommand+import com.streamvault.domain.usecase.SyncProviderResult+import com.streamvault.data.preferences.PreferencesRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class SettingsProviderActions(+ private val providerRepository: ProviderRepository,+ private val combinedM3uRepository: CombinedM3uRepository,+ private val preferencesRepository: PreferencesRepository,+ private val syncProvider: SyncProvider,+ private val tvInputChannelSyncManager: TvInputChannelSyncManager,+ private val uiState: MutableStateFlow<SettingsUiState>+) {+ fun setActiveProvider(scope: CoroutineScope, providerId: Long) {+ scope.launch {+ preferencesRepository.setLastActiveProviderId(providerId)+ combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.ProviderSource(providerId))+ providerRepository.setActiveProvider(providerId)+ refreshProvider(scope, providerId)+ }+ }++ fun setActiveCombinedProfile(scope: CoroutineScope, profileId: Long) {+ scope.launch {+ when (combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(profileId))) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Combined M3U source activated") }+ is Result.Error -> uiState.update { it.copy(userMessage = "Could not activate combined source") }+ Result.Loading -> Unit+ }+ }+ }++ fun createCombinedProfile(scope: CoroutineScope, name: String, providerIds: List<Long>) {+ scope.launch {+ when (val result = combinedM3uRepository.createProfile(name, providerIds)) {+ is Result.Success -> {+ combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(result.data.id))+ uiState.update { it.copy(userMessage = "Combined M3U source created") }+ }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun deleteCombinedProfile(scope: CoroutineScope, profileId: Long) {+ scope.launch {+ when (val result = combinedM3uRepository.deleteProfile(profileId)) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Combined M3U source deleted") }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun addProviderToCombinedProfile(scope: CoroutineScope, profileId: Long, providerId: Long) {+ scope.launch {+ when (val result = combinedM3uRepository.addProvider(profileId, providerId)) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Playlist added to combined source") }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun renameCombinedProfile(scope: CoroutineScope, profileId: Long, name: String) {+ scope.launch {+ when (val result = combinedM3uRepository.updateProfileName(profileId, name)) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Combined M3U source renamed") }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun removeProviderFromCombinedProfile(scope: CoroutineScope, profileId: Long, providerId: Long) {+ scope.launch {+ when (val result = combinedM3uRepository.removeProvider(profileId, providerId)) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Playlist removed from combined source") }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun moveCombinedProvider(scope: CoroutineScope, profileId: Long, providerId: Long, moveUp: Boolean) {+ scope.launch {+ val profile = uiState.value.combinedProfiles.firstOrNull { it.id == profileId } ?: return@launch+ val orderedProviderIds = profile.members.sortedBy { it.priority }.map { it.providerId }.toMutableList()+ val currentIndex = orderedProviderIds.indexOf(providerId)+ if (currentIndex == -1) return@launch+ val targetIndex = if (moveUp) currentIndex - 1 else currentIndex + 1+ if (targetIndex !in orderedProviderIds.indices) return@launch+ java.util.Collections.swap(orderedProviderIds, currentIndex, targetIndex)+ when (val result = combinedM3uRepository.reorderMembers(profileId, orderedProviderIds)) {+ is Result.Success -> uiState.update { it.copy(userMessage = "Combined playlist order updated") }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun setCombinedProviderEnabled(scope: CoroutineScope, profileId: Long, providerId: Long, enabled: Boolean) {+ scope.launch {+ when (val result = combinedM3uRepository.setMemberEnabled(profileId, providerId, enabled)) {+ is Result.Success -> uiState.update {+ it.copy(userMessage = if (enabled) "Playlist enabled in combined source" else "Playlist disabled in combined source")+ }+ is Result.Error -> uiState.update { it.copy(userMessage = result.message) }+ Result.Loading -> Unit+ }+ }+ }++ fun setM3uVodClassificationEnabled(scope: CoroutineScope, providerId: Long, enabled: Boolean) {+ scope.launch {+ val provider = providerRepository.getProvider(providerId) ?: return@launch+ if (provider.type != ProviderType.M3U) return@launch+ when (val result = providerRepository.updateProvider(provider.copy(m3uVodClassificationEnabled = enabled))) {+ is Result.Error -> uiState.update { it.copy(userMessage = "Could not save provider setting: ${result.message}") }+ else -> uiState.update {+ it.copy(+ userMessage = if (enabled) {+ "M3U VOD classification enabled. Refresh the playlist to reclassify content."+ } else {+ "M3U VOD classification disabled. Refresh the playlist to reclassify content."+ }+ )+ }+ }+ }+ }++ fun refreshProvider(scope: CoroutineScope, providerId: Long, movieFastSyncOverride: Boolean? = null) {+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ try {+ val result = syncProvider(+ SyncProviderCommand(+ providerId = providerId,+ force = true,+ movieFastSyncOverride = movieFastSyncOverride+ )+ )+ if (result !is SyncProviderResult.Error) {+ tvInputChannelSyncManager.refreshTvInputCatalog()+ }+ uiState.update { state ->+ val partialWarnings = (result as? SyncProviderResult.Success)?.warnings.orEmpty()+ val warningsMessage = partialWarnings.take(3).joinToString(separator = ", ").ifBlank { "Some sections are incomplete." }+ state.copy(+ isSyncing = false,+ userMessage = when {+ result is SyncProviderResult.Error -> "Refresh failed: ${result.message}"+ (result as? SyncProviderResult.Success)?.isPartial == true -> "Refresh completed with warnings: $warningsMessage"+ else -> "Provider refreshed successfully"+ },+ syncWarningsByProvider = when {+ result is SyncProviderResult.Error -> state.syncWarningsByProvider - providerId+ (result as? SyncProviderResult.Success)?.isPartial == true -> state.syncWarningsByProvider + (providerId to partialWarnings)+ else -> state.syncWarningsByProvider - providerId+ }+ )+ }+ } catch (e: Exception) {+ uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }+ }+ }+ }++ fun deleteProvider(scope: CoroutineScope, providerId: Long) {+ scope.launch {+ providerRepository.deleteProvider(providerId)+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.ktnew file mode 100644index 00000000..d46c7b9e--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt@@ -0,0 +1,1461 @@+package com.streamvault.app.ui.screens.settings++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequester+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Checkbox+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.RadioButton+import androidx.compose.material3.Switch+import androidx.compose.runtime.*+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusProperties+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.unit.dp+import androidx.tv.material3.*+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.design.FocusSpec+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.CombinedM3uProfile+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderStatus+import com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.launch+import java.util.Locale++@Composable+internal fun CombinedM3uProfilesCard(+ profiles: List<CombinedM3uProfile>,+ availableProviders: List<Provider>,+ selectedProfileId: Long?,+ activeLiveSource: ActiveLiveSource?,+ onSelectProfile: (Long) -> Unit,+ onCreateProfile: () -> Unit,+ onActivateProfile: (Long) -> Unit,+ onDeleteProfile: (Long) -> Unit,+ onRenameProfile: (Long) -> Unit,+ onAddProvider: (Long) -> Unit,+ onRemoveProvider: (Long, Long) -> Unit,+ onToggleProviderEnabled: (Long, Long, Boolean) -> Unit,+ onMoveProvider: (Long, Long, Boolean) -> Unit+) {+ Surface(+ shape = RoundedCornerShape(12.dp),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ modifier = Modifier.fillMaxWidth()+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text("Combined M3U", style = MaterialTheme.typography.titleMedium, color = OnSurface)+ Text(+ "Merge selected M3U playlists into one Live TV and EPG source.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ CompactSettingsActionChip(+ label = "Create Combined",+ accent = Primary,+ onClick = onCreateProfile+ )+ }++ if (profiles.isEmpty()) {+ Text("No combined M3U sources yet.", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ } else {+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ items(profiles, key = { it.id }) { profile ->+ val isActive = (activeLiveSource as? ActiveLiveSource.CombinedM3uSource)?.profileId == profile.id+ ProviderChip(+ title = profile.name,+ subtitle = buildString {+ append("${profile.members.count { it.enabled }}/${profile.members.size} playlist(s)")+ if (isActive) append(" • Active")+ if (profile.members.none { it.enabled }) append(" • Empty")+ },+ isSelected = selectedProfileId == profile.id,+ isActive = isActive,+ onClick = { onSelectProfile(profile.id) }+ )+ }+ }++ val selectedProfile = profiles.firstOrNull { it.id == selectedProfileId } ?: profiles.first()+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ CompactSettingsActionChip(+ label = "Use For Live TV",+ accent = Primary,+ onClick = { onActivateProfile(selectedProfile.id) }+ )+ CompactSettingsActionChip(+ label = "Rename",+ accent = OnBackground,+ onClick = { onRenameProfile(selectedProfile.id) }+ )+ CompactSettingsActionChip(+ label = "Add Playlist",+ accent = OnBackground,+ onClick = { onAddProvider(selectedProfile.id) }+ )+ CompactSettingsActionChip(+ label = "Delete",+ accent = ErrorColor,+ onClick = { onDeleteProfile(selectedProfile.id) }+ )+ }++ Text(+ text = "${selectedProfile.members.count { it.enabled }} of ${selectedProfile.members.size} playlists enabled",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )++ if (selectedProfile.members.isEmpty()) {+ Text(+ text = "This combined source has no playlists yet. Add at least one M3U playlist before using it.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ } else if (selectedProfile.members.none { it.enabled }) {+ Text(+ text = "All playlists in this combined source are disabled. Enable at least one to use it in Live TV.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }++ selectedProfile.members+ .sortedBy { it.priority }+ .forEachIndexed { index, member ->+ val providerName = member.providerName.ifBlank {+ availableProviders.firstOrNull { it.id == member.providerId }?.name ?: "Playlist ${member.providerId}"+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(providerName, style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(+ if (member.enabled) "Enabled in merged source" else "Disabled in merged source",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {+ CompactSettingsActionChip(+ label = "Up",+ accent = OnBackground,+ enabled = index > 0,+ onClick = { onMoveProvider(selectedProfile.id, member.providerId, true) }+ )+ CompactSettingsActionChip(+ label = "Down",+ accent = OnBackground,+ enabled = index < selectedProfile.members.lastIndex,+ onClick = { onMoveProvider(selectedProfile.id, member.providerId, false) }+ )+ Switch(+ checked = member.enabled,+ onCheckedChange = { onToggleProviderEnabled(selectedProfile.id, member.providerId, it) }+ )+ CompactSettingsActionChip(+ label = "Remove",+ accent = ErrorColor,+ onClick = { onRemoveProvider(selectedProfile.id, member.providerId) }+ )+ }+ }+ }+ }+ }+ }+ }+}++@Composable+internal fun RenameCombinedM3uDialog(+ profile: CombinedM3uProfile,+ onDismiss: () -> Unit,+ onRename: (String) -> Unit+) {+ var name by rememberSaveable(profile.id) { mutableStateOf(profile.name) }++ PremiumDialog(+ title = "Rename Combined M3U",+ subtitle = "Update the name shown in Live TV and provider settings.",+ onDismissRequest = onDismiss,+ widthFraction = 0.48f,+ content = {+ EpgSourceTextField(+ value = name,+ onValueChange = { updated -> name = updated },+ placeholder = "Combined source name"+ )+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = "Save",+ onClick = { onRename(name.trim()) },+ enabled = name.isNotBlank(),+ emphasized = true+ )+ }+ )+}++@Composable+internal fun CreateCombinedM3uDialog(+ providers: List<Provider>,+ onDismiss: () -> Unit,+ onCreate: (String, List<Long>) -> Unit+) {+ var name by rememberSaveable { mutableStateOf("") }+ var selectedProviderIds by rememberSaveable { mutableStateOf(setOf<Long>()) }+ val m3uProviders = remember(providers) { providers.filter { it.type == ProviderType.M3U } }+ val effectiveName = remember(name, selectedProviderIds, m3uProviders) {+ val manualName = name.trim()+ if (manualName.isNotBlank()) {+ manualName+ } else {+ val selectedProviders = m3uProviders.filter { it.id in selectedProviderIds }+ when {+ selectedProviders.isEmpty() -> ""+ selectedProviders.size == 1 -> "${selectedProviders.first().name} Mix"+ selectedProviders.size == 2 -> "${selectedProviders[0].name} + ${selectedProviders[1].name}"+ else -> "${selectedProviders.first().name} + ${selectedProviders.size - 1} More"+ }+ }+ }++ PremiumDialog(+ title = "Create Combined M3U",+ subtitle = "Pick the M3U playlists you want to browse together in Live TV and guide.",+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ EpgSourceTextField(+ value = name,+ onValueChange = { updated -> name = updated },+ placeholder = effectiveName.ifBlank { "Combined source name" }+ )++ if (m3uProviders.isEmpty()) {+ Text(+ text = "No M3U playlists are available yet. Add at least one playlist first.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ } else {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(max = 360.dp)+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ m3uProviders.forEach { provider ->+ val isSelected = provider.id in selectedProviderIds+ TvClickableSurface(+ onClick = {+ selectedProviderIds = if (isSelected) {+ selectedProviderIds - provider.id+ } else {+ selectedProviderIds + provider.id+ }+ },+ modifier = Modifier.fillMaxWidth(),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.04f),+ focusedContainerColor = Primary.copy(alpha = 0.24f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 14.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = provider.name,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ Text(+ text = if (isSelected) "Included in this combined source" else "Press to include this playlist",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Checkbox(+ checked = isSelected,+ onCheckedChange = null+ )+ }+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = "Create",+ onClick = { onCreate(effectiveName, selectedProviderIds.toList()) },+ enabled = selectedProviderIds.isNotEmpty() && effectiveName.isNotBlank(),+ emphasized = true+ )+ }+ )+}++@Composable+internal fun AddCombinedProviderDialog(+ profile: CombinedM3uProfile,+ availableProviders: List<Provider>,+ onDismiss: () -> Unit,+ onAddProvider: (Long) -> Unit+) {+ val candidateProviders = remember(profile, availableProviders) {+ availableProviders.filter { provider -> profile.members.none { it.providerId == provider.id } }+ }+ var selectedProviderId by rememberSaveable(profile.id) { mutableStateOf(candidateProviders.firstOrNull()?.id) }+ PremiumDialog(+ title = "Add Playlist To ${profile.name}",+ subtitle = "Select another M3U playlist to include in this combined source.",+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ content = {+ if (candidateProviders.isEmpty()) {+ Text(+ text = "All M3U playlists are already in this combined source.",+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ } else {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(max = 320.dp)+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ candidateProviders.forEach { provider ->+ val isSelected = selectedProviderId == provider.id+ TvClickableSurface(+ onClick = { selectedProviderId = provider.id },+ modifier = Modifier.fillMaxWidth(),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.04f),+ focusedContainerColor = Primary.copy(alpha = 0.22f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(+ 1.dp,+ if (isSelected) Primary.copy(alpha = 0.4f) else Color.White.copy(alpha = 0.08f)+ ),+ shape = RoundedCornerShape(12.dp)+ ),+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(12.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 14.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = provider.name,+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface,+ modifier = Modifier.weight(1f)+ )+ RadioButton(+ selected = isSelected,+ onClick = { selectedProviderId = provider.id }+ )+ }+ }+ }+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = "Add",+ onClick = { selectedProviderId?.let(onAddProvider) },+ enabled = selectedProviderId != null && candidateProviders.isNotEmpty(),+ emphasized = true+ )+ }+ )+}++@Composable+private fun ProviderChip(+ title: String,+ subtitle: String,+ isSelected: Boolean,+ isActive: Boolean,+ onClick: () -> Unit+) {+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.24f)+ )+ ) {+ Column(modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp)) {+ Text(title, style = MaterialTheme.typography.bodyMedium, color = OnSurface)+ Text(+ if (isActive) "$subtitle • Active" else subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = if (isActive) Primary else OnSurfaceDim+ )+ }+ }+}++private fun availableSyncSelections(provider: Provider): List<ProviderSyncSelection> = buildList {+ add(ProviderSyncSelection.TV)+ add(ProviderSyncSelection.MOVIES)+ if (provider.type == ProviderType.XTREAM_CODES) {+ add(ProviderSyncSelection.SERIES)+ }+ add(ProviderSyncSelection.EPG)+}++@Composable+internal fun ProviderSyncOptionsDialog(+ provider: Provider,+ onDismiss: () -> Unit,+ onSelect: (ProviderSyncSelection?) -> Unit+) {+ PremiumDialog(+ onDismissRequest = onDismiss,+ title = stringResource(R.string.settings_sync_dialog_title, provider.name),+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(+ text = stringResource(R.string.settings_sync_dialog_subtitle),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ SyncOptionButton(stringResource(R.string.settings_sync_option_all)) {+ onSelect(ProviderSyncSelection.ALL)+ }+ availableSyncSelections(provider).forEach { option ->+ SyncOptionButton(text = syncSelectionLabel(option)) {+ onSelect(option)+ }+ }+ OutlinedButton(+ onClick = { onSelect(null) },+ modifier = Modifier.fillMaxWidth()+ ) {+ Text(stringResource(R.string.settings_sync_option_custom))+ }+ }+ }+ )+}++@Composable+internal fun ProviderCustomSyncDialog(+ provider: Provider,+ selected: Set<ProviderSyncSelection>,+ onToggle: (ProviderSyncSelection) -> Unit,+ onDismiss: () -> Unit,+ onConfirm: () -> Unit+) {+ PremiumDialog(+ onDismissRequest = onDismiss,+ title = stringResource(R.string.settings_sync_custom_title, provider.name),+ content = {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(+ text = stringResource(R.string.settings_sync_custom_subtitle),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ availableSyncSelections(provider).forEach { option ->+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .clickable { onToggle(option) }+ .padding(vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Checkbox(+ checked = option in selected,+ onCheckedChange = { onToggle(option) }+ )+ Text(+ text = syncSelectionLabel(option),+ style = MaterialTheme.typography.bodyLarge,+ color = OnBackground+ )+ }+ }+ }+ },+ footer = {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)+ ) {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_sync_btn),+ onClick = onConfirm,+ enabled = selected.isNotEmpty()+ )+ }+ }+ )+}++@Composable+private fun SyncOptionButton(+ text: String,+ onClick: () -> Unit+) {+ TvButton(+ onClick = onClick,+ modifier = Modifier.fillMaxWidth()+ ) {+ Text(text)+ }+}++@Composable+private fun syncSelectionLabel(selection: ProviderSyncSelection): String = when (selection) {+ ProviderSyncSelection.ALL -> stringResource(R.string.settings_sync_option_all)+ ProviderSyncSelection.FAST -> stringResource(R.string.settings_sync_option_fast)+ ProviderSyncSelection.TV -> stringResource(R.string.settings_sync_option_tv)+ ProviderSyncSelection.MOVIES -> stringResource(R.string.settings_sync_option_movies)+ ProviderSyncSelection.SERIES -> stringResource(R.string.settings_sync_option_series)+ ProviderSyncSelection.EPG -> stringResource(R.string.settings_sync_option_epg)+}++@Composable+internal fun ProviderSettingsCard(+ provider: Provider,+ isActive: Boolean,+ isSyncing: Boolean,+ diagnostics: ProviderDiagnosticsUiModel?,+ syncWarnings: List<String>,+ onRetryWarningAction: (ProviderWarningAction) -> Unit,+ onConnect: () -> Unit,+ onRefresh: () -> Unit,+ onDelete: () -> Unit,+ onEdit: () -> Unit,+ onParentalControl: () -> Unit,+ onToggleM3uVodClassification: (Boolean) -> Unit,+ onRefreshM3uClassification: () -> Unit+) {+ val context = androidx.compose.ui.platform.LocalContext.current+ // Use Column layout - provider info + buttons below as separate focusable items+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(+ color = if (isActive) SurfaceHighlight else SurfaceElevated,+ shape = RoundedCornerShape(8.dp)+ )+ .border(+ width = if (isActive) 2.dp else 0.dp,+ color = if (isActive) Primary else Color.Transparent,+ shape = RoundedCornerShape(8.dp)+ )+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ // Provider info+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column {+ Text(+ text = provider.name,+ style = MaterialTheme.typography.bodyLarge,+ color = OnBackground+ )+ Text(+ text = provider.type.name,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ }+ ProviderStatusBadge(status = provider.status)+ if (isActive) {+ Text(+ text = stringResource(R.string.settings_active),+ style = MaterialTheme.typography.labelSmall,+ color = Primary,+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,+ modifier = Modifier+ .background(Primary.copy(alpha = 0.1f), RoundedCornerShape(4.dp))+ .padding(horizontal = 8.dp, vertical = 4.dp)+ )+ }+ }++ // Expiration Date+ val expDate = provider.expirationDate+ val expirationText = remember(expDate) {+ when (expDate) {+ null -> context.getString(R.string.settings_expiration_unknown)+ Long.MAX_VALUE -> context.getString(R.string.settings_expiration_never)+ else -> context.getString(R.string.settings_expires, java.text.SimpleDateFormat("d MMM yyyy", java.util.Locale.getDefault()).format(java.util.Date(expDate)))+ }+ }+ Text(+ text = expirationText,+ style = MaterialTheme.typography.bodySmall,+ color = if (expDate != null && expDate < System.currentTimeMillis() && expDate != Long.MAX_VALUE) ErrorColor else OnSurfaceDim+ )++ diagnostics?.let { model ->+ Text(+ text = listOf(model.sourceLabel, model.connectionSummary, model.expirySummary)+ .filter { it.isNotBlank() }+ .joinToString(" • "),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_live), count = model.liveCount)+ ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_movies), count = model.movieCount)+ if (provider.type == ProviderType.XTREAM_CODES) {+ ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_series), count = model.seriesCount)+ }+ ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_epg), count = model.epgCount)+ }++ ProviderDiagnosticsPanel(+ provider = provider,+ diagnostics = model+ )+ }++ if (provider.type == ProviderType.M3U) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(10.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(10.dp))+ .padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = stringResource(R.string.settings_m3u_vod_classification_title),+ style = MaterialTheme.typography.titleSmall,+ color = OnBackground+ )+ Text(+ text = stringResource(R.string.settings_m3u_vod_classification_summary),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Switch(+ checked = provider.m3uVodClassificationEnabled,+ onCheckedChange = onToggleM3uVodClassification+ )+ }+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ TvClickableSurface(+ onClick = onRefreshM3uClassification,+ enabled = !isSyncing,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.15f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = stringResource(R.string.settings_m3u_vod_classification_refresh),+ style = MaterialTheme.typography.labelMedium,+ color = Primary,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ }+ }+ }++ if (syncWarnings.isNotEmpty()) {+ val hasEpgWarning = syncWarnings.any { it.contains("EPG", ignoreCase = true) }+ val hasMoviesWarning = syncWarnings.any { it.contains("Movies", ignoreCase = true) }+ val hasSeriesWarning = syncWarnings.any { it.contains("Series", ignoreCase = true) }++ Text(+ text = stringResource(R.string.settings_provider_warnings, syncWarnings.take(3).joinToString(", ")),+ style = MaterialTheme.typography.bodySmall,+ color = Secondary+ )++ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (hasEpgWarning) {+ TvClickableSurface(+ onClick = { onRetryWarningAction(ProviderWarningAction.EPG) },+ enabled = !isSyncing,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.35f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_retry_epg),+ style = MaterialTheme.typography.labelSmall,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)+ )+ }+ }+ if (hasMoviesWarning) {+ TvClickableSurface(+ onClick = { onRetryWarningAction(ProviderWarningAction.MOVIES) },+ enabled = !isSyncing,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.35f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_retry_movies),+ style = MaterialTheme.typography.labelSmall,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)+ )+ }+ }+ if (hasSeriesWarning && provider.type == ProviderType.XTREAM_CODES) {+ TvClickableSurface(+ onClick = { onRetryWarningAction(ProviderWarningAction.SERIES) },+ enabled = !isSyncing,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.35f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_retry_series),+ style = MaterialTheme.typography.labelSmall,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)+ )+ }+ }+ }+ }++ // Action buttons - each independently focusable for d-pad+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ if (!isActive) {+ TvClickableSurface(+ onClick = onConnect,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary,+ focusedContainerColor = Primary.copy(alpha = 0.8f),+ contentColor = Color.White+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(6.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = stringResource(R.string.settings_connect),+ style = MaterialTheme.typography.labelMedium,+ color = Color.White,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ } else {+ TvClickableSurface(+ onClick = onRefresh,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.2f),+ focusedContainerColor = Primary.copy(alpha = 0.5f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(6.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = if (isSyncing) stringResource(R.string.settings_syncing_btn) else stringResource(R.string.settings_sync_btn),+ style = MaterialTheme.typography.labelMedium,+ color = Primary,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ }++ TvClickableSurface(+ onClick = onEdit,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.2f),+ focusedContainerColor = Secondary.copy(alpha = 0.5f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(6.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = stringResource(R.string.settings_edit),+ style = MaterialTheme.typography.labelMedium,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }++ TvClickableSurface(+ onClick = onDelete,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = ErrorColor.copy(alpha = 0.2f),+ focusedContainerColor = ErrorColor.copy(alpha = 0.5f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(6.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = stringResource(R.string.settings_delete),+ style = MaterialTheme.typography.labelMedium,+ color = ErrorColor,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }++ if (isActive) {+ TvClickableSurface(+ onClick = onParentalControl,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.15f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(6.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = stringResource(R.string.settings_provider_category_controls_action),+ style = MaterialTheme.typography.labelMedium,+ color = Primary,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+ }+ }++ }+}++@Composable+internal fun ProviderSelectorTab(+ provider: Provider,+ isSelected: Boolean,+ isActive: Boolean,+ onClick: () -> Unit+) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = onClick,+ modifier = Modifier+ .focusRequester(focusRequester)+ .mouseClickable(+ focusRequester = focusRequester,+ onClick = onClick+ ),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.34f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = androidx.compose.foundation.BorderStroke(+ width = 1.dp,+ color = if (isSelected) Primary.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.08f)+ )+ ),+ focusedBorder = Border(+ border = androidx.compose.foundation.BorderStroke(+ width = 2.dp,+ color = Primary+ )+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = provider.name,+ style = MaterialTheme.typography.labelLarge,+ color = OnBackground,+ fontWeight = FontWeight.Bold,+ maxLines = 1+ )+ Text(+ text = provider.type.name,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ }+ if (isActive) {+ Text(+ text = stringResource(R.string.settings_active),+ style = MaterialTheme.typography.labelSmall,+ color = Primary,+ fontWeight = FontWeight.Bold+ )+ }+ }+ }+}++@Composable+private fun ProviderCompactStat(+ title: String,+ count: Int+) {+ Surface(+ shape = RoundedCornerShape(10.dp),+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Text(+ text = count.toString(),+ style = MaterialTheme.typography.labelMedium,+ color = OnBackground+ )+ }+ }+}++@Composable+private fun ProviderStatusBadge(status: ProviderStatus) {+ val (label, color) = when (status) {+ ProviderStatus.ACTIVE -> stringResource(R.string.settings_status_active) to Primary+ ProviderStatus.PARTIAL -> stringResource(R.string.settings_status_partial) to Secondary+ ProviderStatus.ERROR -> stringResource(R.string.settings_status_error) to ErrorColor+ ProviderStatus.EXPIRED -> stringResource(R.string.settings_status_expired) to ErrorColor+ ProviderStatus.DISABLED -> stringResource(R.string.settings_status_disabled) to OnSurfaceDim+ ProviderStatus.UNKNOWN -> stringResource(R.string.settings_status_unknown) to OnSurfaceDim+ }++ Text(+ text = label,+ style = MaterialTheme.typography.labelSmall,+ color = color,+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,+ modifier = Modifier+ .background(color.copy(alpha = 0.16f), RoundedCornerShape(4.dp))+ .padding(horizontal = 8.dp, vertical = 4.dp)+ )+}++@Composable+internal fun SettingsOverviewCard(+ activeProviderName: String,+ providerCount: Int,+ protectionSummary: String,+ languageLabel: String+) {+ Surface(+ modifier = Modifier.fillMaxWidth(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier.padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ Text(+ text = stringResource(R.string.settings_overview_title),+ style = MaterialTheme.typography.titleLarge,+ color = OnBackground+ )+ Text(+ text = stringResource(R.string.settings_overview_subtitle),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurfaceDim+ )+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ SettingsOverviewStat(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_overview_provider_label),+ value = activeProviderName+ )+ SettingsOverviewStat(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_overview_count_label),+ value = providerCount.toString()+ )+ SettingsOverviewStat(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_overview_protection_label),+ value = protectionSummary+ )+ SettingsOverviewStat(+ modifier = Modifier.weight(1f),+ label = stringResource(R.string.settings_overview_language_label),+ value = languageLabel+ )+ }+ }++ }+}++@Composable+private fun ProviderDiagnosticsPanel(+ provider: Provider,+ diagnostics: ProviderDiagnosticsUiModel+) {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(+ text = stringResource(R.string.settings_provider_diagnostics_title),+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )+ Text(+ text = diagnostics.capabilitySummary,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Text(+ text = stringResource(R.string.diagnostics_summary_format, diagnostics.sourceLabel, diagnostics.connectionSummary),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ Text(+ text = diagnostics.expirySummary,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )+ Text(+ text = diagnostics.archiveSummary,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ ProviderDiagnosticPill(+ title = stringResource(R.string.settings_diagnostic_live),+ count = diagnostics.liveCount,+ timestamp = diagnostics.lastLiveSync+ )+ ProviderDiagnosticPill(+ title = stringResource(R.string.settings_diagnostic_movies),+ count = diagnostics.movieCount,+ timestamp = diagnostics.lastMovieSync+ )+ if (provider.type == ProviderType.XTREAM_CODES) {+ ProviderDiagnosticPill(+ title = stringResource(R.string.settings_diagnostic_series),+ count = diagnostics.seriesCount,+ timestamp = diagnostics.lastSeriesSync+ )+ }+ ProviderDiagnosticPill(+ title = stringResource(R.string.settings_diagnostic_epg),+ count = diagnostics.epgCount,+ timestamp = diagnostics.lastEpgSync+ )+ }+ Text(+ text = stringResource(R.string.settings_diagnostic_status, diagnostics.lastSyncStatus),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurface+ )+ }+}++@Composable+private fun ProviderDiagnosticPill(+ title: String,+ count: Int,+ timestamp: Long+) {+ val syncLabel = remember(timestamp) {+ if (timestamp <= 0L) {+ null+ } else {+ java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(timestamp))+ }+ }+ Surface(+ shape = RoundedCornerShape(10.dp),+ colors = SurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.06f)+ )+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Text(+ text = stringResource(R.string.settings_diagnostic_items, count),+ style = MaterialTheme.typography.labelLarge,+ color = OnBackground+ )+ Text(+ text = syncLabel ?: stringResource(R.string.settings_diagnostic_never),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurface+ )+ }+ }+}++@Composable+internal fun SettingsOverviewStat(+ label: String,+ value: String,+ modifier: Modifier = Modifier+) {+ Column(+ modifier = modifier+ .background(SurfaceHighlight.copy(alpha = 0.28f), RoundedCornerShape(12.dp))+ .padding(horizontal = 14.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = label.uppercase(Locale.getDefault()),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim+ )+ Text(+ text = value,+ style = MaterialTheme.typography.titleSmall,+ color = OnBackground,+ fontWeight = FontWeight.SemiBold+ )+ }+}++@Composable+private fun CompactSettingsActionChip(+ label: String,+ accent: Color,+ enabled: Boolean = true,+ onClick: () -> Unit+) {+ TvClickableSurface(+ onClick = onClick,+ enabled = enabled,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = accent.copy(alpha = if (enabled) 0.14f else 0.08f),+ contentColor = accent.copy(alpha = if (enabled) 1f else 0.42f),+ focusedContainerColor = accent.copy(alpha = if (enabled) 0.28f else 0.08f),+ focusedContentColor = accent.copy(alpha = if (enabled) 1f else 0.42f),+ disabledContainerColor = accent.copy(alpha = 0.08f),+ disabledContentColor = accent.copy(alpha = 0.42f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, Color.White.copy(alpha = if (enabled) 0.08f else 0.04f)),+ shape = RoundedCornerShape(8.dp)+ ),+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(8.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = label,+ color = accent.copy(alpha = if (enabled) 1f else 0.42f),+ style = MaterialTheme.typography.labelSmall,+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)+ )+ }+}++@Composable+internal fun EpgSourceTextField(+ value: String,+ onValueChange: (String) -> Unit,+ placeholder: String+) {+ val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()+ val focusRequester = remember { FocusRequester() }+ val keyboardController = LocalSoftwareKeyboardController.current+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ val coroutineScope = rememberCoroutineScope()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var fieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ val isFocused = hasContainerFocus || hasInputFocus++ fun requestBringIntoView(delayMillis: Long = 0L) {+ coroutineScope.launch {+ if (delayMillis > 0) {+ kotlinx.coroutines.delay(delayMillis)+ }+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ LaunchedEffect(value) {+ if (value != fieldValue.text) {+ val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = fieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ fieldValue = fieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {+ return@LaunchedEffect+ }+ focusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView(120)+ pendingInputActivation = false+ }++ TvClickableSurface(+ onClick = {+ if (!isTelevisionDevice) {+ focusRequester.requestFocus()+ keyboardController?.show()+ requestBringIntoView()+ requestBringIntoView(180)+ return@TvClickableSurface+ }+ acceptsInput = true+ pendingInputActivation = true+ requestBringIntoView()+ },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.12f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusChanged { hasContainerFocus = it.isFocused }+ ) {+ Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {+ if (value.isEmpty() && !isFocused) {+ Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)+ }+ BasicTextField(+ value = fieldValue,+ onValueChange = { updatedValue ->+ fieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },+ textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),+ singleLine = true,+ cursorBrush = SolidColor(Primary),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(focusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = fieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }+ .onFocusChanged {+ hasInputFocus = it.isFocused+ if (it.isFocused) {+ requestBringIntoView(120)+ } else {+ if (isTelevisionDevice) {+ acceptsInput = false+ }+ keyboardController?.hide()+ }+ },+ readOnly = isTelevisionDevice && !acceptsInput+ )+ }+ }+}++diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.ktnew file mode 100644index 00000000..066b9315--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderSection.kt@@ -0,0 +1,188 @@+package com.streamvault.app.ui.screens.settings++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.TvEmptyState+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderType++internal fun LazyListScope.providerSection(+ uiState: SettingsUiState,+ onAddProvider: () -> Unit,+ onEditProvider: (Provider) -> Unit,+ onNavigateToParentalControl: (Long) -> Unit,+ viewModel: SettingsViewModel,+ selectedCombinedProfileId: Long?,+ onSelectedCombinedProfileIdChange: (Long?) -> Unit,+ onPendingSyncProviderIdChange: (Long?) -> Unit,+ onCustomSyncSelectionsChange: (Set<ProviderSyncSelection>) -> Unit,+ onShowProviderSyncDialogChange: (Boolean) -> Unit,+ onShowCreateCombinedDialogChange: (Boolean) -> Unit,+ onShowRenameCombinedDialogChange: (Boolean) -> Unit,+ onShowAddCombinedMemberDialogChange: (Boolean) -> Unit+) {+ if (uiState.providers.isEmpty()) {+ item {+ TvEmptyState(+ title = stringResource(R.string.settings_no_providers),+ subtitle = stringResource(R.string.settings_no_providers_subtitle),+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 8.dp, bottom = 8.dp)+ )+ }+ } else {+ item {+ var selectedProviderId by rememberSaveable(uiState.providers, uiState.activeProviderId) {+ mutableStateOf(uiState.activeProviderId ?: uiState.providers.first().id)+ }+ LaunchedEffect(uiState.providers, uiState.activeProviderId) {+ val availableIds = uiState.providers.map { it.id }.toSet()+ if (selectedProviderId !in availableIds) {+ selectedProviderId = uiState.activeProviderId ?: uiState.providers.first().id+ }+ }+ val selectedProvider = uiState.providers.firstOrNull { it.id == selectedProviderId }+ ?: uiState.providers.first()++ Text(+ text = stringResource(R.string.settings_provider_selector_hint),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ modifier = Modifier.padding(bottom = 10.dp)+ )+ LazyRow(+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ contentPadding = PaddingValues(bottom = 14.dp)+ ) {+ items(uiState.providers, key = { it.id }) { provider ->+ ProviderSelectorTab(+ provider = provider,+ isSelected = provider.id == selectedProvider.id,+ isActive = provider.id == uiState.activeProviderId,+ onClick = { selectedProviderId = provider.id }+ )+ }+ }+ ProviderSettingsCard(+ provider = selectedProvider,+ isActive = selectedProvider.id == uiState.activeProviderId,+ isSyncing = uiState.isSyncing,+ diagnostics = uiState.diagnosticsByProvider[selectedProvider.id],+ syncWarnings = uiState.syncWarningsByProvider[selectedProvider.id].orEmpty(),+ onRetryWarningAction = { action -> viewModel.retryWarningAction(selectedProvider.id, action) },+ onConnect = { viewModel.setActiveProvider(selectedProvider.id) },+ onRefresh = {+ onPendingSyncProviderIdChange(selectedProvider.id)+ onCustomSyncSelectionsChange(+ buildSet {+ add(ProviderSyncSelection.TV)+ add(ProviderSyncSelection.MOVIES)+ add(ProviderSyncSelection.EPG)+ if (selectedProvider.type == ProviderType.XTREAM_CODES) {+ add(ProviderSyncSelection.SERIES)+ }+ }+ )+ onShowProviderSyncDialogChange(true)+ },+ onDelete = { viewModel.deleteProvider(selectedProvider.id) },+ onEdit = { onEditProvider(selectedProvider) },+ onParentalControl = { onNavigateToParentalControl(selectedProvider.id) },+ onToggleM3uVodClassification = { enabled ->+ viewModel.setM3uVodClassificationEnabled(selectedProvider.id, enabled)+ },+ onRefreshM3uClassification = {+ viewModel.refreshProviderClassification(selectedProvider.id)+ }+ )++ Spacer(modifier = Modifier.height(18.dp))+ CombinedM3uProfilesCard(+ profiles = uiState.combinedProfiles,+ availableProviders = uiState.availableM3uProviders,+ selectedProfileId = selectedCombinedProfileId,+ activeLiveSource = uiState.activeLiveSource,+ onSelectProfile = onSelectedCombinedProfileIdChange,+ onCreateProfile = { onShowCreateCombinedDialogChange(true) },+ onActivateProfile = { profileId -> viewModel.setActiveCombinedProfile(profileId) },+ onDeleteProfile = { profileId ->+ if (selectedCombinedProfileId == profileId) {+ onSelectedCombinedProfileIdChange(null)+ }+ viewModel.deleteCombinedProfile(profileId)+ },+ onRenameProfile = { profileId ->+ onSelectedCombinedProfileIdChange(profileId)+ onShowRenameCombinedDialogChange(true)+ },+ onAddProvider = { profileId ->+ onSelectedCombinedProfileIdChange(profileId)+ onShowAddCombinedMemberDialogChange(true)+ },+ onRemoveProvider = { profileId, providerId ->+ viewModel.removeProviderFromCombinedProfile(profileId, providerId)+ },+ onToggleProviderEnabled = { profileId, providerId, enabled ->+ viewModel.setCombinedProviderEnabled(profileId, providerId, enabled)+ },+ onMoveProvider = { profileId, providerId, moveUp ->+ viewModel.moveCombinedProvider(profileId, providerId, moveUp)+ }+ )+ }+ }++ item {+ TvClickableSurface(+ onClick = onAddProvider,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.15f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier.fillMaxWidth()+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.settings_add_provider),+ style = MaterialTheme.typography.bodyLarge,+ color = Primary+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.ktnew file mode 100644index 00000000..829cb42d--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingActions.kt@@ -0,0 +1,206 @@+package com.streamvault.app.ui.screens.settings++import android.app.Application+import com.streamvault.app.R+import com.streamvault.domain.manager.RecordingManager+import com.streamvault.domain.model.RecordingStorageConfig+import com.streamvault.domain.model.Result+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class SettingsRecordingActions(+ private val appContext: Application,+ private val recordingManager: RecordingManager,+ private val uiState: MutableStateFlow<SettingsUiState>+) {+ fun stopRecording(scope: CoroutineScope, recordingId: String) {+ scope.launch {+ val result = recordingManager.stopRecording(recordingId)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_stop_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_stopped)+ }+ )+ }+ }+ }++ fun cancelRecording(scope: CoroutineScope, recordingId: String) {+ scope.launch {+ val result = recordingManager.cancelRecording(recordingId)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_cancel_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_cancelled)+ }+ )+ }+ }+ }++ fun deleteRecording(scope: CoroutineScope, recordingId: String) {+ scope.launch {+ val result = recordingManager.deleteRecording(recordingId)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_delete_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_deleted)+ }+ )+ }+ }+ }++ fun retryRecording(scope: CoroutineScope, recordingId: String) {+ scope.launch {+ val result = recordingManager.retryRecording(recordingId)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_retry_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_retry_started)+ }+ )+ }+ }+ }++ fun setRecordingScheduleEnabled(scope: CoroutineScope, recordingId: String, enabled: Boolean) {+ scope.launch {+ val result = recordingManager.setScheduleEnabled(recordingId, enabled)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_schedule_toggle_failed, result.message)+ } else {+ appContext.getString(+ if (enabled) R.string.settings_recording_schedule_enabled+ else R.string.settings_recording_schedule_disabled+ )+ }+ )+ }+ }+ }++ fun reconcileRecordings(scope: CoroutineScope) {+ scope.launch {+ val result = recordingManager.reconcileRecordingState()+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_reconcile_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_reconcile_complete)+ }+ )+ }+ }+ }++ fun updateRecordingFolder(scope: CoroutineScope, treeUri: String?, displayName: String?) {+ scope.launch {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = treeUri,+ displayName = displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_storage_update_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_storage_updated)+ }+ )+ }+ }+ }++ fun updateRecordingFileNamePattern(scope: CoroutineScope, pattern: String) {+ scope.launch {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = pattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_pattern_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_pattern_saved)+ }+ )+ }+ }+ }++ fun updateRecordingRetentionDays(scope: CoroutineScope, retentionDays: Int?) {+ scope.launch {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_retention_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_retention_saved)+ }+ )+ }+ }+ }++ fun updateRecordingMaxSimultaneous(scope: CoroutineScope, maxSimultaneousRecordings: Int) {+ scope.launch {+ val current = uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings+ )+ )+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_concurrency_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_concurrency_saved)+ }+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.ktnew file mode 100644index 00000000..b3ff6f02--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsRecordingComponents.kt@@ -0,0 +1,651 @@+package com.streamvault.app.ui.screens.settings++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Switch+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.res.stringResource+import androidx.tv.material3.*+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogActionButton+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.design.FocusSpec+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import com.streamvault.domain.manager.BackupConflictStrategy+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingSourceType+import com.streamvault.domain.model.RecordingStatus+import androidx.compose.foundation.layout.ExperimentalLayoutApi++@Composable+internal fun InternetSpeedTestCard(+ valueLabel: String,+ summary: String,+ recommendationLabel: String,+ isRunning: Boolean,+ canApplyRecommendation: Boolean,+ onRunTest: () -> Unit,+ onApplyWifi: () -> Unit,+ onApplyEthernet: () -> Unit+) {+ val focusRequester = remember { FocusRequester() }+ TvClickableSurface(+ onClick = onRunTest,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.18f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 8.dp)+ .focusRequester(focusRequester)+ .mouseClickable(+ focusRequester = focusRequester,+ onClick = onRunTest+ )+ ) {+ Column(+ modifier = Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = stringResource(R.string.settings_speed_test_title),+ style = MaterialTheme.typography.bodyLarge,+ color = OnBackground+ )+ Text(+ text = valueLabel,+ style = MaterialTheme.typography.titleSmall,+ color = Primary,+ fontWeight = FontWeight.SemiBold+ )+ }+ if (isRunning) {+ CircularProgressIndicator(+ color = Primary,+ strokeWidth = 2.dp,+ modifier = Modifier.size(20.dp)+ )+ } else {+ Text(+ text = stringResource(R.string.settings_speed_test_run_action),+ style = MaterialTheme.typography.labelLarge,+ color = Primary+ )+ }+ }++ Text(+ text = summary,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )++ Text(+ text = stringResource(R.string.settings_speed_test_recommendation, recommendationLabel),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface+ )++ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ TvClickableSurface(+ onClick = onRunTest,+ enabled = !isRunning,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.18f),+ focusedContainerColor = Primary.copy(alpha = 0.32f)+ )+ ) {+ Text(+ text = stringResource(if (isRunning) R.string.settings_speed_test_running_action else R.string.settings_speed_test_run_action),+ style = MaterialTheme.typography.labelMedium,+ color = Primary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+ TvClickableSurface(+ onClick = onApplyWifi,+ enabled = canApplyRecommendation && !isRunning,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.28f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_speed_test_apply_wifi),+ style = MaterialTheme.typography.labelMedium,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+ TvClickableSurface(+ onClick = onApplyEthernet,+ enabled = canApplyRecommendation && !isRunning,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.28f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_speed_test_apply_ethernet),+ style = MaterialTheme.typography.labelMedium,+ color = Secondary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+ }+ }+ }+}++@Composable+internal fun BackupImportPreviewDialog(+ preview: com.streamvault.domain.manager.BackupPreview,+ plan: com.streamvault.domain.manager.BackupImportPlan,+ onDismiss: () -> Unit,+ onStrategySelected: (BackupConflictStrategy) -> Unit,+ onImportPreferencesChanged: (Boolean) -> Unit,+ onImportProvidersChanged: (Boolean) -> Unit,+ onImportSavedLibraryChanged: (Boolean) -> Unit,+ onImportPlaybackHistoryChanged: (Boolean) -> Unit,+ onImportMultiViewChanged: (Boolean) -> Unit,+ onImportRecordingSchedulesChanged: (Boolean) -> Unit,+ onConfirm: () -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_backup_preview_title),+ subtitle = stringResource(R.string.settings_backup_preview_subtitle, preview.version),+ onDismissRequest = onDismiss,+ widthFraction = 0.58f,+ content = {+ BackupPreviewRow(stringResource(R.string.settings_backup_section_preferences), preview.preferenceCount, 0)+ BackupPreviewRow(stringResource(R.string.settings_backup_section_providers), preview.providerCount, preview.providerConflicts)+ BackupPreviewRow(stringResource(R.string.settings_backup_section_saved), preview.favoriteCount + preview.groupCount + preview.protectedCategoryCount, preview.favoriteConflicts + preview.groupConflicts + preview.protectedCategoryConflicts)+ BackupPreviewRow(stringResource(R.string.settings_backup_section_history), preview.playbackHistoryCount, preview.historyConflicts)+ BackupPreviewRow(stringResource(R.string.settings_backup_section_multiview), preview.multiViewPresetCount, 0)+ BackupPreviewRow(stringResource(R.string.settings_backup_section_recordings), preview.scheduledRecordingCount, preview.recordingConflicts)+ Text(+ text = stringResource(R.string.settings_backup_conflict_strategy),+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ BackupStrategyChip(+ title = stringResource(R.string.settings_backup_keep_existing),+ selected = plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING,+ onClick = { onStrategySelected(BackupConflictStrategy.KEEP_EXISTING) }+ )+ BackupStrategyChip(+ title = stringResource(R.string.settings_backup_replace_existing),+ selected = plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING,+ onClick = { onStrategySelected(BackupConflictStrategy.REPLACE_EXISTING) }+ )+ }+ Text(+ text = stringResource(R.string.settings_backup_import_sections),+ style = MaterialTheme.typography.titleSmall,+ color = Primary+ )+ BackupToggleRow(stringResource(R.string.settings_backup_section_preferences), plan.importPreferences, onImportPreferencesChanged)+ BackupToggleRow(stringResource(R.string.settings_backup_section_providers), plan.importProviders, onImportProvidersChanged)+ BackupToggleRow(stringResource(R.string.settings_backup_section_saved), plan.importSavedLibrary, onImportSavedLibraryChanged)+ BackupToggleRow(stringResource(R.string.settings_backup_section_history), plan.importPlaybackHistory, onImportPlaybackHistoryChanged)+ BackupToggleRow(stringResource(R.string.settings_backup_section_multiview), plan.importMultiViewPresets, onImportMultiViewChanged)+ BackupToggleRow(stringResource(R.string.settings_backup_section_recordings), plan.importRecordingSchedules, onImportRecordingSchedulesChanged)+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_backup_import_confirm),+ onClick = onConfirm,+ emphasized = true+ )+ }+ )+}++@Composable+private fun BackupPreviewRow(+ title: String,+ itemCount: Int,+ conflictCount: Int+) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column {+ Text(title, style = MaterialTheme.typography.bodyLarge, color = OnBackground)+ Text(+ text = if (conflictCount > 0) {+ stringResource(R.string.settings_backup_conflict_count, conflictCount)+ } else {+ stringResource(R.string.settings_backup_no_conflicts)+ },+ style = MaterialTheme.typography.bodySmall,+ color = if (conflictCount > 0) Secondary else OnSurfaceDim+ )+ }+ Text(+ text = stringResource(R.string.settings_backup_item_count, itemCount),+ style = MaterialTheme.typography.labelLarge,+ color = OnBackground+ )+ }+}++@Composable+private fun BackupStrategyChip(+ title: String,+ selected: Boolean,+ onClick: () -> Unit+) {+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(24.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.2f) else SurfaceElevated,+ focusedContainerColor = Primary.copy(alpha = 0.35f)+ )+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.labelLarge,+ color = if (selected) Primary else OnBackground,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)+ )+ }+}++@Composable+private fun BackupToggleRow(+ label: String,+ checked: Boolean,+ onCheckedChange: (Boolean) -> Unit+) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(label, style = MaterialTheme.typography.bodyLarge, color = OnBackground)+ Switch(checked = checked, onCheckedChange = onCheckedChange)+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun RecordingOverviewCard(+ treeLabel: String?,+ outputDirectory: String?,+ availableBytes: Long?,+ isWritable: Boolean,+ activeCount: Int,+ scheduledCount: Int,+ fileNamePattern: String,+ retentionDays: Int?,+ maxSimultaneousRecordings: Int,+ onChooseFolder: () -> Unit,+ onUseAppStorage: () -> Unit,+ onChangePattern: () -> Unit,+ onChangeRetention: () -> Unit,+ onChangeConcurrency: () -> Unit,+ onRepairSchedule: () -> Unit+) {+ Surface(+ modifier = Modifier.fillMaxWidth(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier.padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ Text(+ text = stringResource(R.string.settings_recording_storage_title),+ style = MaterialTheme.typography.titleMedium,+ color = Primary+ )+ treeLabel?.takeIf { it.isNotBlank() }?.let {+ Text(+ text = it,+ style = MaterialTheme.typography.bodySmall,+ color = Secondary+ )+ }+ Text(+ text = outputDirectory ?: stringResource(R.string.settings_recording_storage_unknown),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ SettingsOverviewStat(+ label = stringResource(R.string.settings_recording_active_label),+ value = activeCount.toString(),+ modifier = Modifier.weight(1f)+ )+ SettingsOverviewStat(+ label = stringResource(R.string.settings_recording_scheduled_label),+ value = scheduledCount.toString(),+ modifier = Modifier.weight(1f)+ )+ SettingsOverviewStat(+ label = stringResource(R.string.settings_recording_space_label),+ value = availableBytes?.let(::formatBytes) ?: stringResource(R.string.settings_recording_storage_unknown),+ modifier = Modifier.weight(1f)+ )+ }+ Text(+ text = if (isWritable) stringResource(R.string.settings_recording_storage_ready) else stringResource(R.string.settings_recording_storage_unavailable),+ style = MaterialTheme.typography.bodySmall,+ color = if (isWritable) Primary else ErrorColor+ )+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_pattern_title),+ value = fileNamePattern+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_retention_title),+ value = retentionDays?.let {+ stringResource(R.string.settings_recording_retention_days, it)+ } ?: stringResource(R.string.settings_recording_retention_keep_all)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_concurrency_title),+ value = maxSimultaneousRecordings.toString()+ )+ }+ FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ maxItemsInEachRow = 3+ ) {+ RecordingActionButton(stringResource(R.string.settings_recording_choose_folder), Primary, onChooseFolder)+ RecordingActionButton(stringResource(R.string.settings_recording_use_app_storage), Secondary, onUseAppStorage)+ RecordingActionButton(stringResource(R.string.settings_recording_pattern_title), OnBackground, onChangePattern)+ RecordingActionButton(stringResource(R.string.settings_recording_retention_title), OnBackground, onChangeRetention)+ RecordingActionButton(stringResource(R.string.settings_recording_concurrency_title), OnBackground, onChangeConcurrency)+ RecordingActionButton(stringResource(R.string.settings_recording_reconcile), Secondary, onRepairSchedule)+ }+ }+ }+}++@Composable+internal fun RecordingItemCard(+ item: RecordingItem,+ onPlay: () -> Unit,+ onStop: () -> Unit,+ onCancel: () -> Unit,+ onDelete: () -> Unit,+ onRetry: () -> Unit,+ onToggleSchedule: (Boolean) -> Unit+) {+ Surface(+ modifier = Modifier.fillMaxWidth(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(12.dp)+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(+ item.programTitle ?: item.channelName,+ style = MaterialTheme.typography.bodyMedium,+ color = OnBackground,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ if (item.programTitle != null && item.programTitle != item.channelName) {+ Text(+ item.channelName,+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ Text(+ text = when (item.status) {+ RecordingStatus.SCHEDULED -> stringResource(R.string.settings_recording_status_scheduled)+ RecordingStatus.RECORDING -> stringResource(R.string.settings_recording_status_recording)+ RecordingStatus.COMPLETED -> stringResource(R.string.settings_recording_status_completed)+ RecordingStatus.FAILED -> stringResource(R.string.settings_recording_status_failed)+ RecordingStatus.CANCELLED -> stringResource(R.string.settings_recording_status_cancelled)+ },+ style = MaterialTheme.typography.labelMedium,+ color = when (item.status) {+ RecordingStatus.RECORDING -> Primary+ RecordingStatus.COMPLETED -> OnBackground+ RecordingStatus.FAILED -> ErrorColor+ RecordingStatus.CANCELLED -> OnSurfaceDim+ RecordingStatus.SCHEDULED -> Secondary+ }+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(+ R.string.settings_recording_time_window,+ formatTimestamp(item.scheduledStartMs),+ formatTimestamp(item.scheduledEndMs)+ ),+ style = MaterialTheme.typography.labelSmall,+ color = OnSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )+ if (item.recurrence != RecordingRecurrence.NONE) {+ Spacer(modifier = Modifier.width(8.dp))+ Text(+ text = when (item.recurrence) {+ RecordingRecurrence.DAILY -> stringResource(R.string.settings_recording_recurrence_daily)+ RecordingRecurrence.WEEKLY -> stringResource(R.string.settings_recording_recurrence_weekly)+ RecordingRecurrence.NONE -> stringResource(R.string.settings_recording_recurrence_none)+ },+ style = MaterialTheme.typography.labelSmall,+ color = Secondary,+ maxLines = 1+ )+ }+ }+ item.failureReason?.takeIf { it.isNotBlank() }?.let { reason ->+ Text(reason, style = MaterialTheme.typography.bodySmall, color = ErrorColor)+ }+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp),+ modifier = Modifier.fillMaxWidth(),+ maxItemsInEachRow = 4+ ) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_source_label),+ value = formatRecordingSourceType(item.sourceType)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_bytes_label),+ value = formatBytes(item.bytesWritten)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_speed_label),+ value = if (item.averageThroughputBytesPerSecond > 0L) {+ "${formatBytes(item.averageThroughputBytesPerSecond)}/s"+ } else {+ "ג€“"+ }+ )+ if (item.retryCount > 0) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_retry_count_label),+ value = item.retryCount.toString()+ )+ }+ }+ item.outputDisplayPath?.takeIf { it.isNotBlank() }?.let { output ->+ Text(+ text = "${stringResource(R.string.settings_recording_output_label)}: ${summarizeRecordingOutputPath(output)}",+ style = MaterialTheme.typography.labelSmall,+ color = OnSurfaceDim,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ }+ if (item.failureCategory != RecordingFailureCategory.NONE) {+ Text(+ text = "${stringResource(R.string.settings_recording_failure_label)}: ${formatRecordingFailureCategory(item.failureCategory)}",+ style = MaterialTheme.typography.labelSmall,+ color = ErrorColor+ )+ }+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp),+ modifier = Modifier.fillMaxWidth(),+ maxItemsInEachRow = 4+ ) {+ if (item.status == RecordingStatus.COMPLETED && (!item.outputUri.isNullOrBlank() || !item.outputPath.isNullOrBlank())) {+ CompactRecordingActionChip(+ label = "Play",+ accent = Primary,+ onClick = onPlay+ )+ }+ if (item.status == RecordingStatus.RECORDING) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_stop),+ accent = ErrorColor,+ onClick = onStop+ )+ }+ if (item.status == RecordingStatus.SCHEDULED) {+ CompactRecordingActionChip(+ label = stringResource(+ if (item.scheduleEnabled) R.string.settings_recording_disable+ else R.string.settings_recording_enable+ ),+ accent = Secondary,+ onClick = { onToggleSchedule(!item.scheduleEnabled) }+ )+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_cancel),+ accent = OnBackground,+ onClick = onCancel+ )+ }+ if (item.status == RecordingStatus.COMPLETED || item.status == RecordingStatus.FAILED || item.status == RecordingStatus.CANCELLED) {+ if (item.status == RecordingStatus.FAILED) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_retry),+ accent = Primary,+ onClick = onRetry+ )+ }+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_delete),+ accent = OnBackground,+ onClick = onDelete+ )+ }+ }+ }+ }+}++@Composable+internal fun CompactRecordingActionChip(label: String, accent: Color, onClick: () -> Unit) {+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = accent.copy(alpha = 0.14f),+ focusedContainerColor = accent.copy(alpha = 0.3f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(FocusSpec.BorderWidth, Color.White),+ shape = RoundedCornerShape(8.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = label,+ color = accent,+ style = MaterialTheme.typography.labelSmall,+ modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp)+ )+ }+}++internal fun RecordingItem.playbackUrl(): String? {+ val persistedUri = outputUri?.trim()?.takeIf { it.isNotBlank() }+ if (persistedUri != null) {+ return persistedUri+ }+ val localPath = outputPath?.trim()?.takeIf { it.isNotBlank() } ?: return null+ val parsed = runCatching { android.net.Uri.parse(localPath) }.getOrNull()+ return if (parsed?.scheme.isNullOrBlank()) {+ android.net.Uri.fromFile(java.io.File(localPath)).toString()+ } else {+ localPath+ }+}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 36e2c953..ab526010 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@@ -99,9 +99,11 @@ import com.streamvault.app.navigation.Routesimport java.util.Localeimport com.streamvault.app.BuildConfigimport com.streamvault.app.ui.screens.settings.AppUpdateUiModel+import com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.interaction.mouseClickableimport java.text.DateFormatimport com.streamvault.app.ui.design.FocusSpec+import kotlinx.coroutines.delay@Composable@@ -114,6 +116,7 @@ fun SettingsScreen(viewModel: SettingsViewModel = hiltViewModel()) {val uiState by viewModel.uiState.collectAsStateWithLifecycle()+ val settingsNavFocusRequester = remember { FocusRequester() }val snackbarHostState = remember { SnackbarHostState() }val scope = rememberCoroutineScope()@@ -265,6 +268,11 @@ fun SettingsScreen(}}+ LaunchedEffect(currentRoute, selectedCategory) {+ delay(80)+ settingsNavFocusRequester.requestFocusSafely(tag = "SettingsScreen", target = "Selected settings section")+ }+Box(modifier = Modifier.fillMaxSize()) {AppScreenScaffold(currentRoute = currentRoute,@@ -276,7 +284,7 @@ fun SettingsScreen(showScreenHeader = false) {Row(modifier = Modifier.fillMaxSize()) {- // ── Left navigation rail ──────────────────────────────────────+ // ג”€ג”€ Left navigation rail ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€LazyColumn(modifier = Modifier.width(236.dp)@@ -285,13 +293,69 @@ fun SettingsScreen(contentPadding = PaddingValues(top = 76.dp, bottom = 16.dp),verticalArrangement = Arrangement.spacedBy(2.dp)) {- item { SettingsNavItem(stringResource(R.string.settings_providers), "P", Primary, selectedCategory == 0) { selectedCategory = 0 } }- item { SettingsNavItem(stringResource(R.string.settings_playback), ">", Color(0xFF9E8FFF), selectedCategory == 1) { selectedCategory = 1 } }- item { SettingsNavItem(stringResource(R.string.settings_privacy), "L", Color(0xFFFFB74D), selectedCategory == 2) { selectedCategory = 2 } }- item { SettingsNavItem(stringResource(R.string.settings_recording_title), "R", Color(0xFFEF5350), selectedCategory == 3) { selectedCategory = 3 } }- item { SettingsNavItem(stringResource(R.string.settings_backup_restore), "B", Color(0xFF42A5F5), selectedCategory == 4) { selectedCategory = 4 } }- item { SettingsNavItem("EPG Sources", "E", Color(0xFF66BB6A), selectedCategory == 5) { selectedCategory = 5; viewModel.loadEpgSources() } }- item { SettingsNavItem(stringResource(R.string.settings_about), "i", Color(0xFF78909C), selectedCategory == 6) { selectedCategory = 6 } }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_providers),+ "P",+ Primary,+ selectedCategory == 0,+ modifier = if (selectedCategory == 0) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 0 }+ }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_playback),+ ">",+ Color(0xFF9E8FFF),+ selectedCategory == 1,+ modifier = if (selectedCategory == 1) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 1 }+ }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_privacy),+ "L",+ Color(0xFFFFB74D),+ selectedCategory == 2,+ modifier = if (selectedCategory == 2) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 2 }+ }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_recording_title),+ "R",+ Color(0xFFEF5350),+ selectedCategory == 3,+ modifier = if (selectedCategory == 3) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 3 }+ }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_backup_restore),+ "B",+ Color(0xFF42A5F5),+ selectedCategory == 4,+ modifier = if (selectedCategory == 4) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 4 }+ }+ item {+ SettingsNavItem(+ "EPG Sources",+ "E",+ Color(0xFF66BB6A),+ selectedCategory == 5,+ modifier = if (selectedCategory == 5) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 5; viewModel.loadEpgSources() }+ }+ item {+ SettingsNavItem(+ stringResource(R.string.settings_about),+ "i",+ Color(0xFF78909C),+ selectedCategory == 6,+ modifier = if (selectedCategory == 6) Modifier.focusRequester(settingsNavFocusRequester) else Modifier+ ) { selectedCategory = 6 }+ }}// Thin vertical separator@@ -302,7 +366,7 @@ fun SettingsScreen(.background(Color.White.copy(alpha = 0.07f)))- // ── Right content pane ────────────────────────────────────────+ // ג”€ג”€ Right content pane ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€LazyColumn(modifier = Modifier.weight(1f)@@ -311,146 +375,26 @@ fun SettingsScreen(verticalArrangement = Arrangement.spacedBy(10.dp),userScrollEnabled = !uiState.isSyncing) {- // ── 0: Providers ──────────────────────────────────────────+ // ג”€ג”€ 0: Providers ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€if (selectedCategory == 0) {- if (uiState.providers.isEmpty()) {- item {- TvEmptyState(- title = stringResource(R.string.settings_no_providers),- subtitle = stringResource(R.string.settings_no_providers_subtitle),- modifier = Modifier- .fillMaxWidth()- .padding(top = 8.dp, bottom = 8.dp)- )- }- } else {- item {- var selectedProviderId by rememberSaveable(uiState.providers, uiState.activeProviderId) {- mutableStateOf(uiState.activeProviderId ?: uiState.providers.first().id)- }- LaunchedEffect(uiState.providers, uiState.activeProviderId) {- val availableIds = uiState.providers.map { it.id }.toSet()- if (selectedProviderId !in availableIds) {- selectedProviderId = uiState.activeProviderId ?: uiState.providers.first().id- }- }- val selectedProvider = uiState.providers.firstOrNull { it.id == selectedProviderId }- ?: uiState.providers.first()-- Text(- text = stringResource(R.string.settings_provider_selector_hint),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- modifier = Modifier.padding(bottom = 10.dp)- )- LazyRow(- horizontalArrangement = Arrangement.spacedBy(10.dp),- contentPadding = PaddingValues(bottom = 14.dp)- ) {- items(uiState.providers, key = { it.id }) { provider ->- ProviderSelectorTab(- provider = provider,- isSelected = provider.id == selectedProvider.id,- isActive = provider.id == uiState.activeProviderId,- onClick = { selectedProviderId = provider.id }- )- }- }- ProviderSettingsCard(- provider = selectedProvider,- isActive = selectedProvider.id == uiState.activeProviderId,- isSyncing = uiState.isSyncing,- diagnostics = uiState.diagnosticsByProvider[selectedProvider.id],- syncWarnings = uiState.syncWarningsByProvider[selectedProvider.id].orEmpty(),- onRetryWarningAction = { action -> viewModel.retryWarningAction(selectedProvider.id, action) },- onConnect = { viewModel.setActiveProvider(selectedProvider.id) },- onRefresh = {- pendingSyncProviderId = selectedProvider.id- customSyncSelections = buildSet {- add(ProviderSyncSelection.TV)- add(ProviderSyncSelection.MOVIES)- add(ProviderSyncSelection.EPG)- if (selectedProvider.type == ProviderType.XTREAM_CODES) {- add(ProviderSyncSelection.SERIES)- }- }- showProviderSyncDialog = true- },- onDelete = { viewModel.deleteProvider(selectedProvider.id) },- onEdit = { onEditProvider(selectedProvider) },- onParentalControl = { onNavigateToParentalControl(selectedProvider.id) },- onToggleM3uVodClassification = { enabled ->- viewModel.setM3uVodClassificationEnabled(selectedProvider.id, enabled)- },- onRefreshM3uClassification = {- viewModel.refreshProviderClassification(selectedProvider.id)- }- )-- Spacer(modifier = Modifier.height(18.dp))- CombinedM3uProfilesCard(- profiles = uiState.combinedProfiles,- availableProviders = uiState.availableM3uProviders,- selectedProfileId = selectedCombinedProfileId,- activeLiveSource = uiState.activeLiveSource,- onSelectProfile = { selectedCombinedProfileId = it },- onCreateProfile = { showCreateCombinedDialog = true },- onActivateProfile = { profileId -> viewModel.setActiveCombinedProfile(profileId) },- onDeleteProfile = { profileId ->- if (selectedCombinedProfileId == profileId) {- selectedCombinedProfileId = null- }- viewModel.deleteCombinedProfile(profileId)- },- onRenameProfile = { profileId ->- selectedCombinedProfileId = profileId- showRenameCombinedDialog = true- },- onAddProvider = { profileId ->- selectedCombinedProfileId = profileId- showAddCombinedMemberDialog = true- },- onRemoveProvider = { profileId, providerId ->- viewModel.removeProviderFromCombinedProfile(profileId, providerId)- },- onToggleProviderEnabled = { profileId, providerId, enabled ->- viewModel.setCombinedProviderEnabled(profileId, providerId, enabled)- },- onMoveProvider = { profileId, providerId, moveUp ->- viewModel.moveCombinedProvider(profileId, providerId, moveUp)- }- )- }- }- item {- TvClickableSurface(- onClick = onAddProvider,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.15f),- focusedContainerColor = Primary.copy(alpha = 0.3f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier.fillMaxWidth()- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(16.dp),- horizontalArrangement = Arrangement.Center,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(R.string.settings_add_provider),- style = MaterialTheme.typography.bodyLarge,- color = Primary- )- }- }- }+ providerSection(+ uiState = uiState,+ onAddProvider = onAddProvider,+ onEditProvider = onEditProvider,+ onNavigateToParentalControl = onNavigateToParentalControl,+ viewModel = viewModel,+ selectedCombinedProfileId = selectedCombinedProfileId,+ onSelectedCombinedProfileIdChange = { selectedCombinedProfileId = it },+ onPendingSyncProviderIdChange = { pendingSyncProviderId = it },+ onCustomSyncSelectionsChange = { customSyncSelections = it },+ onShowProviderSyncDialogChange = { showProviderSyncDialog = it },+ onShowCreateCombinedDialogChange = { showCreateCombinedDialog = it },+ onShowRenameCombinedDialogChange = { showRenameCombinedDialog = it },+ onShowAddCombinedMemberDialogChange = { showAddCombinedMemberDialog = it }+ )}- // ── 1: Playback ───────────────────────────────────────────+ // ג”€ג”€ 1: Playback ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 1) {item {TvClickableSurface(@@ -659,7 +603,7 @@ fun SettingsScreen(}}- // ── 2: Privacy & Parental ─────────────────────────────────+ // ג”€ג”€ 2: Privacy & Parental ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 2) {item {ParentalControlCard(@@ -754,12 +698,12 @@ fun SettingsScreen(Text(text = stringResource(R.string.settings_clear_history_subtitle), style = MaterialTheme.typography.bodySmall, color = OnBackground.copy(alpha = 0.6f))}Text(text = stringResource(R.string.settings_clear_history_confirm), style = MaterialTheme.typography.labelLarge, color = Primary)- }- }- }- }+ }+ }+ }+ }- // ── 3: Recordings ─────────────────────────────────────────+ // ג”€ג”€ 3: Recordings ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 3) {item {RecordingOverviewCard(@@ -808,8 +752,8 @@ fun SettingsScreen(Routes.player(streamUrl = playbackUrl,title = item.programTitle ?: item.channelName,- internalId = item.channelId,- providerId = item.providerId,+ internalId = -1L,+ providerId = null,contentType = "MOVIE",returnRoute = currentRoute)@@ -826,7 +770,7 @@ fun SettingsScreen(}}- // ── 4: Backup ─────────────────────────────────────────────+ // ג”€ג”€ 4: Backup ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 4) {item {Row(@@ -877,297 +821,15 @@ fun SettingsScreen(}}- // ── 5: EPG Sources ───────────────────────────────────────+ // ג”€ג”€ 5: EPG Sources ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 5) {- val epgSources = uiState.epgSources- val providers = uiState.providers-- item {- Text(- text = "EPG Sources",- style = MaterialTheme.typography.titleMedium,- color = Color(0xFF66BB6A),- modifier = Modifier.padding(bottom = 8.dp)- )- Text(- text = "Add external XMLTV EPG sources and assign them to providers. External sources are matched to channels by ID or name and override provider-native EPG data.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- modifier = Modifier.padding(bottom = 16.dp)- )- }-- // Add source form- item {- var newName by remember { mutableStateOf("") }- var newUrl by remember { mutableStateOf("") }- val ctx = androidx.compose.ui.platform.LocalContext.current- val filePickerLauncher = rememberLauncherForActivityResult(- contract = ActivityResultContracts.OpenDocument()- ) { uri ->- if (uri != null) {- try {- ctx.contentResolver.takePersistableUriPermission(- uri, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION- )- } catch (_: SecurityException) { /* provider does not offer persistable permission */ }- newUrl = uri.toString()- }- }- Box(- modifier = Modifier- .fillMaxWidth()- .clip(RoundedCornerShape(12.dp))- .background(Color.White.copy(alpha = 0.06f))- ) {- Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text("Add EPG Source", style = MaterialTheme.typography.titleSmall, color = Color.White)- EpgSourceTextField(value = newName, onValueChange = { newName = it }, placeholder = "Source name")- Row(- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Box(modifier = Modifier.weight(1f)) {- EpgSourceTextField(- value = newUrl,- onValueChange = { newUrl = it },- placeholder = "XMLTV URL (HTTPS) or browse file"- )- }- TvClickableSurface(- onClick = { filePickerLauncher.launch(arrayOf("*/*")) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.15f),- focusedContainerColor = Primary.copy(alpha = 0.3f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Browse", modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), style = MaterialTheme.typography.labelMedium, color = Primary)- }- }- TvClickableSurface(- onClick = {- if (newName.isNotBlank() && newUrl.isNotBlank()) {- viewModel.addEpgSource(newName.trim(), newUrl.trim())- newName = ""- newUrl = ""- }- },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color(0xFF66BB6A).copy(alpha = 0.2f),- focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.4f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Add Source", modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = Color(0xFF66BB6A))- }- }- }- }-- // Source list- if (epgSources.isEmpty()) {- item {- Text(- text = "No external EPG sources configured. Add a source above to get started.",- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim,- modifier = Modifier.padding(vertical = 16.dp)- )- }- } else {- items(epgSources.size) { index ->- val source = epgSources[index]- Box(- modifier = Modifier- .fillMaxWidth()- .clip(RoundedCornerShape(12.dp))- .background(Color.White.copy(alpha = 0.06f))- ) {- Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Row(verticalAlignment = Alignment.CenterVertically) {- Column(modifier = Modifier.weight(1f)) {- Text(source.name, style = MaterialTheme.typography.titleSmall, color = Color.White)- Text(displayableEpgUrl(source.url), style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, maxLines = 1)- if (source.lastError != null) {- Text("Error: ${source.lastError}", style = MaterialTheme.typography.bodySmall, color = Color(0xFFEF5350))- }- if (source.lastSuccessAt != null) {- val ago = (System.currentTimeMillis() - source.lastSuccessAt) / 60000- Text("Last synced: ${ago}m ago", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- }- }- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- TvClickableSurface(- onClick = { viewModel.toggleEpgSourceEnabled(source.id, !source.enabled) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.2f) else Color.White.copy(alpha = 0.08f),- focusedContainerColor = if (source.enabled) Color(0xFF66BB6A).copy(alpha = 0.4f) else Color.White.copy(alpha = 0.15f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- if (source.enabled) "ON" else "OFF",- modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),- style = MaterialTheme.typography.labelSmall,- color = if (source.enabled) Color(0xFF66BB6A) else OnSurfaceDim- )- }- TvClickableSurface(- onClick = { viewModel.refreshEpgSource(source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.15f),- focusedContainerColor = Primary.copy(alpha = 0.3f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Refresh", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Primary)- }- TvClickableSurface(- onClick = { viewModel.deleteEpgSource(source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),- focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Delete", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))- }- }- }- }- }- }- }-- // Provider assignment section- if (providers.isNotEmpty() && epgSources.isNotEmpty()) {- item {- Text(- text = "Provider Assignments",- style = MaterialTheme.typography.titleMedium,- color = Color(0xFF66BB6A),- modifier = Modifier.padding(top = 24.dp, bottom = 8.dp)- )- Text(- text = "Assign EPG sources to providers. Channels will be matched automatically by ID or name.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim,- modifier = Modifier.padding(bottom = 8.dp)- )- }- items(providers.size) { providerIndex ->- val provider = providers[providerIndex]- val assignments = uiState.epgSourceAssignments[provider.id].orEmpty()- val resolutionSummary = uiState.epgResolutionSummaries[provider.id]- val assignedSourceIds = assignments.map { it.epgSourceId }.toSet()- val unassignedSources = epgSources.filter { it.id !in assignedSourceIds }-- LaunchedEffect(provider.id) {- viewModel.loadEpgAssignments(provider.id)- }-- Box(- modifier = Modifier- .fillMaxWidth()- .clip(RoundedCornerShape(12.dp))- .background(Color.White.copy(alpha = 0.06f))- ) {- Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(provider.name, style = MaterialTheme.typography.titleSmall, color = Color.White)- if (resolutionSummary != null) {- val matchedChannels = (resolutionSummary.totalChannels - resolutionSummary.unresolvedChannels).coerceAtLeast(0)- Text(- text = "Matched $matchedChannels/${resolutionSummary.totalChannels} channels • ${resolutionSummary.exactIdMatches} exact • ${resolutionSummary.normalizedNameMatches} name • ${resolutionSummary.providerNativeMatches} provider",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }-- if (assignments.isEmpty()) {- Text("No EPG sources assigned", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- } else {- assignments.sortedBy { it.priority }.forEachIndexed { assignmentIndex, assignment ->- Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {- Text(- "${assignment.epgSourceName} (priority: ${assignment.priority})",- style = MaterialTheme.typography.bodySmall,- color = Color.White,- modifier = Modifier.weight(1f)- )- Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {- TvClickableSurface(- onClick = { viewModel.moveEpgSourceAssignmentUp(provider.id, assignment.epgSourceId) },- enabled = assignmentIndex > 0,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.08f),- focusedContainerColor = Color.White.copy(alpha = 0.16f),- disabledContainerColor = Color.White.copy(alpha = 0.04f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Up", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)- }- TvClickableSurface(- onClick = { viewModel.moveEpgSourceAssignmentDown(provider.id, assignment.epgSourceId) },- enabled = assignmentIndex < assignments.lastIndex,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.08f),- focusedContainerColor = Color.White.copy(alpha = 0.16f),- disabledContainerColor = Color.White.copy(alpha = 0.04f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Down", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color.White)- }- }- Spacer(modifier = Modifier.width(6.dp))- TvClickableSurface(- onClick = { viewModel.unassignEpgSourceFromProvider(provider.id, assignment.epgSourceId) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color(0xFFEF5350).copy(alpha = 0.12f),- focusedContainerColor = Color(0xFFEF5350).copy(alpha = 0.25f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("Remove", modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFFEF5350))- }- }- }- }-- if (unassignedSources.isNotEmpty()) {- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- unassignedSources.forEach { source ->- TvClickableSurface(- onClick = { viewModel.assignEpgSourceToProvider(provider.id, source.id) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color(0xFF66BB6A).copy(alpha = 0.12f),- focusedContainerColor = Color(0xFF66BB6A).copy(alpha = 0.25f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text("+ ${source.name}", modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall, color = Color(0xFF66BB6A))- }- }- }- }- }- }- }- }+ epgSourcesSection(+ uiState = uiState,+ viewModel = viewModel+ )}- // ── 6: About ──────────────────────────────────────────────+ // ג”€ג”€ 6: About ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else {item {SettingsSectionHeader(@@ -1260,3926 +922,92 @@ fun SettingsScreen(.padding(bottom = 16.dp))- // Blocking Loading Overlay- if (uiState.isSyncing) {- // Block Back Press- androidx.activity.compose.BackHandler(enabled = true) {- // Do nothing, effectively blocking back- }-- val overlayFocusRequester = remember { FocusRequester() }- LaunchedEffect(Unit) { overlayFocusRequester.requestFocus() }-- // Overlay- Box(- modifier = Modifier- .fillMaxSize()- .background(Color.Black.copy(alpha = 0.7f))- .clickable(enabled = true, onClick = {}) // Consume clicks- .focusRequester(overlayFocusRequester)- .focusable()- .onKeyEvent { true } // Consume all d-pad/key events- .align(Alignment.Center),- contentAlignment = Alignment.Center- ) {- Column(- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- CircularProgressIndicator(color = Primary)- Text(- text = stringResource(R.string.settings_syncing_title),- style = MaterialTheme.typography.titleMedium,- color = OnSurface- )- Text(- text = stringResource(R.string.settings_syncing_subtitle),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }--- if (showLiveTvModeDialog) {- LiveTvChannelModeDialog(- selectedMode = uiState.liveTvChannelMode,- onDismiss = { showLiveTvModeDialog = false },- onModeSelected = { mode ->- viewModel.setLiveTvChannelMode(mode)- showLiveTvModeDialog = false- }- )- }-- if (showLiveTvQuickFilterVisibilityDialog) {- LiveTvQuickFilterVisibilityDialog(- selectedMode = uiState.liveTvQuickFilterVisibilityMode,- onDismiss = { showLiveTvQuickFilterVisibilityDialog = false },- onModeSelected = { mode ->- viewModel.setLiveTvQuickFilterVisibilityMode(mode)- showLiveTvQuickFilterVisibilityDialog = false- }- )- }-- if (showLiveChannelNumberingDialog) {- LiveChannelNumberingModeDialog(- selectedMode = uiState.liveChannelNumberingMode,- onDismiss = { showLiveChannelNumberingDialog = false },- onModeSelected = { mode ->- viewModel.setLiveChannelNumberingMode(mode)- showLiveChannelNumberingDialog = false- }- )- }-- if (showVodViewModeDialog) {- VodViewModeDialog(- selectedMode = uiState.vodViewMode,- onDismiss = { showVodViewModeDialog = false },- onModeSelected = { mode ->- viewModel.setVodViewMode(mode)- showVodViewModeDialog = false- }- )- }-- if (showPlaybackSpeedDialog) {- val speedOptions = remember { listOf(0.5f, 0.75f, 1f, 1.25f, 1.5f, 2f) }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_playback_speed),- onDismiss = { showPlaybackSpeedDialog = false }- ) {- speedOptions.forEachIndexed { index, speed ->- LevelOption(- level = index,- text = formatPlaybackSpeedLabel(speed),- currentLevel = if (speed == uiState.playerPlaybackSpeed) index else -1,- onSelect = {- viewModel.setDefaultPlaybackSpeed(speed)- showPlaybackSpeedDialog = false- }- )- }- }- }-- if (showDecoderModeDialog) {- val decoderOptions = remember(context) {- listOf(- DecoderMode.AUTO to context.getString(R.string.settings_decoder_auto),- DecoderMode.HARDWARE to context.getString(R.string.settings_decoder_hardware),- DecoderMode.SOFTWARE to context.getString(R.string.settings_decoder_software)- )- }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_decoder_mode),- onDismiss = { showDecoderModeDialog = false }- ) {- decoderOptions.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.second,- currentLevel = if (uiState.playerDecoderMode == option.first) index else -1,- onSelect = {- viewModel.setPlayerDecoderMode(option.first)- showDecoderModeDialog = false- }- )- }- }- }-- if (showControlsTimeoutDialog) {- TimeoutValueDialog(- title = stringResource(R.string.settings_player_controls_timeout),- subtitle = stringResource(R.string.settings_timeout_vod_controls_subtitle),- initialValue = uiState.playerControlsTimeoutSeconds,- onDismiss = { showControlsTimeoutDialog = false }- ) { seconds ->- viewModel.setPlayerControlsTimeoutSeconds(seconds)- showControlsTimeoutDialog = false- }- }-- if (showLiveOverlayTimeoutDialog) {- TimeoutValueDialog(- title = stringResource(R.string.settings_live_overlay_timeout),- subtitle = stringResource(R.string.settings_timeout_live_overlays_subtitle),- initialValue = uiState.playerLiveOverlayTimeoutSeconds,- onDismiss = { showLiveOverlayTimeoutDialog = false }- ) { seconds ->- viewModel.setPlayerLiveOverlayTimeoutSeconds(seconds)- showLiveOverlayTimeoutDialog = false- }- }-- if (showNoticeTimeoutDialog) {- TimeoutValueDialog(- title = stringResource(R.string.settings_player_notice_timeout),- subtitle = stringResource(R.string.settings_timeout_notices_subtitle),- initialValue = uiState.playerNoticeTimeoutSeconds,- onDismiss = { showNoticeTimeoutDialog = false }- ) { seconds ->- viewModel.setPlayerNoticeTimeoutSeconds(seconds)- showNoticeTimeoutDialog = false- }- }-- if (showDiagnosticsTimeoutDialog) {- TimeoutValueDialog(- title = stringResource(R.string.settings_player_diagnostics_timeout),- subtitle = stringResource(R.string.settings_timeout_diagnostics_subtitle),- initialValue = uiState.playerDiagnosticsTimeoutSeconds,- onDismiss = { showDiagnosticsTimeoutDialog = false }- ) { seconds ->- viewModel.setPlayerDiagnosticsTimeoutSeconds(seconds)- showDiagnosticsTimeoutDialog = false- }- }-- if (showLiveTvFiltersDialog) {- LiveTvQuickFiltersDialog(- filters = uiState.liveTvCategoryFilters,- onDismiss = { showLiveTvFiltersDialog = false },- onAddFilter = viewModel::addLiveTvCategoryFilter,- onRemoveFilter = viewModel::removeLiveTvCategoryFilter- )- }-- if (showAudioLanguageDialog) {- val autoLabel = stringResource(R.string.settings_audio_language_auto)- val audioLanguageOptions = remember(autoLabel) { supportedAudioLanguages(autoLabel) }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_audio_language),- onDismiss = { showAudioLanguageDialog = false }- ) {- audioLanguageOptions.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.label,- currentLevel = if (uiState.preferredAudioLanguage == option.tag) index else -1,- onSelect = {- viewModel.setPreferredAudioLanguage(option.tag)- showAudioLanguageDialog = false- }- )- }- }- }-- if (showSubtitleSizeDialog) {- val subtitleSizeOptions = remember { subtitleSizeOptions() }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_subtitle_size),- onDismiss = { showSubtitleSizeDialog = false }- ) {- subtitleSizeOptions.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.label(context),- currentLevel = if (uiState.subtitleTextScale == option.scale) index else -1,- onSelect = {- viewModel.setSubtitleTextScale(option.scale)- showSubtitleSizeDialog = false- }- )- }- }- }-- if (showSubtitleTextColorDialog) {- val options = remember(context) { subtitleTextColorOptions(context) }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_subtitle_text_color),- onDismiss = { showSubtitleTextColorDialog = false }- ) {- options.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.label,- currentLevel = if (uiState.subtitleTextColor == option.colorArgb) index else -1,- onSelect = {- viewModel.setSubtitleTextColor(option.colorArgb)- showSubtitleTextColorDialog = false- }- )- }- }- }-- if (showSubtitleBackgroundDialog) {- val options = remember(context) { subtitleBackgroundColorOptions(context) }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_subtitle_background),- onDismiss = { showSubtitleBackgroundDialog = false }- ) {- options.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.label,- currentLevel = if (uiState.subtitleBackgroundColor == option.colorArgb) index else -1,- onSelect = {- viewModel.setSubtitleBackgroundColor(option.colorArgb)- showSubtitleBackgroundDialog = false- }- )- }- }- }-- if (showWifiQualityDialog) {- QualityCapSelectionDialog(- title = stringResource(R.string.settings_select_wifi_quality_cap),- currentValue = uiState.wifiMaxVideoHeight,- onDismiss = { showWifiQualityDialog = false },- onSelect = {- viewModel.setWifiQualityCap(it)- showWifiQualityDialog = false- }- )- }-- if (showEthernetQualityDialog) {- QualityCapSelectionDialog(- title = stringResource(R.string.settings_select_ethernet_quality_cap),- currentValue = uiState.ethernetMaxVideoHeight,- onDismiss = { showEthernetQualityDialog = false },- onSelect = {- viewModel.setEthernetQualityCap(it)- showEthernetQualityDialog = false- }- )- }-- categorySortDialogType?.let { typeName ->- val type = ContentType.entries.firstOrNull { it.name == typeName }- if (type != null) {- CategorySortModeDialog(- type = type,- currentMode = uiState.categorySortModes[type] ?: CategorySortMode.DEFAULT,- onDismiss = { categorySortDialogType = null },- onModeSelected = { mode ->- viewModel.setCategorySortMode(type, mode)- categorySortDialogType = null- }- )- }- }-- if (showPinDialog) {- PinDialog(- onDismissRequest = {- showPinDialog = false- pinError = null- if (pendingAction == ParentalAction.SetNewPin) {- pendingAction = null- pendingProtectionLevel = null- }- },- onPinEntered = { pin ->- scope.launch {- if (pendingAction == ParentalAction.SetNewPin) {- viewModel.changePin(pin)- pendingProtectionLevel?.let(viewModel::setParentalControlLevel)- pendingProtectionLevel = null- showPinDialog = false- pendingAction = null- } else {- if (viewModel.verifyPin(pin)) {- showPinDialog = false- pinError = null- when (pendingAction) {- ParentalAction.ChangeLevel -> showLevelDialog = true- ParentalAction.ChangePin -> {- pendingAction = ParentalAction.SetNewPin- showPinDialog = true- }- else -> pendingAction = null- }- } else {- pinError = context.getString(R.string.home_incorrect_pin)- }- }- }- },- title = if (pendingAction == ParentalAction.SetNewPin) stringResource(R.string.settings_enter_new_pin) else stringResource(R.string.settings_enter_pin),- error = pinError- )- }-- if (showLevelDialog) {- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_level),- onDismiss = { showLevelDialog = false }- ) {- LevelOption(0, stringResource(R.string.settings_level_off_desc), uiState.parentalControlLevel) {- viewModel.setParentalControlLevel(0)- showLevelDialog = false- }- LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {- if (uiState.hasParentalPin) {- viewModel.setParentalControlLevel(1)- } else {- pendingProtectionLevel = 1- pendingAction = ParentalAction.SetNewPin- showPinDialog = true- }- showLevelDialog = false- }- LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {- if (uiState.hasParentalPin) {- viewModel.setParentalControlLevel(2)- } else {- pendingProtectionLevel = 2- pendingAction = ParentalAction.SetNewPin- showPinDialog = true- }- showLevelDialog = false- }- }- }-- if (showLanguageDialog) {- val systemDefaultLabel = stringResource(R.string.settings_system_default)- val languageOptions = remember(systemDefaultLabel) { supportedAppLanguages(systemDefaultLabel) }- PremiumSelectionDialog(- title = stringResource(R.string.settings_select_language),- onDismiss = { showLanguageDialog = false }- ) {- languageOptions.forEachIndexed { index, option ->- LevelOption(- level = index,- text = option.label,- currentLevel = if (uiState.appLanguage == option.tag) index else -1,- onSelect = {- viewModel.setAppLanguage(option.tag)- showLanguageDialog = false- }- )- }- }- }-- val backupPreview = uiState.backupPreview- if (backupPreview != null && uiState.pendingBackupUri != null) {- BackupImportPreviewDialog(- preview = backupPreview,- plan = uiState.backupImportPlan,- onDismiss = { viewModel.dismissBackupPreview() },- onStrategySelected = { viewModel.setBackupConflictStrategy(it) },- onImportPreferencesChanged = { viewModel.setImportPreferences(it) },- onImportProvidersChanged = { viewModel.setImportProviders(it) },- onImportSavedLibraryChanged = { viewModel.setImportSavedLibrary(it) },- onImportPlaybackHistoryChanged = { viewModel.setImportPlaybackHistory(it) },- onImportMultiViewChanged = { viewModel.setImportMultiViewPresets(it) },- onImportRecordingSchedulesChanged = { viewModel.setImportRecordingSchedules(it) },- onConfirm = { viewModel.confirmBackupImport() }- )- }-- if (showRecordingPatternDialog) {- SimpleTextValueDialog(- title = stringResource(R.string.settings_recording_pattern_title),- subtitle = stringResource(R.string.settings_recording_pattern_hint),- initialValue = uiState.recordingStorageState.fileNamePattern,- onDismiss = { showRecordingPatternDialog = false },- onConfirm = { pattern ->- viewModel.updateRecordingFileNamePattern(pattern)- showRecordingPatternDialog = false- }- )- }-- if (showRecordingRetentionDialog) {- val retentionOptions = listOf<Int?>(null, 7, 14, 30, 60, 90)- PremiumSelectionDialog(- title = stringResource(R.string.settings_recording_retention_title),- onDismiss = { showRecordingRetentionDialog = false }- ) {- retentionOptions.forEachIndexed { index, days ->- LevelOption(- level = index,- text = if (days == null) {- stringResource(R.string.settings_recording_retention_keep_all)- } else {- stringResource(R.string.settings_recording_retention_days, days)- },- currentLevel = if (days == uiState.recordingStorageState.retentionDays) index else -1,- onSelect = {- viewModel.updateRecordingRetentionDays(days)- showRecordingRetentionDialog = false- }- )- }- }- }-- if (showRecordingConcurrencyDialog) {- PremiumSelectionDialog(- title = stringResource(R.string.settings_recording_concurrency_title),- onDismiss = { showRecordingConcurrencyDialog = false }- ) {- (1..4).forEach { value ->- LevelOption(- level = value,- text = value.toString(),- currentLevel = if (value == uiState.recordingStorageState.maxSimultaneousRecordings) value else -1,- onSelect = {- viewModel.updateRecordingMaxSimultaneous(value)- showRecordingConcurrencyDialog = false- }- )- }- }- }-- if (showClearHistoryDialog) {- androidx.compose.material3.AlertDialog(- onDismissRequest = { showClearHistoryDialog = false },- title = { Text(text = stringResource(R.string.settings_clear_history_dialog_title)) },- text = {- Text(- text = stringResource(R.string.settings_clear_history_dialog_body),- color = OnSurface- )- },- confirmButton = {- TextButton(- onClick = {- viewModel.clearHistory()- showClearHistoryDialog = false- }- ) {- Text(text = stringResource(R.string.settings_clear_history_confirm), color = Primary)- }- },- dismissButton = {- TextButton(onClick = { showClearHistoryDialog = false }) {- Text(text = stringResource(R.string.settings_cancel), color = OnSurface)- }- },- containerColor = SurfaceElevated,- titleContentColor = OnSurface,- textContentColor = TextSecondary- )- }- }+ SettingsScreenDialogs(+ uiState = uiState,+ viewModel = viewModel,+ context = context,+ scope = scope,+ showLiveTvModeDialog = showLiveTvModeDialog,+ onShowLiveTvModeDialogChange = { showLiveTvModeDialog = it },+ showLiveTvQuickFilterVisibilityDialog = showLiveTvQuickFilterVisibilityDialog,+ onShowLiveTvQuickFilterVisibilityDialogChange = { showLiveTvQuickFilterVisibilityDialog = it },+ showLiveChannelNumberingDialog = showLiveChannelNumberingDialog,+ onShowLiveChannelNumberingDialogChange = { showLiveChannelNumberingDialog = it },+ showVodViewModeDialog = showVodViewModeDialog,+ onShowVodViewModeDialogChange = { showVodViewModeDialog = it },+ showPlaybackSpeedDialog = showPlaybackSpeedDialog,+ onShowPlaybackSpeedDialogChange = { showPlaybackSpeedDialog = it },+ showDecoderModeDialog = showDecoderModeDialog,+ onShowDecoderModeDialogChange = { showDecoderModeDialog = it },+ showControlsTimeoutDialog = showControlsTimeoutDialog,+ onShowControlsTimeoutDialogChange = { showControlsTimeoutDialog = it },+ showLiveOverlayTimeoutDialog = showLiveOverlayTimeoutDialog,+ onShowLiveOverlayTimeoutDialogChange = { showLiveOverlayTimeoutDialog = it },+ showNoticeTimeoutDialog = showNoticeTimeoutDialog,+ onShowNoticeTimeoutDialogChange = { showNoticeTimeoutDialog = it },+ showDiagnosticsTimeoutDialog = showDiagnosticsTimeoutDialog,+ onShowDiagnosticsTimeoutDialogChange = { showDiagnosticsTimeoutDialog = it },+ showLiveTvFiltersDialog = showLiveTvFiltersDialog,+ onShowLiveTvFiltersDialogChange = { showLiveTvFiltersDialog = it },+ showAudioLanguageDialog = showAudioLanguageDialog,+ onShowAudioLanguageDialogChange = { showAudioLanguageDialog = it },+ showSubtitleSizeDialog = showSubtitleSizeDialog,+ onShowSubtitleSizeDialogChange = { showSubtitleSizeDialog = it },+ showSubtitleTextColorDialog = showSubtitleTextColorDialog,+ onShowSubtitleTextColorDialogChange = { showSubtitleTextColorDialog = it },+ showSubtitleBackgroundDialog = showSubtitleBackgroundDialog,+ onShowSubtitleBackgroundDialogChange = { showSubtitleBackgroundDialog = it },+ showWifiQualityDialog = showWifiQualityDialog,+ onShowWifiQualityDialogChange = { showWifiQualityDialog = it },+ showEthernetQualityDialog = showEthernetQualityDialog,+ onShowEthernetQualityDialogChange = { showEthernetQualityDialog = it },+ categorySortDialogType = categorySortDialogType,+ onCategorySortDialogTypeChange = { categorySortDialogType = it },+ showPinDialog = showPinDialog,+ onShowPinDialogChange = { showPinDialog = it },+ showLevelDialog = showLevelDialog,+ onShowLevelDialogChange = { showLevelDialog = it },+ pinError = pinError,+ onPinErrorChange = { pinError = it },+ pendingAction = pendingAction,+ onPendingActionChange = { pendingAction = it },+ pendingProtectionLevel = pendingProtectionLevel,+ onPendingProtectionLevelChange = { pendingProtectionLevel = it },+ showLanguageDialog = showLanguageDialog,+ onShowLanguageDialogChange = { showLanguageDialog = it },+ showRecordingPatternDialog = showRecordingPatternDialog,+ onShowRecordingPatternDialogChange = { showRecordingPatternDialog = it },+ showRecordingRetentionDialog = showRecordingRetentionDialog,+ onShowRecordingRetentionDialogChange = { showRecordingRetentionDialog = it },+ showRecordingConcurrencyDialog = showRecordingConcurrencyDialog,+ onShowRecordingConcurrencyDialogChange = { showRecordingConcurrencyDialog = it },+ showClearHistoryDialog = showClearHistoryDialog,+ onShowClearHistoryDialogChange = { showClearHistoryDialog = it },+ showCreateCombinedDialog = showCreateCombinedDialog,+ onShowCreateCombinedDialogChange = { showCreateCombinedDialog = it },+ showAddCombinedMemberDialog = showAddCombinedMemberDialog,+ onShowAddCombinedMemberDialogChange = { showAddCombinedMemberDialog = it },+ showRenameCombinedDialog = showRenameCombinedDialog,+ onShowRenameCombinedDialogChange = { showRenameCombinedDialog = it },+ selectedCombinedProfileId = selectedCombinedProfileId,+ showProviderSyncDialog = showProviderSyncDialog,+ onShowProviderSyncDialogChange = { showProviderSyncDialog = it },+ showCustomProviderSyncDialog = showCustomProviderSyncDialog,+ onShowCustomProviderSyncDialogChange = { showCustomProviderSyncDialog = it },+ pendingSyncProviderId = pendingSyncProviderId,+ onPendingSyncProviderIdChange = { pendingSyncProviderId = it },+ customSyncSelections = customSyncSelections,+ onCustomSyncSelectionsChange = { customSyncSelections = it }+ )+}+}- val pendingSyncProvider = pendingSyncProviderId?.let { providerId ->- uiState.providers.firstOrNull { it.id == providerId }- }- if (showCreateCombinedDialog) {- CreateCombinedM3uDialog(- providers = uiState.availableM3uProviders,- onDismiss = { showCreateCombinedDialog = false },- onCreate = { name, providerIds ->- showCreateCombinedDialog = false- viewModel.createCombinedProfile(name, providerIds)- }- )- }- if (showRenameCombinedDialog) {- val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == selectedCombinedProfileId }- if (selectedProfile != null) {- RenameCombinedM3uDialog(- profile = selectedProfile,- onDismiss = { showRenameCombinedDialog = false },- onRename = { name ->- showRenameCombinedDialog = false- viewModel.renameCombinedProfile(selectedProfile.id, name)- }- )- }- }- if (showAddCombinedMemberDialog) {- val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == selectedCombinedProfileId }- if (selectedProfile != null) {- AddCombinedProviderDialog(- profile = selectedProfile,- availableProviders = uiState.availableM3uProviders,- onDismiss = { showAddCombinedMemberDialog = false },- onAddProvider = { providerId ->- showAddCombinedMemberDialog = false- viewModel.addProviderToCombinedProfile(selectedProfile.id, providerId)- }- )- }- }- if (showProviderSyncDialog && pendingSyncProvider != null) {- ProviderSyncOptionsDialog(- provider = pendingSyncProvider,- onDismiss = {- showProviderSyncDialog = false- pendingSyncProviderId = null- },- onSelect = { selection ->- showProviderSyncDialog = false- if (selection == ProviderSyncSelection.ALL) {- viewModel.syncProviderSection(pendingSyncProvider.id, selection)- pendingSyncProviderId = null- } else if (selection == null) {- showCustomProviderSyncDialog = true- } else {- viewModel.syncProviderSection(pendingSyncProvider.id, selection)- pendingSyncProviderId = null- }- }- )- }- if (showCustomProviderSyncDialog && pendingSyncProvider != null) {- ProviderCustomSyncDialog(- provider = pendingSyncProvider,- selected = customSyncSelections,- onToggle = { option ->- customSyncSelections = if (option in customSyncSelections) {- customSyncSelections - option- } else {- customSyncSelections + option- }- },- onDismiss = {- showCustomProviderSyncDialog = false- pendingSyncProviderId = null- },- onConfirm = {- showCustomProviderSyncDialog = false- viewModel.syncProviderCustom(pendingSyncProvider.id, customSyncSelections)- pendingSyncProviderId = null- }- )- }-}--@Composable-private fun CombinedM3uProfilesCard(- profiles: List<CombinedM3uProfile>,- availableProviders: List<Provider>,- selectedProfileId: Long?,- activeLiveSource: ActiveLiveSource?,- onSelectProfile: (Long) -> Unit,- onCreateProfile: () -> Unit,- onActivateProfile: (Long) -> Unit,- onDeleteProfile: (Long) -> Unit,- onRenameProfile: (Long) -> Unit,- onAddProvider: (Long) -> Unit,- onRemoveProvider: (Long, Long) -> Unit,- onToggleProviderEnabled: (Long, Long, Boolean) -> Unit,- onMoveProvider: (Long, Long, Boolean) -> Unit-) {- Surface(- shape = RoundedCornerShape(12.dp),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier- .fillMaxWidth()- .padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text("Combined M3U", style = MaterialTheme.typography.titleMedium, color = OnSurface)- Text(- "Merge selected M3U playlists into one Live TV and EPG source.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- CompactSettingsActionChip(- label = "Create Combined",- accent = Primary,- onClick = onCreateProfile- )- }-- if (profiles.isEmpty()) {- Text("No combined M3U sources yet.", style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- } else {- LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- items(profiles, key = { it.id }) { profile ->- val isActive = (activeLiveSource as? ActiveLiveSource.CombinedM3uSource)?.profileId == profile.id- ProviderChip(- title = profile.name,- subtitle = buildString {- append("${profile.members.count { it.enabled }}/${profile.members.size} playlist(s)")- if (isActive) append(" • Active")- if (profile.members.none { it.enabled }) append(" • Empty")- },- isSelected = selectedProfileId == profile.id,- isActive = isActive,- onClick = { onSelectProfile(profile.id) }- )- }- }-- val selectedProfile = profiles.firstOrNull { it.id == selectedProfileId } ?: profiles.first()- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- FlowRow(- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- CompactSettingsActionChip(- label = "Use For Live TV",- accent = Primary,- onClick = { onActivateProfile(selectedProfile.id) }- )- CompactSettingsActionChip(- label = "Rename",- accent = OnBackground,- onClick = { onRenameProfile(selectedProfile.id) }- )- CompactSettingsActionChip(- label = "Add Playlist",- accent = OnBackground,- onClick = { onAddProvider(selectedProfile.id) }- )- CompactSettingsActionChip(- label = "Delete",- accent = ErrorColor,- onClick = { onDeleteProfile(selectedProfile.id) }- )- }-- Text(- text = "${selectedProfile.members.count { it.enabled }} of ${selectedProfile.members.size} playlists enabled",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )-- if (selectedProfile.members.isEmpty()) {- Text(- text = "This combined source has no playlists yet. Add at least one M3U playlist before using it.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- } else if (selectedProfile.members.none { it.enabled }) {- Text(- text = "All playlists in this combined source are disabled. Enable at least one to use it in Live TV.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }-- selectedProfile.members- .sortedBy { it.priority }- .forEachIndexed { index, member ->- val providerName = member.providerName.ifBlank {- availableProviders.firstOrNull { it.id == member.providerId }?.name ?: "Playlist ${member.providerId}"- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f)) {- Text(providerName, style = MaterialTheme.typography.bodyMedium, color = OnSurface)- Text(- if (member.enabled) "Enabled in merged source" else "Disabled in merged source",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {- CompactSettingsActionChip(- label = "Up",- accent = OnBackground,- enabled = index > 0,- onClick = { onMoveProvider(selectedProfile.id, member.providerId, true) }- )- CompactSettingsActionChip(- label = "Down",- accent = OnBackground,- enabled = index < selectedProfile.members.lastIndex,- onClick = { onMoveProvider(selectedProfile.id, member.providerId, false) }- )- Switch(- checked = member.enabled,- onCheckedChange = { onToggleProviderEnabled(selectedProfile.id, member.providerId, it) }- )- CompactSettingsActionChip(- label = "Remove",- accent = ErrorColor,- onClick = { onRemoveProvider(selectedProfile.id, member.providerId) }- )- }- }- }- }- }- }- }-}--@Composable-private fun RenameCombinedM3uDialog(- profile: CombinedM3uProfile,- onDismiss: () -> Unit,- onRename: (String) -> Unit-) {- var name by rememberSaveable(profile.id) { mutableStateOf(profile.name) }-- PremiumDialog(- title = "Rename Combined M3U",- subtitle = "Update the name shown in Live TV and provider settings.",- onDismissRequest = onDismiss,- widthFraction = 0.48f,- content = {- EpgSourceTextField(- value = name,- onValueChange = { updated -> name = updated },- placeholder = "Combined source name"- )- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = "Save",- onClick = { onRename(name.trim()) },- enabled = name.isNotBlank(),- emphasized = true- )- }- )-}--@Composable-private fun CreateCombinedM3uDialog(- providers: List<Provider>,- onDismiss: () -> Unit,- onCreate: (String, List<Long>) -> Unit-) {- var name by rememberSaveable { mutableStateOf("") }- var selectedProviderIds by rememberSaveable { mutableStateOf(setOf<Long>()) }- val m3uProviders = remember(providers) { providers.filter { it.type == ProviderType.M3U } }- val effectiveName = remember(name, selectedProviderIds, m3uProviders) {- val manualName = name.trim()- if (manualName.isNotBlank()) {- manualName- } else {- val selectedProviders = m3uProviders.filter { it.id in selectedProviderIds }- when {- selectedProviders.isEmpty() -> ""- selectedProviders.size == 1 -> "${selectedProviders.first().name} Mix"- selectedProviders.size == 2 -> "${selectedProviders[0].name} + ${selectedProviders[1].name}"- else -> "${selectedProviders.first().name} + ${selectedProviders.size - 1} More"- }- }- }-- PremiumDialog(- title = "Create Combined M3U",- subtitle = "Pick the M3U playlists you want to browse together in Live TV and guide.",- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- EpgSourceTextField(- value = name,- onValueChange = { updated -> name = updated },- placeholder = effectiveName.ifBlank { "Combined source name" }- )-- if (m3uProviders.isEmpty()) {- Text(- text = "No M3U playlists are available yet. Add at least one playlist first.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- } else {- Column(- modifier = Modifier- .fillMaxWidth()- .heightIn(max = 360.dp)- .verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- m3uProviders.forEach { provider ->- val isSelected = provider.id in selectedProviderIds- TvClickableSurface(- onClick = {- selectedProviderIds = if (isSelected) {- selectedProviderIds - provider.id- } else {- selectedProviderIds + provider.id- }- },- modifier = Modifier.fillMaxWidth(),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.04f),- focusedContainerColor = Primary.copy(alpha = 0.24f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 14.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = provider.name,- style = MaterialTheme.typography.bodyMedium,- color = OnSurface- )- Text(- text = if (isSelected) "Included in this combined source" else "Press to include this playlist",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Checkbox(- checked = isSelected,- onCheckedChange = null- )- }- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = "Create",- onClick = { onCreate(effectiveName, selectedProviderIds.toList()) },- enabled = selectedProviderIds.isNotEmpty() && effectiveName.isNotBlank(),- emphasized = true- )- }- )-}--@Composable-private fun AddCombinedProviderDialog(- profile: CombinedM3uProfile,- availableProviders: List<Provider>,- onDismiss: () -> Unit,- onAddProvider: (Long) -> Unit-) {- val candidateProviders = remember(profile, availableProviders) {- availableProviders.filter { provider -> profile.members.none { it.providerId == provider.id } }- }- var selectedProviderId by rememberSaveable(profile.id) { mutableStateOf(candidateProviders.firstOrNull()?.id) }- PremiumDialog(- title = "Add Playlist To ${profile.name}",- subtitle = "Select another M3U playlist to include in this combined source.",- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- if (candidateProviders.isEmpty()) {- Text(- text = "All M3U playlists are already in this combined source.",- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- } else {- Column(- modifier = Modifier- .fillMaxWidth()- .heightIn(max = 320.dp)- .verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- candidateProviders.forEach { provider ->- val isSelected = selectedProviderId == provider.id- TvClickableSurface(- onClick = { selectedProviderId = provider.id },- modifier = Modifier.fillMaxWidth(),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.White.copy(alpha = 0.04f),- focusedContainerColor = Primary.copy(alpha = 0.22f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- border = BorderStroke(- 1.dp,- if (isSelected) Primary.copy(alpha = 0.4f) else Color.White.copy(alpha = 0.08f)- ),- shape = RoundedCornerShape(12.dp)- ),- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(12.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 14.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = provider.name,- style = MaterialTheme.typography.bodyMedium,- color = OnSurface,- modifier = Modifier.weight(1f)- )- RadioButton(- selected = isSelected,- onClick = { selectedProviderId = provider.id }- )- }- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = "Add",- onClick = { selectedProviderId?.let(onAddProvider) },- enabled = selectedProviderId != null && candidateProviders.isNotEmpty(),- emphasized = true- )- }- )-}--@Composable-private fun ProviderChip(- title: String,- subtitle: String,- isSelected: Boolean,- isActive: Boolean,- onClick: () -> Unit-) {- TvClickableSurface(- onClick = onClick,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.16f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.24f)- )- ) {- Column(modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp)) {- Text(title, style = MaterialTheme.typography.bodyMedium, color = OnSurface)- Text(- if (isActive) "$subtitle • Active" else subtitle,- style = MaterialTheme.typography.bodySmall,- color = if (isActive) Primary else OnSurfaceDim- )- }- }-}--private fun availableSyncSelections(provider: Provider): List<ProviderSyncSelection> = buildList {- add(ProviderSyncSelection.TV)- add(ProviderSyncSelection.MOVIES)- if (provider.type == ProviderType.XTREAM_CODES) {- add(ProviderSyncSelection.SERIES)- }- add(ProviderSyncSelection.EPG)-}--@Composable-private fun ProviderSyncOptionsDialog(- provider: Provider,- onDismiss: () -> Unit,- onSelect: (ProviderSyncSelection?) -> Unit-) {- PremiumDialog(- onDismissRequest = onDismiss,- title = stringResource(R.string.settings_sync_dialog_title, provider.name),- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- Text(- text = stringResource(R.string.settings_sync_dialog_subtitle),- style = MaterialTheme.typography.bodyMedium,- color = OnSurface- )- SyncOptionButton(stringResource(R.string.settings_sync_option_all)) {- onSelect(ProviderSyncSelection.ALL)- }- availableSyncSelections(provider).forEach { option ->- SyncOptionButton(text = syncSelectionLabel(option)) {- onSelect(option)- }- }- OutlinedButton(- onClick = { onSelect(null) },- modifier = Modifier.fillMaxWidth()- ) {- Text(stringResource(R.string.settings_sync_option_custom))- }- }- }- )-}--@Composable-private fun ProviderCustomSyncDialog(- provider: Provider,- selected: Set<ProviderSyncSelection>,- onToggle: (ProviderSyncSelection) -> Unit,- onDismiss: () -> Unit,- onConfirm: () -> Unit-) {- PremiumDialog(- onDismissRequest = onDismiss,- title = stringResource(R.string.settings_sync_custom_title, provider.name),- content = {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(- text = stringResource(R.string.settings_sync_custom_subtitle),- style = MaterialTheme.typography.bodyMedium,- color = OnSurface- )- availableSyncSelections(provider).forEach { option ->- Row(- modifier = Modifier- .fillMaxWidth()- .clickable { onToggle(option) }- .padding(vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(12.dp)- ) {- Checkbox(- checked = option in selected,- onCheckedChange = { onToggle(option) }- )- Text(- text = syncSelectionLabel(option),- style = MaterialTheme.typography.bodyLarge,- color = OnBackground- )- }- }- }- },- footer = {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)- ) {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = stringResource(R.string.settings_sync_btn),- onClick = onConfirm,- enabled = selected.isNotEmpty()- )- }- }- )-}--@Composable-private fun SyncOptionButton(- text: String,- onClick: () -> Unit-) {- TvButton(- onClick = onClick,- modifier = Modifier.fillMaxWidth()- ) {- Text(text)- }-}--@Composable-private fun syncSelectionLabel(selection: ProviderSyncSelection): String = when (selection) {- ProviderSyncSelection.ALL -> stringResource(R.string.settings_sync_option_all)- ProviderSyncSelection.FAST -> stringResource(R.string.settings_sync_option_fast)- ProviderSyncSelection.TV -> stringResource(R.string.settings_sync_option_tv)- ProviderSyncSelection.MOVIES -> stringResource(R.string.settings_sync_option_movies)- ProviderSyncSelection.SERIES -> stringResource(R.string.settings_sync_option_series)- ProviderSyncSelection.EPG -> stringResource(R.string.settings_sync_option_epg)-}--private enum class ParentalAction {- ChangeLevel, ChangePin, SetNewPin-}--@Composable-private fun PremiumSelectionDialog(- title: String,- onDismiss: () -> Unit,- content: @Composable ColumnScope.() -> Unit-) {- val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()- Dialog(onDismissRequest = onDismiss) {- val dialogContent: @Composable (Modifier) -> Unit = { resolvedModifier ->- androidx.compose.material3.Surface(- shape = RoundedCornerShape(14.dp),- color = SurfaceElevated,- modifier = resolvedModifier- .border(1.dp, Primary.copy(alpha = 0.4f), RoundedCornerShape(14.dp))- ) {- Column(- modifier = Modifier.padding(18.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.titleMedium,- color = Primary- )- HorizontalDivider(color = Color.White.copy(alpha = 0.1f))- Column(- verticalArrangement = Arrangement.spacedBy(6.dp),- modifier = Modifier.padding(top = 6.dp)- ) {- content()- }- Row(- modifier = Modifier.fillMaxWidth().padding(top = 8.dp),- horizontalArrangement = Arrangement.End- ) {- TvClickableSurface(- onClick = onDismiss,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.2f),- focusedContainerColor = Primary.copy(alpha = 0.4f)- )- ) {- Text(- text = stringResource(R.string.settings_cancel),- style = MaterialTheme.typography.labelMedium,- color = Primary,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)- )- }- }- }- }- }-- if (isTelevisionDevice) {- dialogContent(Modifier.fillMaxWidth(0.62f))- } else {- BoxWithConstraints(- modifier = Modifier.fillMaxWidth(),- contentAlignment = Alignment.Center- ) {- val dialogWidthFraction = when {- maxWidth < 700.dp -> 0.92f- maxWidth < 1000.dp -> 0.78f- else -> 0.62f- }- dialogContent(Modifier.fillMaxWidth(dialogWidthFraction))- }- }- }-}--@Composable-private fun TimeoutValueDialog(- title: String,- subtitle: String,- initialValue: Int,- onDismiss: () -> Unit,- onConfirm: (Int) -> Unit-) {- var value by rememberSaveable(initialValue) { mutableStateOf(initialValue.toString()) }- val parsedValue = value.toIntOrNull()- val isValid = parsedValue != null && parsedValue in 2..60-- PremiumDialog(- title = title,- subtitle = subtitle,- onDismissRequest = onDismiss,- widthFraction = 0.42f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- Text(- text = stringResource(R.string.settings_timeout_seconds_label),- style = MaterialTheme.typography.bodyMedium,- color = OnSurface- )- NumericSettingsTextField(- value = value,- onValueChange = { updated -> value = updated.filter(Char::isDigit).take(2) },- placeholder = stringResource(R.string.settings_timeout_seconds_placeholder)- )- Text(- text = if (isValid) {- formatTimeoutSecondsLabel(parsedValue ?: initialValue, androidx.compose.ui.platform.LocalContext.current)- } else {- stringResource(R.string.settings_timeout_validation)- },- style = MaterialTheme.typography.bodySmall,- color = if (isValid) OnSurfaceDim else Color(0xFFFF8A80)- )- }- },- footer = {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End)- ) {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = stringResource(R.string.settings_timeout_apply),- onClick = { parsedValue?.let(onConfirm) },- enabled = isValid- )- }- }- )-}--@Composable-private fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: () -> Unit) {- Row(- modifier = Modifier- .fillMaxWidth()- .clickable(onClick = onSelect)- .padding(vertical = 12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- RadioButton(- selected = level == currentLevel,- onClick = onSelect- )- Spacer(modifier = Modifier.width(8.dp))- Text(text, style = MaterialTheme.typography.bodyMedium, color = OnBackground)- }-}--@Composable-private fun NumericSettingsTextField(- value: String,- onValueChange: (String) -> Unit,- placeholder: String-) {- val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()- val focusRequester = remember { FocusRequester() }- val keyboardController = LocalSoftwareKeyboardController.current- var hasContainerFocus by remember { mutableStateOf(false) }- var hasInputFocus by remember { mutableStateOf(false) }- var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }- var pendingInputActivation by remember { mutableStateOf(false) }- var fieldValue by remember {- mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))- }- val isFocused = hasContainerFocus || hasInputFocus-- LaunchedEffect(value) {- if (value != fieldValue.text) {- fieldValue = TextFieldValue(text = value, selection = TextRange(value.length))- }- }-- LaunchedEffect(acceptsInput, pendingInputActivation) {- if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) return@LaunchedEffect- focusRequester.requestFocus()- keyboardController?.show()- pendingInputActivation = false- }-- TvClickableSurface(- onClick = {- if (!isTelevisionDevice) {- focusRequester.requestFocus()- keyboardController?.show()- return@TvClickableSurface- }- acceptsInput = true- pendingInputActivation = true- },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.08f),- focusedContainerColor = Color.White.copy(alpha = 0.12f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .onFocusChanged { hasContainerFocus = it.isFocused }- ) {- Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {- if (value.isEmpty() && !isFocused) {- Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)- }- BasicTextField(- value = fieldValue,- onValueChange = { updatedValue ->- val digitsOnly = updatedValue.text.filter(Char::isDigit).take(2)- fieldValue = updatedValue.copy(- text = digitsOnly,- selection = TextRange(digitsOnly.length.coerceAtMost(digitsOnly.length))- )- if (digitsOnly != value) {- onValueChange(digitsOnly)- }- },- textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),- singleLine = true,- cursorBrush = SolidColor(Primary),- keyboardOptions = KeyboardOptions(- keyboardType = KeyboardType.Number,- imeAction = ImeAction.Done- ),- keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .focusProperties {- canFocus = !isTelevisionDevice || acceptsInput- if (isTelevisionDevice && acceptsInput) {- left = FocusRequester.Cancel- right = FocusRequester.Cancel- }- }- .onFocusChanged {- hasInputFocus = it.isFocused- if (!it.isFocused) {- if (isTelevisionDevice) {- acceptsInput = false- }- keyboardController?.hide()- }- },- readOnly = isTelevisionDevice && !acceptsInput- )- }- }-}--@Composable-private fun QualityCapSelectionDialog(- title: String,- currentValue: Int?,- onDismiss: () -> Unit,- onSelect: (Int?) -> Unit-) {- val context = androidx.compose.ui.platform.LocalContext.current- val options = remember(context) {- listOf<Int?>(null, 2160, 1080, 720, 480)- }- PremiumSelectionDialog(- title = title,- onDismiss = onDismiss- ) {- options.forEachIndexed { index, option ->- LevelOption(- level = index,- text = formatQualityCapLabel(option, context.getString(R.string.settings_quality_cap_auto)),- currentLevel = if (option == currentValue) index else -1,- onSelect = { onSelect(option) }- )- }- }-}--@Composable-private fun CategorySortModeDialog(- type: ContentType,- currentMode: CategorySortMode,- onDismiss: () -> Unit,- onModeSelected: (CategorySortMode) -> Unit-) {- val context = androidx.compose.ui.platform.LocalContext.current- PremiumDialog(- title = categoryTypeLabel(type, context),- subtitle = categoryTypeDescription(type, context),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- CategorySortMode.entries.forEach { mode ->- TvClickableSurface(- onClick = { onModeSelected(mode) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (mode == currentMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = formatCategorySortModeLabel(mode, context),- style = MaterialTheme.typography.titleSmall,- color = if (mode == currentMode) Primary else OnBackground- )- Text(- text = sortModeLabel(mode, context),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun ParentalControlCard(- level: Int,- hasParentalPin: Boolean,- hasActiveProvider: Boolean,- onChangeLevel: () -> Unit,- onChangePin: () -> Unit-) {- Column(- modifier = Modifier- .fillMaxWidth()- .background(SurfaceElevated, RoundedCornerShape(8.dp))- .padding(16.dp),- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column {- Text(stringResource(R.string.settings_protection_level), style = MaterialTheme.typography.bodyLarge, color = OnBackground)- Text(- text = when(level) {- 0 -> stringResource(R.string.settings_level_off)- 1 -> stringResource(R.string.settings_level_locked)- 2 -> stringResource(R.string.settings_level_hidden)- else -> stringResource(R.string.settings_level_unknown)- },- style = MaterialTheme.typography.bodyMedium,- color = if (level == 0) ErrorColor else Primary- )- }-- // Custom Focusable Button for "Change"- TvClickableSurface(- onClick = onChangeLevel,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.2f),- focusedContainerColor = Secondary.copy(alpha = 0.5f),- contentColor = Secondary,- focusedContentColor = Secondary- )- ) {- Text(- text = stringResource(R.string.settings_change),- style = MaterialTheme.typography.labelMedium,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- }-- HorizontalDivider(color = Color.White.copy(alpha = 0.1f))-- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(stringResource(R.string.settings_parental_pin), style = MaterialTheme.typography.bodyLarge, color = OnBackground)-- // Custom Focusable Button for "Change PIN"- TvClickableSurface(- onClick = onChangePin,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.2f),- focusedContainerColor = Primary.copy(alpha = 0.5f),- contentColor = Primary,- focusedContentColor = Primary- )- ) {- Text(- text = stringResource(if (hasParentalPin) R.string.settings_change_pin else R.string.settings_set_pin),- style = MaterialTheme.typography.labelMedium,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- }- }-}--@Composable-private fun ProviderSettingsCard(- provider: Provider,- isActive: Boolean,- isSyncing: Boolean,- diagnostics: ProviderDiagnosticsUiModel?,- syncWarnings: List<String>,- onRetryWarningAction: (ProviderWarningAction) -> Unit,- onConnect: () -> Unit,- onRefresh: () -> Unit,- onDelete: () -> Unit,- onEdit: () -> Unit,- onParentalControl: () -> Unit,- onToggleM3uVodClassification: (Boolean) -> Unit,- onRefreshM3uClassification: () -> Unit-) {- val context = androidx.compose.ui.platform.LocalContext.current- // Use Column layout - provider info + buttons below as separate focusable items- Column(- modifier = Modifier- .fillMaxWidth()- .background(- color = if (isActive) SurfaceHighlight else SurfaceElevated,- shape = RoundedCornerShape(8.dp)- )- .border(- width = if (isActive) 2.dp else 0.dp,- color = if (isActive) Primary else Color.Transparent,- shape = RoundedCornerShape(8.dp)- )- .padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- // Provider info- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column {- Text(- text = provider.name,- style = MaterialTheme.typography.bodyLarge,- color = OnBackground- )- Text(- text = provider.type.name,- style = MaterialTheme.typography.bodySmall,- color = OnSurface- )- }- ProviderStatusBadge(status = provider.status)- if (isActive) {- Text(- text = stringResource(R.string.settings_active),- style = MaterialTheme.typography.labelSmall,- color = Primary,- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,- modifier = Modifier- .background(Primary.copy(alpha = 0.1f), RoundedCornerShape(4.dp))- .padding(horizontal = 8.dp, vertical = 4.dp)- )- }- }-- // Expiration Date- val expDate = provider.expirationDate- val expirationText = remember(expDate) {- when (expDate) {- null -> context.getString(R.string.settings_expiration_unknown)- Long.MAX_VALUE -> context.getString(R.string.settings_expiration_never)- else -> context.getString(R.string.settings_expires, java.text.SimpleDateFormat("d MMM yyyy", java.util.Locale.getDefault()).format(java.util.Date(expDate)))- }- }- Text(- text = expirationText,- style = MaterialTheme.typography.bodySmall,- color = if (expDate != null && expDate < System.currentTimeMillis() && expDate != Long.MAX_VALUE) ErrorColor else OnSurfaceDim- )-- diagnostics?.let { model ->- Text(- text = listOf(model.sourceLabel, model.connectionSummary, model.expirySummary)- .filter { it.isNotBlank() }- .joinToString(" • "),- style = MaterialTheme.typography.bodySmall,- color = OnSurface- )- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_live), count = model.liveCount)- ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_movies), count = model.movieCount)- if (provider.type == ProviderType.XTREAM_CODES) {- ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_series), count = model.seriesCount)- }- ProviderCompactStat(title = stringResource(R.string.settings_diagnostic_epg), count = model.epgCount)- }-- ProviderDiagnosticsPanel(- provider = provider,- diagnostics = model- )- }-- if (provider.type == ProviderType.M3U) {- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(10.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(10.dp))- .padding(12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = stringResource(R.string.settings_m3u_vod_classification_title),- style = MaterialTheme.typography.titleSmall,- color = OnBackground- )- Text(- text = stringResource(R.string.settings_m3u_vod_classification_summary),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Switch(- checked = provider.m3uVodClassificationEnabled,- onCheckedChange = onToggleM3uVodClassification- )- }- Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- TvClickableSurface(- onClick = onRefreshM3uClassification,- enabled = !isSyncing,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.15f),- focusedContainerColor = Primary.copy(alpha = 0.3f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = stringResource(R.string.settings_m3u_vod_classification_refresh),- style = MaterialTheme.typography.labelMedium,- color = Primary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- }- }- }-- if (syncWarnings.isNotEmpty()) {- val hasEpgWarning = syncWarnings.any { it.contains("EPG", ignoreCase = true) }- val hasMoviesWarning = syncWarnings.any { it.contains("Movies", ignoreCase = true) }- val hasSeriesWarning = syncWarnings.any { it.contains("Series", ignoreCase = true) }-- Text(- text = stringResource(R.string.settings_provider_warnings, syncWarnings.take(3).joinToString(", ")),- style = MaterialTheme.typography.bodySmall,- color = Secondary- )-- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- if (hasEpgWarning) {- TvClickableSurface(- onClick = { onRetryWarningAction(ProviderWarningAction.EPG) },- enabled = !isSyncing,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.16f),- focusedContainerColor = Secondary.copy(alpha = 0.35f)- )- ) {- Text(- text = stringResource(R.string.settings_retry_epg),- style = MaterialTheme.typography.labelSmall,- color = Secondary,- modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)- )- }- }- if (hasMoviesWarning) {- TvClickableSurface(- onClick = { onRetryWarningAction(ProviderWarningAction.MOVIES) },- enabled = !isSyncing,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.16f),- focusedContainerColor = Secondary.copy(alpha = 0.35f)- )- ) {- Text(- text = stringResource(R.string.settings_retry_movies),- style = MaterialTheme.typography.labelSmall,- color = Secondary,- modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)- )- }- }- if (hasSeriesWarning && provider.type == ProviderType.XTREAM_CODES) {- TvClickableSurface(- onClick = { onRetryWarningAction(ProviderWarningAction.SERIES) },- enabled = !isSyncing,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.16f),- focusedContainerColor = Secondary.copy(alpha = 0.35f)- )- ) {- Text(- text = stringResource(R.string.settings_retry_series),- style = MaterialTheme.typography.labelSmall,- color = Secondary,- modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)- )- }- }- }- }-- // Action buttons - each independently focusable for d-pad- Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- if (!isActive) {- TvClickableSurface(- onClick = onConnect,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary,- focusedContainerColor = Primary.copy(alpha = 0.8f),- contentColor = Color.White- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(6.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = stringResource(R.string.settings_connect),- style = MaterialTheme.typography.labelMedium,- color = Color.White,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- } else {- TvClickableSurface(- onClick = onRefresh,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.2f),- focusedContainerColor = Primary.copy(alpha = 0.5f)- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(6.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = if (isSyncing) stringResource(R.string.settings_syncing_btn) else stringResource(R.string.settings_sync_btn),- style = MaterialTheme.typography.labelMedium,- color = Primary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- }-- TvClickableSurface(- onClick = onEdit,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.2f),- focusedContainerColor = Secondary.copy(alpha = 0.5f)- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(6.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = stringResource(R.string.settings_edit),- style = MaterialTheme.typography.labelMedium,- color = Secondary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }-- TvClickableSurface(- onClick = onDelete,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = ErrorColor.copy(alpha = 0.2f),- focusedContainerColor = ErrorColor.copy(alpha = 0.5f)- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(6.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = stringResource(R.string.settings_delete),- style = MaterialTheme.typography.labelMedium,- color = ErrorColor,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }-- if (isActive) {- TvClickableSurface(- onClick = onParentalControl,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(6.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.15f),- focusedContainerColor = Primary.copy(alpha = 0.3f)- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(6.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = stringResource(R.string.settings_provider_category_controls_action),- style = MaterialTheme.typography.labelMedium,- color = Primary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }- }- }-- }-}--@Composable-private fun ProviderSelectorTab(- provider: Provider,- isSelected: Boolean,- isActive: Boolean,- onClick: () -> Unit-) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = onClick,- modifier = Modifier- .focusRequester(focusRequester)- .mouseClickable(- focusRequester = focusRequester,- onClick = onClick- ),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.34f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- border = androidx.compose.foundation.BorderStroke(- width = 1.dp,- color = if (isSelected) Primary.copy(alpha = 0.45f) else Color.White.copy(alpha = 0.08f)- )- ),- focusedBorder = Border(- border = androidx.compose.foundation.BorderStroke(- width = 2.dp,- color = Primary- )- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Column(- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = provider.name,- style = MaterialTheme.typography.labelLarge,- color = OnBackground,- fontWeight = FontWeight.Bold,- maxLines = 1- )- Text(- text = provider.type.name,- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- }- if (isActive) {- Text(- text = stringResource(R.string.settings_active),- style = MaterialTheme.typography.labelSmall,- color = Primary,- fontWeight = FontWeight.Bold- )- }- }- }-}--@Composable-private fun ProviderCompactStat(- title: String,- count: Int-) {- Surface(- shape = RoundedCornerShape(10.dp),- colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.06f))- ) {- Column(- modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),- verticalArrangement = Arrangement.spacedBy(2.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- Text(- text = count.toString(),- style = MaterialTheme.typography.labelMedium,- color = OnBackground- )- }- }-}--@Composable-private fun ProviderStatusBadge(status: ProviderStatus) {- val (label, color) = when (status) {- ProviderStatus.ACTIVE -> stringResource(R.string.settings_status_active) to Primary- ProviderStatus.PARTIAL -> stringResource(R.string.settings_status_partial) to Secondary- ProviderStatus.ERROR -> stringResource(R.string.settings_status_error) to ErrorColor- ProviderStatus.EXPIRED -> stringResource(R.string.settings_status_expired) to ErrorColor- ProviderStatus.DISABLED -> stringResource(R.string.settings_status_disabled) to OnSurfaceDim- ProviderStatus.UNKNOWN -> stringResource(R.string.settings_status_unknown) to OnSurfaceDim- }-- Text(- text = label,- style = MaterialTheme.typography.labelSmall,- color = color,- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,- modifier = Modifier- .background(color.copy(alpha = 0.16f), RoundedCornerShape(4.dp))- .padding(horizontal = 8.dp, vertical = 4.dp)- )-}--@Composable-private fun SettingsOverviewCard(- activeProviderName: String,- providerCount: Int,- protectionSummary: String,- languageLabel: String-) {- Surface(- modifier = Modifier.fillMaxWidth(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(16.dp)- ) {- Column(- modifier = Modifier.padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)- ) {- Text(- text = stringResource(R.string.settings_overview_title),- style = MaterialTheme.typography.titleLarge,- color = OnBackground- )- Text(- text = stringResource(R.string.settings_overview_subtitle),- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp)- ) {- SettingsOverviewStat(- modifier = Modifier.weight(1f),- label = stringResource(R.string.settings_overview_provider_label),- value = activeProviderName- )- SettingsOverviewStat(- modifier = Modifier.weight(1f),- label = stringResource(R.string.settings_overview_count_label),- value = providerCount.toString()- )- SettingsOverviewStat(- modifier = Modifier.weight(1f),- label = stringResource(R.string.settings_overview_protection_label),- value = protectionSummary- )- SettingsOverviewStat(- modifier = Modifier.weight(1f),- label = stringResource(R.string.settings_overview_language_label),- value = languageLabel- )- }- }-- }-}--@Composable-private fun ProviderDiagnosticsPanel(- provider: Provider,- diagnostics: ProviderDiagnosticsUiModel-) {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- Text(- text = stringResource(R.string.settings_provider_diagnostics_title),- style = MaterialTheme.typography.titleSmall,- color = Primary- )- Text(- text = diagnostics.capabilitySummary,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- Text(- text = stringResource(R.string.diagnostics_summary_format, diagnostics.sourceLabel, diagnostics.connectionSummary),- style = MaterialTheme.typography.bodySmall,- color = OnSurface- )- Text(- text = diagnostics.expirySummary,- style = MaterialTheme.typography.bodySmall,- color = OnSurface- )- Text(- text = diagnostics.archiveSummary,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- ProviderDiagnosticPill(- title = stringResource(R.string.settings_diagnostic_live),- count = diagnostics.liveCount,- timestamp = diagnostics.lastLiveSync- )- ProviderDiagnosticPill(- title = stringResource(R.string.settings_diagnostic_movies),- count = diagnostics.movieCount,- timestamp = diagnostics.lastMovieSync- )- if (provider.type == ProviderType.XTREAM_CODES) {- ProviderDiagnosticPill(- title = stringResource(R.string.settings_diagnostic_series),- count = diagnostics.seriesCount,- timestamp = diagnostics.lastSeriesSync- )- }- ProviderDiagnosticPill(- title = stringResource(R.string.settings_diagnostic_epg),- count = diagnostics.epgCount,- timestamp = diagnostics.lastEpgSync- )- }- Text(- text = stringResource(R.string.settings_diagnostic_status, diagnostics.lastSyncStatus),- style = MaterialTheme.typography.labelSmall,- color = OnSurface- )- }-}--@Composable-private fun ProviderDiagnosticPill(- title: String,- count: Int,- timestamp: Long-) {- val syncLabel = remember(timestamp) {- if (timestamp <= 0L) {- null- } else {- java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(timestamp))- }- }- Surface(- shape = RoundedCornerShape(10.dp),- colors = SurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.06f)- )- ) {- Column(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- Text(- text = stringResource(R.string.settings_diagnostic_items, count),- style = MaterialTheme.typography.labelLarge,- color = OnBackground- )- Text(- text = syncLabel ?: stringResource(R.string.settings_diagnostic_never),- style = MaterialTheme.typography.labelSmall,- color = OnSurface- )- }- }-}--@Composable-private fun SettingsOverviewStat(- label: String,- value: String,- modifier: Modifier = Modifier-) {- Column(- modifier = modifier- .background(SurfaceHighlight.copy(alpha = 0.28f), RoundedCornerShape(12.dp))- .padding(horizontal = 14.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = label.uppercase(Locale.getDefault()),- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim- )- Text(- text = value,- style = MaterialTheme.typography.titleSmall,- color = OnBackground,- fontWeight = FontWeight.SemiBold- )- }-}--@Composable-private fun LiveTvChannelModeDialog(- selectedMode: LiveTvChannelMode,- onDismiss: () -> Unit,- onModeSelected: (LiveTvChannelMode) -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_live_tv_channel_mode),- subtitle = stringResource(R.string.settings_live_tv_channel_mode_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- LiveTvChannelMode.entries.forEach { mode ->- TvClickableSurface(- onClick = { onModeSelected(mode) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = stringResource(mode.labelResId()),- style = MaterialTheme.typography.titleSmall,- color = if (mode == selectedMode) Primary else OnBackground- )- Text(- text = stringResource(mode.descriptionResId()),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun LiveTvQuickFilterVisibilityDialog(- selectedMode: LiveTvQuickFilterVisibilityMode,- onDismiss: () -> Unit,- onModeSelected: (LiveTvQuickFilterVisibilityMode) -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_live_tv_quick_filter_visibility),- subtitle = stringResource(R.string.settings_live_tv_quick_filter_visibility_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- LiveTvQuickFilterVisibilityMode.entries.forEach { mode ->- TvClickableSurface(- onClick = { onModeSelected(mode) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = stringResource(mode.labelResId()),- style = MaterialTheme.typography.titleSmall,- color = if (mode == selectedMode) Primary else OnBackground- )- Text(- text = stringResource(mode.descriptionResId()),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun SettingsSectionHeader(- title: String,- subtitle: String-) {- Column(- modifier = Modifier.fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = title,- style = MaterialTheme.typography.titleMedium,- color = Primary- )- Text(- text = subtitle,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }-}--@Composable-private fun VodViewModeDialog(- selectedMode: VodViewMode,- onDismiss: () -> Unit,- onModeSelected: (VodViewMode) -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_vod_view_mode),- subtitle = stringResource(R.string.settings_vod_view_mode_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- VodViewMode.entries.forEach { mode ->- TvClickableSurface(- onClick = { onModeSelected(mode) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = stringResource(mode.labelResId()),- style = MaterialTheme.typography.titleSmall,- color = if (mode == selectedMode) Primary else OnBackground- )- Text(- text = stringResource(mode.descriptionResId()),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun LiveChannelNumberingModeDialog(- selectedMode: ChannelNumberingMode,- onDismiss: () -> Unit,- onModeSelected: (ChannelNumberingMode) -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_live_channel_numbering_mode),- subtitle = stringResource(R.string.settings_live_channel_numbering_mode_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- content = {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- ChannelNumberingMode.entries.forEach { mode ->- TvClickableSurface(- onClick = { onModeSelected(mode) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (mode == selectedMode) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- modifier = Modifier.fillMaxWidth()- ) {- Column(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = stringResource(mode.labelResId()),- style = MaterialTheme.typography.titleSmall,- color = if (mode == selectedMode) Primary else OnBackground- )- Text(- text = stringResource(mode.descriptionResId()),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun SettingsRow(label: String, value: String) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = {},- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.15f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .mouseClickable(- focusRequester = focusRequester,- onClick = {}- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)- Text(text = value, style = MaterialTheme.typography.bodyMedium, color = OnBackground)- }- }-}--@Composable-private fun ClickableSettingsRow(label: String, value: String, onClick: () -> Unit) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = onClick,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.15f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .mouseClickable(- focusRequester = focusRequester,- onClick = onClick- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)- Text(text = value, style = MaterialTheme.typography.bodyMedium, color = Primary)- }- }-}--@Composable-private fun SwitchSettingsRow(label: String, value: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = { onCheckedChange(!checked) },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.15f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .mouseClickable(- focusRequester = focusRequester,- onClick = { onCheckedChange(!checked) }- )- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 8.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(text = label, style = MaterialTheme.typography.bodyMedium, color = OnSurface)- Text(text = value, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- }- Switch(- checked = checked,- onCheckedChange = { onCheckedChange(it) }- )- }- }-}--private fun formatLatestReleaseLabel(update: AppUpdateUiModel, context: android.content.Context): String {- val versionName = update.latestVersionName ?: return context.getString(R.string.settings_update_not_checked)- val versionCodeSuffix = update.latestVersionCode?.let { " ($it)" }.orEmpty()- return "$versionName$versionCodeSuffix"-}--private fun formatUpdateStatusLabel(update: AppUpdateUiModel, context: android.content.Context): String {- val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&- (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)- return when {- update.errorMessage != null -> context.getString(R.string.settings_update_status_check_failed)- update.downloadStatus == com.streamvault.app.update.AppUpdateDownloadStatus.Downloading -> context.getString(R.string.settings_update_status_downloading)- update.downloadStatus == com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded && downloadedReleaseMatchesLatest -> context.getString(R.string.settings_update_status_ready_to_install)- update.latestVersionName == null -> context.getString(R.string.settings_update_not_checked)- update.isUpdateAvailable -> context.getString(R.string.settings_update_status_available)- else -> context.getString(R.string.settings_update_status_current)- }-}--private fun formatUpdateCheckTimeLabel(timestamp: Long?, context: android.content.Context): String {- if (timestamp == null || timestamp <= 0L) {- return context.getString(R.string.settings_update_not_checked)- }- return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(java.util.Date(timestamp))-}--private fun shouldShowUpdateDownloadAction(update: AppUpdateUiModel): Boolean {- val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&- (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)- return when (update.downloadStatus) {- com.streamvault.app.update.AppUpdateDownloadStatus.Downloading,- com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded -> downloadedReleaseMatchesLatest || (update.isUpdateAvailable && !update.downloadUrl.isNullOrBlank())- else -> update.isUpdateAvailable && !update.downloadUrl.isNullOrBlank()- }-}--private fun formatUpdateDownloadLabel(update: AppUpdateUiModel, context: android.content.Context): String {- val downloadedReleaseMatchesLatest = update.downloadedVersionName != null &&- (update.latestVersionName == null || update.downloadedVersionName == update.latestVersionName)- return when (update.downloadStatus) {- com.streamvault.app.update.AppUpdateDownloadStatus.Downloading -> context.getString(R.string.settings_update_download_in_progress)- com.streamvault.app.update.AppUpdateDownloadStatus.Downloaded -> {- if (downloadedReleaseMatchesLatest) {- context.getString(R.string.settings_update_install_action)- } else {- context.getString(R.string.settings_update_download_action)- }- }- else -> context.getString(R.string.settings_update_download_action)- }-}--@Composable-private fun InternetSpeedTestCard(- valueLabel: String,- summary: String,- recommendationLabel: String,- isRunning: Boolean,- canApplyRecommendation: Boolean,- onRunTest: () -> Unit,- onApplyWifi: () -> Unit,- onApplyEthernet: () -> Unit-) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = onRunTest,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.18f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .padding(top = 8.dp)- .focusRequester(focusRequester)- .mouseClickable(- focusRequester = focusRequester,- onClick = onRunTest- )- ) {- Column(- modifier = Modifier.padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = stringResource(R.string.settings_speed_test_title),- style = MaterialTheme.typography.bodyLarge,- color = OnBackground- )- Text(- text = valueLabel,- style = MaterialTheme.typography.titleSmall,- color = Primary,- fontWeight = FontWeight.SemiBold- )- }- if (isRunning) {- CircularProgressIndicator(- color = Primary,- strokeWidth = 2.dp,- modifier = Modifier.size(20.dp)- )- } else {- Text(- text = stringResource(R.string.settings_speed_test_run_action),- style = MaterialTheme.typography.labelLarge,- color = Primary- )- }- }-- Text(- text = summary,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )-- Text(- text = stringResource(R.string.settings_speed_test_recommendation, recommendationLabel),- style = MaterialTheme.typography.bodySmall,- color = OnSurface- )-- Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- TvClickableSurface(- onClick = onRunTest,- enabled = !isRunning,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Primary.copy(alpha = 0.18f),- focusedContainerColor = Primary.copy(alpha = 0.32f)- )- ) {- Text(- text = stringResource(if (isRunning) R.string.settings_speed_test_running_action else R.string.settings_speed_test_run_action),- style = MaterialTheme.typography.labelMedium,- color = Primary,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)- )- }- TvClickableSurface(- onClick = onApplyWifi,- enabled = canApplyRecommendation && !isRunning,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.16f),- focusedContainerColor = Secondary.copy(alpha = 0.28f)- )- ) {- Text(- text = stringResource(R.string.settings_speed_test_apply_wifi),- style = MaterialTheme.typography.labelMedium,- color = Secondary,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)- )- }- TvClickableSurface(- onClick = onApplyEthernet,- enabled = canApplyRecommendation && !isRunning,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Secondary.copy(alpha = 0.16f),- focusedContainerColor = Secondary.copy(alpha = 0.28f)- )- ) {- Text(- text = stringResource(R.string.settings_speed_test_apply_ethernet),- style = MaterialTheme.typography.labelMedium,- color = Secondary,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)- )- }- }- }- }-}--@Composable-private fun BackupImportPreviewDialog(- preview: com.streamvault.domain.manager.BackupPreview,- plan: com.streamvault.domain.manager.BackupImportPlan,- onDismiss: () -> Unit,- onStrategySelected: (BackupConflictStrategy) -> Unit,- onImportPreferencesChanged: (Boolean) -> Unit,- onImportProvidersChanged: (Boolean) -> Unit,- onImportSavedLibraryChanged: (Boolean) -> Unit,- onImportPlaybackHistoryChanged: (Boolean) -> Unit,- onImportMultiViewChanged: (Boolean) -> Unit,- onImportRecordingSchedulesChanged: (Boolean) -> Unit,- onConfirm: () -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_backup_preview_title),- subtitle = stringResource(R.string.settings_backup_preview_subtitle, preview.version),- onDismissRequest = onDismiss,- widthFraction = 0.58f,- content = {- BackupPreviewRow(stringResource(R.string.settings_backup_section_preferences), preview.preferenceCount, 0)- BackupPreviewRow(stringResource(R.string.settings_backup_section_providers), preview.providerCount, preview.providerConflicts)- BackupPreviewRow(stringResource(R.string.settings_backup_section_saved), preview.favoriteCount + preview.groupCount + preview.protectedCategoryCount, preview.favoriteConflicts + preview.groupConflicts + preview.protectedCategoryConflicts)- BackupPreviewRow(stringResource(R.string.settings_backup_section_history), preview.playbackHistoryCount, preview.historyConflicts)- BackupPreviewRow(stringResource(R.string.settings_backup_section_multiview), preview.multiViewPresetCount, 0)- BackupPreviewRow(stringResource(R.string.settings_backup_section_recordings), preview.scheduledRecordingCount, preview.recordingConflicts)- Text(- text = stringResource(R.string.settings_backup_conflict_strategy),- style = MaterialTheme.typography.titleSmall,- color = Primary- )- Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {- BackupStrategyChip(- title = stringResource(R.string.settings_backup_keep_existing),- selected = plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING,- onClick = { onStrategySelected(BackupConflictStrategy.KEEP_EXISTING) }- )- BackupStrategyChip(- title = stringResource(R.string.settings_backup_replace_existing),- selected = plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING,- onClick = { onStrategySelected(BackupConflictStrategy.REPLACE_EXISTING) }- )- }- Text(- text = stringResource(R.string.settings_backup_import_sections),- style = MaterialTheme.typography.titleSmall,- color = Primary- )- BackupToggleRow(stringResource(R.string.settings_backup_section_preferences), plan.importPreferences, onImportPreferencesChanged)- BackupToggleRow(stringResource(R.string.settings_backup_section_providers), plan.importProviders, onImportProvidersChanged)- BackupToggleRow(stringResource(R.string.settings_backup_section_saved), plan.importSavedLibrary, onImportSavedLibraryChanged)- BackupToggleRow(stringResource(R.string.settings_backup_section_history), plan.importPlaybackHistory, onImportPlaybackHistoryChanged)- BackupToggleRow(stringResource(R.string.settings_backup_section_multiview), plan.importMultiViewPresets, onImportMultiViewChanged)- BackupToggleRow(stringResource(R.string.settings_backup_section_recordings), plan.importRecordingSchedules, onImportRecordingSchedulesChanged)- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogFooterButton(- label = stringResource(R.string.settings_backup_import_confirm),- onClick = onConfirm,- emphasized = true- )- }- )-}--@Composable-private fun BackupPreviewRow(- title: String,- itemCount: Int,- conflictCount: Int-) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column {- Text(title, style = MaterialTheme.typography.bodyLarge, color = OnBackground)- Text(- text = if (conflictCount > 0) {- stringResource(R.string.settings_backup_conflict_count, conflictCount)- } else {- stringResource(R.string.settings_backup_no_conflicts)- },- style = MaterialTheme.typography.bodySmall,- color = if (conflictCount > 0) Secondary else OnSurfaceDim- )- }- Text(- text = stringResource(R.string.settings_backup_item_count, itemCount),- style = MaterialTheme.typography.labelLarge,- color = OnBackground- )- }-}--@Composable-private fun BackupStrategyChip(- title: String,- selected: Boolean,- onClick: () -> Unit-) {- TvClickableSurface(- onClick = onClick,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(24.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.2f) else SurfaceElevated,- focusedContainerColor = Primary.copy(alpha = 0.35f)- )- ) {- Text(- text = title,- style = MaterialTheme.typography.labelLarge,- color = if (selected) Primary else OnBackground,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)- )- }-}--@Composable-private fun BackupToggleRow(- label: String,- checked: Boolean,- onCheckedChange: (Boolean) -> Unit-) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(label, style = MaterialTheme.typography.bodyLarge, color = OnBackground)- Switch(checked = checked, onCheckedChange = onCheckedChange)- }-}--@OptIn(ExperimentalLayoutApi::class)-@Composable-private fun RecordingOverviewCard(- treeLabel: String?,- outputDirectory: String?,- availableBytes: Long?,- isWritable: Boolean,- activeCount: Int,- scheduledCount: Int,- fileNamePattern: String,- retentionDays: Int?,- maxSimultaneousRecordings: Int,- onChooseFolder: () -> Unit,- onUseAppStorage: () -> Unit,- onChangePattern: () -> Unit,- onChangeRetention: () -> Unit,- onChangeConcurrency: () -> Unit,- onRepairSchedule: () -> Unit-) {- Surface(- modifier = Modifier.fillMaxWidth(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(16.dp)- ) {- Column(- modifier = Modifier.padding(20.dp),- verticalArrangement = Arrangement.spacedBy(14.dp)- ) {- Text(- text = stringResource(R.string.settings_recording_storage_title),- style = MaterialTheme.typography.titleMedium,- color = Primary- )- treeLabel?.takeIf { it.isNotBlank() }?.let {- Text(- text = it,- style = MaterialTheme.typography.bodySmall,- color = Secondary- )- }- Text(- text = outputDirectory ?: stringResource(R.string.settings_recording_storage_unknown),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp)- ) {- SettingsOverviewStat(- label = stringResource(R.string.settings_recording_active_label),- value = activeCount.toString(),- modifier = Modifier.weight(1f)- )- SettingsOverviewStat(- label = stringResource(R.string.settings_recording_scheduled_label),- value = scheduledCount.toString(),- modifier = Modifier.weight(1f)- )- SettingsOverviewStat(- label = stringResource(R.string.settings_recording_space_label),- value = availableBytes?.let(::formatBytes) ?: stringResource(R.string.settings_recording_storage_unknown),- modifier = Modifier.weight(1f)- )- }- Text(- text = if (isWritable) stringResource(R.string.settings_recording_storage_ready) else stringResource(R.string.settings_recording_storage_unavailable),- style = MaterialTheme.typography.bodySmall,- color = if (isWritable) Primary else ErrorColor- )- FlowRow(- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- RecordingMetaPill(- label = stringResource(R.string.settings_recording_pattern_title),- value = fileNamePattern- )- RecordingMetaPill(- label = stringResource(R.string.settings_recording_retention_title),- value = retentionDays?.let {- stringResource(R.string.settings_recording_retention_days, it)- } ?: stringResource(R.string.settings_recording_retention_keep_all)- )- RecordingMetaPill(- label = stringResource(R.string.settings_recording_concurrency_title),- value = maxSimultaneousRecordings.toString()- )- }- FlowRow(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp),- verticalArrangement = Arrangement.spacedBy(10.dp),- maxItemsInEachRow = 3- ) {- RecordingActionButton(stringResource(R.string.settings_recording_choose_folder), Primary, onChooseFolder)- RecordingActionButton(stringResource(R.string.settings_recording_use_app_storage), Secondary, onUseAppStorage)- RecordingActionButton(stringResource(R.string.settings_recording_pattern_title), OnBackground, onChangePattern)- RecordingActionButton(stringResource(R.string.settings_recording_retention_title), OnBackground, onChangeRetention)- RecordingActionButton(stringResource(R.string.settings_recording_concurrency_title), OnBackground, onChangeConcurrency)- RecordingActionButton(stringResource(R.string.settings_recording_reconcile), Secondary, onRepairSchedule)- }- }- }-}--@Composable-private fun RecordingItemCard(- item: RecordingItem,- onPlay: () -> Unit,- onStop: () -> Unit,- onCancel: () -> Unit,- onDelete: () -> Unit,- onRetry: () -> Unit,- onToggleSchedule: (Boolean) -> Unit-) {- Surface(- modifier = Modifier.fillMaxWidth(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(12.dp)- ) {- Column(- modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f)) {- Text(- item.programTitle ?: item.channelName,- style = MaterialTheme.typography.bodyMedium,- color = OnBackground,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- if (item.programTitle != null && item.programTitle != item.channelName) {- Text(- item.channelName,- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- }- Text(- text = when (item.status) {- RecordingStatus.SCHEDULED -> stringResource(R.string.settings_recording_status_scheduled)- RecordingStatus.RECORDING -> stringResource(R.string.settings_recording_status_recording)- RecordingStatus.COMPLETED -> stringResource(R.string.settings_recording_status_completed)- RecordingStatus.FAILED -> stringResource(R.string.settings_recording_status_failed)- RecordingStatus.CANCELLED -> stringResource(R.string.settings_recording_status_cancelled)- },- style = MaterialTheme.typography.labelMedium,- color = when (item.status) {- RecordingStatus.RECORDING -> Primary- RecordingStatus.COMPLETED -> OnBackground- RecordingStatus.FAILED -> ErrorColor- RecordingStatus.CANCELLED -> OnSurfaceDim- RecordingStatus.SCHEDULED -> Secondary- }- )- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = stringResource(- R.string.settings_recording_time_window,- formatTimestamp(item.scheduledStartMs),- formatTimestamp(item.scheduledEndMs)- ),- style = MaterialTheme.typography.labelSmall,- color = OnSurface,- maxLines = 1,- overflow = TextOverflow.Ellipsis,- modifier = Modifier.weight(1f)- )- if (item.recurrence != RecordingRecurrence.NONE) {- Spacer(modifier = Modifier.width(8.dp))- Text(- text = when (item.recurrence) {- RecordingRecurrence.DAILY -> stringResource(R.string.settings_recording_recurrence_daily)- RecordingRecurrence.WEEKLY -> stringResource(R.string.settings_recording_recurrence_weekly)- RecordingRecurrence.NONE -> stringResource(R.string.settings_recording_recurrence_none)- },- style = MaterialTheme.typography.labelSmall,- color = Secondary,- maxLines = 1- )- }- }- item.failureReason?.takeIf { it.isNotBlank() }?.let { reason ->- Text(reason, style = MaterialTheme.typography.bodySmall, color = ErrorColor)- }- FlowRow(- horizontalArrangement = Arrangement.spacedBy(6.dp),- verticalArrangement = Arrangement.spacedBy(6.dp),- modifier = Modifier.fillMaxWidth(),- maxItemsInEachRow = 4- ) {- RecordingMetaPill(- label = stringResource(R.string.settings_recording_source_label),- value = formatRecordingSourceType(item.sourceType)- )- RecordingMetaPill(- label = stringResource(R.string.settings_recording_bytes_label),- value = formatBytes(item.bytesWritten)- )- RecordingMetaPill(- label = stringResource(R.string.settings_recording_speed_label),- value = if (item.averageThroughputBytesPerSecond > 0L) {- "${formatBytes(item.averageThroughputBytesPerSecond)}/s"- } else {- "–"- }- )- if (item.retryCount > 0) {- RecordingMetaPill(- label = stringResource(R.string.settings_recording_retry_count_label),- value = item.retryCount.toString()- )- }- }- item.outputDisplayPath?.takeIf { it.isNotBlank() }?.let { output ->- Text(- text = "${stringResource(R.string.settings_recording_output_label)}: ${summarizeRecordingOutputPath(output)}",- style = MaterialTheme.typography.labelSmall,- color = OnSurfaceDim,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- }- if (item.failureCategory != RecordingFailureCategory.NONE) {- Text(- text = "${stringResource(R.string.settings_recording_failure_label)}: ${formatRecordingFailureCategory(item.failureCategory)}",- style = MaterialTheme.typography.labelSmall,- color = ErrorColor- )- }- FlowRow(- horizontalArrangement = Arrangement.spacedBy(6.dp),- verticalArrangement = Arrangement.spacedBy(6.dp),- modifier = Modifier.fillMaxWidth(),- maxItemsInEachRow = 4- ) {- if (item.status == RecordingStatus.COMPLETED && (!item.outputUri.isNullOrBlank() || !item.outputPath.isNullOrBlank())) {- CompactRecordingActionChip(- label = "Play",- accent = Primary,- onClick = onPlay- )- }- if (item.status == RecordingStatus.RECORDING) {- CompactRecordingActionChip(- label = stringResource(R.string.settings_recording_stop),- accent = ErrorColor,- onClick = onStop- )- }- if (item.status == RecordingStatus.SCHEDULED) {- CompactRecordingActionChip(- label = stringResource(- if (item.scheduleEnabled) R.string.settings_recording_disable- else R.string.settings_recording_enable- ),- accent = Secondary,- onClick = { onToggleSchedule(!item.scheduleEnabled) }- )- CompactRecordingActionChip(- label = stringResource(R.string.settings_recording_cancel),- accent = OnBackground,- onClick = onCancel- )- }- if (item.status == RecordingStatus.COMPLETED || item.status == RecordingStatus.FAILED || item.status == RecordingStatus.CANCELLED) {- if (item.status == RecordingStatus.FAILED) {- CompactRecordingActionChip(- label = stringResource(R.string.settings_recording_retry),- accent = Primary,- onClick = onRetry- )- }- CompactRecordingActionChip(- label = stringResource(R.string.settings_recording_delete),- accent = OnBackground,- onClick = onDelete- )- }- }- }- }-}--@Composable-private fun CompactRecordingActionChip(label: String, accent: Color, onClick: () -> Unit) {- TvClickableSurface(- onClick = onClick,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = accent.copy(alpha = 0.14f),- focusedContainerColor = accent.copy(alpha = 0.3f)- ),- border = ClickableSurfaceDefaults.border(- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(8.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = label,- color = accent,- style = MaterialTheme.typography.labelSmall,- modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp)- )- }-}--@Composable-private fun CompactSettingsActionChip(- label: String,- accent: Color,- enabled: Boolean = true,- onClick: () -> Unit-) {- TvClickableSurface(- onClick = onClick,- enabled = enabled,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = accent.copy(alpha = if (enabled) 0.14f else 0.08f),- contentColor = accent.copy(alpha = if (enabled) 1f else 0.42f),- focusedContainerColor = accent.copy(alpha = if (enabled) 0.28f else 0.08f),- focusedContentColor = accent.copy(alpha = if (enabled) 1f else 0.42f),- disabledContainerColor = accent.copy(alpha = 0.08f),- disabledContentColor = accent.copy(alpha = 0.42f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- border = BorderStroke(1.dp, Color.White.copy(alpha = if (enabled) 0.08f else 0.04f)),- shape = RoundedCornerShape(8.dp)- ),- focusedBorder = Border(- border = BorderStroke(FocusSpec.BorderWidth, Color.White),- shape = RoundedCornerShape(8.dp)- )- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = label,- color = accent.copy(alpha = if (enabled) 1f else 0.42f),- style = MaterialTheme.typography.labelSmall,- modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)- )- }-}--private fun RecordingItem.playbackUrl(): String? {- val persistedUri = outputUri?.trim()?.takeIf { it.isNotBlank() }- if (persistedUri != null) {- return persistedUri- }- val localPath = outputPath?.trim()?.takeIf { it.isNotBlank() } ?: return null- val parsed = runCatching { android.net.Uri.parse(localPath) }.getOrNull()- return if (parsed?.scheme.isNullOrBlank()) {- android.net.Uri.fromFile(java.io.File(localPath)).toString()- } else {- localPath- }-}--private fun android.content.Context.findMainActivity(): MainActivity? {- var current: android.content.Context? = this- while (current is android.content.ContextWrapper) {- if (current is MainActivity) return current- current = current.baseContext+private fun android.content.Context.findMainActivity(): MainActivity? {+ var current: android.content.Context? = this+ while (current is android.content.ContextWrapper) {+ if (current is MainActivity) return current+ current = current.baseContext}return null}-private fun displayableEpgUrl(url: String): String = when {- url.startsWith("content://") -> {- val lastSegment = try { android.net.Uri.parse(url).lastPathSegment } catch (_: Exception) { null }- val decoded = lastSegment?.let { android.net.Uri.decode(it) }?.substringAfterLast("/")?.substringAfterLast("\\")- if (!decoded.isNullOrBlank() && decoded.length < 60) "local: $decoded" else "local file"- }- else -> url-}--@Composable-private fun EpgSourceTextField(- value: String,- onValueChange: (String) -> Unit,- placeholder: String-) {- val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()- val focusRequester = remember { FocusRequester() }- val keyboardController = LocalSoftwareKeyboardController.current- val bringIntoViewRequester = remember { BringIntoViewRequester() }- val coroutineScope = rememberCoroutineScope()- var hasContainerFocus by remember { mutableStateOf(false) }- var hasInputFocus by remember { mutableStateOf(false) }- var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }- var pendingInputActivation by remember { mutableStateOf(false) }- var fieldValue by remember {- mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))- }- val isFocused = hasContainerFocus || hasInputFocus-- fun requestBringIntoView(delayMillis: Long = 0L) {- coroutineScope.launch {- if (delayMillis > 0) {- kotlinx.coroutines.delay(delayMillis)- }- runCatching { bringIntoViewRequester.bringIntoView() }- }- }-- LaunchedEffect(value) {- if (value != fieldValue.text) {- val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)- val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)- val coercedComposition = fieldValue.composition?.let { composition ->- val compositionStart = composition.start.coerceIn(0, value.length)- val compositionEnd = composition.end.coerceIn(0, value.length)- if (compositionStart <= compositionEnd) {- TextRange(compositionStart, compositionEnd)- } else {- null- }- }- fieldValue = fieldValue.copy(- text = value,- selection = TextRange(coercedSelectionStart, coercedSelectionEnd),- composition = coercedComposition- )- }- }-- LaunchedEffect(acceptsInput, pendingInputActivation) {- if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {- return@LaunchedEffect- }- focusRequester.requestFocus()- keyboardController?.show()- requestBringIntoView(120)- pendingInputActivation = false- }-- TvClickableSurface(- onClick = {- if (!isTelevisionDevice) {- focusRequester.requestFocus()- keyboardController?.show()- requestBringIntoView()- requestBringIntoView(180)- return@TvClickableSurface- }- acceptsInput = true- pendingInputActivation = true- requestBringIntoView()- },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Color.White.copy(alpha = 0.08f),- focusedContainerColor = Color.White.copy(alpha = 0.12f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .bringIntoViewRequester(bringIntoViewRequester)- .onFocusChanged { hasContainerFocus = it.isFocused }- ) {- Box(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {- if (value.isEmpty() && !isFocused) {- Text(placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)- }- BasicTextField(- value = fieldValue,- onValueChange = { updatedValue ->- fieldValue = updatedValue- if (updatedValue.text != value) {- onValueChange(updatedValue.text)- }- },- textStyle = MaterialTheme.typography.bodyMedium.copy(color = Color.White),- singleLine = true,- cursorBrush = SolidColor(Primary),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .focusProperties {- canFocus = !isTelevisionDevice || acceptsInput- if (isTelevisionDevice && acceptsInput) {- left = FocusRequester.Cancel- right = FocusRequester.Cancel- }- }- .onPreviewKeyEvent { event ->- if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {- return@onPreviewKeyEvent false- }- val cursor = fieldValue.selection.end- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {- val nextCursor = (cursor - 1).coerceAtLeast(0)- fieldValue = fieldValue.copy(selection = TextRange(nextCursor))- true- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {- val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)- fieldValue = fieldValue.copy(selection = TextRange(nextCursor))- true- }- else -> false- }- }- .onFocusChanged {- hasInputFocus = it.isFocused- if (it.isFocused) {- requestBringIntoView(120)- } else {- if (isTelevisionDevice) {- acceptsInput = false- }- keyboardController?.hide()- }- },- readOnly = isTelevisionDevice && !acceptsInput- )- }- }-}--@Composable-private fun LiveTvQuickFiltersDialog(- filters: List<String>,- onDismiss: () -> Unit,- onAddFilter: (String) -> Unit,- onRemoveFilter: (String) -> Unit-) {- var pendingFilter by rememberSaveable { mutableStateOf("") }-- PremiumDialog(- title = stringResource(R.string.settings_live_tv_quick_filters_dialog_title),- subtitle = stringResource(R.string.settings_live_tv_quick_filters_dialog_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.5f,- content = {- EpgSourceTextField(- value = pendingFilter,- onValueChange = { pendingFilter = it },- placeholder = stringResource(R.string.settings_live_tv_quick_filters_placeholder)- )- PremiumDialogActionButton(- label = stringResource(R.string.settings_live_tv_quick_filters_add),- enabled = pendingFilter.isNotBlank(),- onClick = {- onAddFilter(pendingFilter)- pendingFilter = ""- }- )- if (filters.isEmpty()) {- Text(- text = stringResource(R.string.settings_live_tv_quick_filters_empty),- style = MaterialTheme.typography.bodyMedium,- color = OnSurfaceDim- )- } else {- Text(- text = stringResource(R.string.settings_live_tv_quick_filters_saved),- style = MaterialTheme.typography.labelMedium,- color = OnSurfaceDim- )- LazyColumn(- modifier = Modifier.heightIn(max = 260.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- items(filters, key = { it }) { filter ->- Box(- modifier = Modifier- .fillMaxWidth()- .background(Color.White.copy(alpha = 0.06f), RoundedCornerShape(12.dp))- .padding(horizontal = 14.dp, vertical = 10.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = filter,- style = MaterialTheme.typography.bodyMedium,- color = OnSurface,- modifier = Modifier.weight(1f)- )- TvButton(onClick = { onRemoveFilter(filter) }) {- Text(stringResource(R.string.settings_live_tv_quick_filters_remove))- }- }- }- }- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- }- )-}--private fun formatLiveTvQuickFiltersValue(filters: List<String>, context: android.content.Context): String {- if (filters.isEmpty()) {- return context.getString(R.string.settings_live_tv_quick_filters_none)- }- return context.resources.getQuantityString(- R.plurals.settings_live_tv_quick_filters_count,- filters.size,- filters.size- )-}--@Composable-private fun SettingsNavItem(- label: String,- badgeChar: String,- accentColor: Color,- isSelected: Boolean,- onClick: () -> Unit-) {- val focusRequester = remember { FocusRequester() }- TvClickableSurface(- onClick = onClick,- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(0.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.11f) else Color.Transparent,- focusedContainerColor = Primary.copy(alpha = 0.22f)- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- modifier = Modifier- .fillMaxWidth()- .focusRequester(focusRequester)- .mouseClickable(focusRequester = focusRequester, onClick = onClick)- ) {- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 10.dp, vertical = 12.dp),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(10.dp)- ) {- Box(- Modifier- .width(3.dp)- .height(22.dp)- .background(- color = if (isSelected) Primary else Color.Transparent,- shape = RoundedCornerShape(2.dp)- )- )- Box(- Modifier- .size(28.dp)- .background(accentColor.copy(alpha = 0.18f), RoundedCornerShape(7.dp)),- contentAlignment = Alignment.Center- ) {- Text(- text = badgeChar,- style = MaterialTheme.typography.labelSmall,- color = accentColor,- fontWeight = FontWeight.Bold- )- }- Text(- text = label,- style = MaterialTheme.typography.labelLarge,- color = if (isSelected) Primary else OnBackground,- fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal- )- }- }-}--private fun formatBytes(bytes: Long): String {- if (bytes <= 0L) return "0 B"- val kb = 1024.0- val mb = kb * 1024.0- val gb = mb * 1024.0- return when {- bytes >= gb -> String.format(Locale.getDefault(), "%.1f GB", bytes / gb)- bytes >= mb -> String.format(Locale.getDefault(), "%.1f MB", bytes / mb)- bytes >= kb -> String.format(Locale.getDefault(), "%.1f KB", bytes / kb)- else -> "$bytes B"- }-}--private fun formatTimestamp(timestampMs: Long): String {- if (timestampMs <= 0L) return "--:--"- return java.text.SimpleDateFormat("MMM d, HH:mm", Locale.getDefault()).format(java.util.Date(timestampMs))-}--private data class AppLanguageOption(- val tag: String,- val label: String-)--private fun supportedAppLanguages(systemDefaultLabel: String): List<AppLanguageOption> {- val localeTags = listOf("system") + supportedAppLanguageTags()-- return localeTags.map { tag ->- AppLanguageOption(- tag = tag,- label = if (tag == "system") {- systemDefaultLabel- } else {- val locale = localeForLanguageTag(tag)- locale.getDisplayLanguage(locale)- .replaceFirstChar { character ->- if (character.isLowerCase()) {- character.titlecase(locale)- } else {- character.toString()- }- }- }- )- }-}--private fun supportedAudioLanguages(autoLabel: String): List<AppLanguageOption> {- return buildList {- add(AppLanguageOption(tag = "auto", label = autoLabel))- addAll(supportedAppLanguages(autoLabel).filterNot { it.tag == "system" })- }-}--private data class SubtitleScaleOption(- val scale: Float,- val label: (android.content.Context) -> String-)--private data class SubtitleColorOption(- val colorArgb: Int,- val label: String-)--private fun subtitleSizeOptions(): List<SubtitleScaleOption> {- return listOf(- SubtitleScaleOption(0.85f) { it.getString(R.string.settings_subtitle_size_small) },- SubtitleScaleOption(1f) { it.getString(R.string.settings_subtitle_size_default) },- SubtitleScaleOption(1.15f) { it.getString(R.string.settings_subtitle_size_large) },- SubtitleScaleOption(1.3f) { it.getString(R.string.settings_subtitle_size_extra_large) }- )-}--private fun subtitleTextColorOptions(context: android.content.Context): List<SubtitleColorOption> {- return listOf(- SubtitleColorOption(0xFFFFFFFF.toInt(), context.getString(R.string.settings_subtitle_color_white)),- SubtitleColorOption(0xFFFFEB3B.toInt(), context.getString(R.string.settings_subtitle_color_yellow)),- SubtitleColorOption(0xFF80DEEA.toInt(), context.getString(R.string.settings_subtitle_color_cyan)),- SubtitleColorOption(0xFFA5D6A7.toInt(), context.getString(R.string.settings_subtitle_color_green))- )-}--private fun subtitleBackgroundColorOptions(context: android.content.Context): List<SubtitleColorOption> {- return listOf(- SubtitleColorOption(0x00000000, context.getString(R.string.settings_subtitle_background_transparent)),- SubtitleColorOption(0x80000000.toInt(), context.getString(R.string.settings_subtitle_background_dim)),- SubtitleColorOption(0xCC000000.toInt(), context.getString(R.string.settings_subtitle_background_black)),- SubtitleColorOption(0xCC102A43.toInt(), context.getString(R.string.settings_subtitle_background_blue))- )-}--private fun displayLanguageLabel(languageTag: String, defaultLabel: String): String {- if (languageTag.isBlank() || languageTag == "system" || languageTag == "auto") return defaultLabel- val locale = localeForLanguageTag(languageTag)- if (locale.language.isBlank()) return defaultLabel- return locale.getDisplayLanguage(Locale.getDefault())- .replaceFirstChar { character ->- if (character.isLowerCase()) {- character.titlecase(Locale.getDefault())- } else {- character.toString()- }- }-}--private fun formatPlaybackSpeedLabel(speed: Float): String {- return if (speed % 1f == 0f) {- "${speed.toInt()}x"- } else {- "${("%.2f".format(Locale.US, speed)).trimEnd('0').trimEnd('.')}x"- }-}--@Composable-private fun RecordingMetaPill(label: String, value: String) {- Column(- modifier = Modifier- .widthIn(min = 92.dp, max = 160.dp)- .background(Color.White.copy(alpha = 0.05f), RoundedCornerShape(10.dp))- .padding(horizontal = 7.dp, vertical = 5.dp)- ) {- Text(text = label, style = MaterialTheme.typography.labelSmall, color = OnSurfaceDim)- Text(text = value, style = MaterialTheme.typography.labelMedium, color = OnBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)- }-}--private fun summarizeRecordingOutputPath(path: String): String {- val trimmed = path.trim()- if (trimmed.isBlank()) return trimmed- val decoded = runCatching { android.net.Uri.decode(trimmed) }.getOrDefault(trimmed)- return decoded- .substringAfterLast('/')- .substringAfterLast('\\')- .ifBlank { decoded }-}--@Composable-private fun RecordingActionButton(label: String, accent: Color, onClick: () -> Unit) {- TvButton(- onClick = onClick,- modifier = Modifier- .widthIn(min = 190.dp, max = 260.dp)- .heightIn(min = 52.dp),- shape = ButtonDefaults.shape(RoundedCornerShape(10.dp)),- colors = ButtonDefaults.colors(- containerColor = accent.copy(alpha = 0.14f),- focusedContainerColor = accent.copy(alpha = 0.28f),- contentColor = accent,- focusedContentColor = accent- ),- scale = ButtonDefaults.scale(focusedScale = 1f)- ) {- Text(- text = label,- color = accent,- style = MaterialTheme.typography.labelMedium,- maxLines = 2,- modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)- )- }-}--@Composable-private fun SimpleTextValueDialog(- title: String,- subtitle: String,- initialValue: String,- onDismiss: () -> Unit,- onConfirm: (String) -> Unit-) {- var value by remember(initialValue) { mutableStateOf(initialValue) }- PremiumDialog(- title = title,- subtitle = subtitle,- onDismissRequest = onDismiss,- widthFraction = 0.58f,- content = {- EpgSourceTextField(- value = value,- onValueChange = { value = it },- placeholder = initialValue- )- },- footer = {- Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_cancel),- onClick = onDismiss- )- PremiumDialogActionButton(- label = stringResource(R.string.settings_save),- onClick = { onConfirm(value.trim()) }- )- }- }- )-}--private fun formatRecordingSourceType(sourceType: RecordingSourceType): String = when (sourceType) {- RecordingSourceType.TS -> "TS"- RecordingSourceType.HLS -> "HLS"- RecordingSourceType.DASH -> "DASH"- RecordingSourceType.UNKNOWN -> "Auto"-}--private fun formatRecordingFailureCategory(category: RecordingFailureCategory): String = when (category) {- RecordingFailureCategory.NONE -> "None"- RecordingFailureCategory.NETWORK -> "Network"- RecordingFailureCategory.STORAGE -> "Storage"- RecordingFailureCategory.AUTH -> "Auth"- RecordingFailureCategory.TOKEN_EXPIRED -> "Token"- RecordingFailureCategory.DRM_UNSUPPORTED -> "DRM"- RecordingFailureCategory.FORMAT_UNSUPPORTED -> "Format"- RecordingFailureCategory.SCHEDULE_CONFLICT -> "Conflict"- RecordingFailureCategory.PROVIDER_LIMIT -> "Connection limit"- RecordingFailureCategory.UNKNOWN -> "Unknown"-}--private fun playerTimeoutOptions(): List<Int> = listOf(2, 3, 4, 5, 6, 8, 10, 15, 20, 30)--private fun formatDecoderModeLabel(mode: DecoderMode, context: android.content.Context): String {- return when (mode) {- DecoderMode.AUTO -> context.getString(R.string.settings_decoder_auto)- DecoderMode.HARDWARE -> context.getString(R.string.settings_decoder_hardware)- DecoderMode.SOFTWARE -> context.getString(R.string.settings_decoder_software)- }-}--private fun formatTimeoutSecondsLabel(seconds: Int, context: android.content.Context): String {- return context.resources.getQuantityString(- R.plurals.settings_timeout_seconds,- seconds,- seconds- )-}--private fun formatSubtitleSizeLabel(scale: Float, context: android.content.Context): String {- return subtitleSizeOptions().firstOrNull { it.scale == scale }?.label?.invoke(context)- ?: context.getString(R.string.settings_subtitle_size_default)-}--private fun formatSubtitleColorLabel(colorArgb: Int, options: List<SubtitleColorOption>): String {- return options.firstOrNull { it.colorArgb == colorArgb }?.label ?: options.first().label-}--private fun formatQualityCapLabel(maxHeight: Int?, autoLabel: String): String {- return maxHeight?.let { "${it}p" } ?: autoLabel-}--private fun formatSpeedTestValueLabel(speedTest: InternetSpeedTestUiModel): String {- return String.format(Locale.getDefault(), "%.1f Mbps", speedTest.megabitsPerSecond)-}--private fun formatSpeedTestSummary(- speedTest: InternetSpeedTestUiModel,- context: android.content.Context-): String {- val transportLabel = when (speedTest.transportLabel) {- InternetSpeedTestTransport.WIFI.name -> context.getString(R.string.settings_speed_test_transport_wifi)- InternetSpeedTestTransport.ETHERNET.name -> context.getString(R.string.settings_speed_test_transport_ethernet)- InternetSpeedTestTransport.CELLULAR.name -> context.getString(R.string.settings_speed_test_transport_cellular)- InternetSpeedTestTransport.OTHER.name -> context.getString(R.string.settings_speed_test_transport_other)- else -> context.getString(R.string.settings_speed_test_transport_unknown)- }- val measuredAtLabel = formatTimestamp(speedTest.measuredAtMs)- return if (speedTest.isEstimated) {- context.getString(R.string.settings_speed_test_summary_estimated, transportLabel, measuredAtLabel)- } else {- context.getString(R.string.settings_speed_test_summary_measured, transportLabel, measuredAtLabel)- }-}--private fun sortModeLabel(mode: CategorySortMode, context: android.content.Context): String {- return when (mode) {- CategorySortMode.DEFAULT -> context.getString(R.string.settings_category_sort_default)- CategorySortMode.TITLE_ASC -> context.getString(R.string.settings_category_sort_az)- CategorySortMode.TITLE_DESC -> context.getString(R.string.settings_category_sort_za)- CategorySortMode.COUNT_DESC -> context.getString(R.string.settings_category_sort_most_items)- CategorySortMode.COUNT_ASC -> context.getString(R.string.settings_category_sort_least_items)- }-}--private fun formatCategorySortModeLabel(mode: CategorySortMode, context: android.content.Context): String {- return sortModeLabel(mode, context)-}--private fun categoryTypeLabel(type: ContentType, context: android.content.Context): String {- return when (type) {- ContentType.LIVE -> context.getString(R.string.settings_category_sort_live)- ContentType.MOVIE -> context.getString(R.string.settings_category_sort_movies)- ContentType.SERIES -> context.getString(R.string.settings_category_sort_series)- ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_sort_series)- }-}--private fun categoryTypeDescription(type: ContentType, context: android.content.Context): String {- return when (type) {- ContentType.LIVE -> context.getString(R.string.settings_category_type_live_description)- ContentType.MOVIE -> context.getString(R.string.settings_category_type_movies_description)- ContentType.SERIES -> context.getString(R.string.settings_category_type_series_description)- ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_type_series_description)- }-}--private fun LiveTvChannelMode.labelResId(): Int = when (this) {- LiveTvChannelMode.COMFORTABLE -> R.string.settings_live_tv_mode_comfortable- LiveTvChannelMode.COMPACT -> R.string.settings_live_tv_mode_compact- LiveTvChannelMode.PRO -> R.string.settings_live_tv_mode_pro-}--private fun LiveTvChannelMode.descriptionResId(): Int = when (this) {- LiveTvChannelMode.COMFORTABLE -> R.string.settings_live_tv_mode_comfortable_desc- LiveTvChannelMode.COMPACT -> R.string.settings_live_tv_mode_compact_desc- LiveTvChannelMode.PRO -> R.string.settings_live_tv_mode_pro_desc-}--private fun LiveTvQuickFilterVisibilityMode.labelResId(): Int = when (this) {- LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide- LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available- LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always-}--private fun LiveTvQuickFilterVisibilityMode.descriptionResId(): Int = when (this) {- LiveTvQuickFilterVisibilityMode.HIDE -> R.string.settings_live_tv_quick_filter_visibility_hide_desc- LiveTvQuickFilterVisibilityMode.SHOW_WHEN_FILTERS_AVAILABLE -> R.string.settings_live_tv_quick_filter_visibility_available_desc- LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE -> R.string.settings_live_tv_quick_filter_visibility_always_desc-}--private fun VodViewMode.labelResId(): Int = when (this) {- VodViewMode.MODERN -> R.string.settings_vod_view_mode_modern- VodViewMode.CLASSIC -> R.string.settings_vod_view_mode_classic-}--private fun VodViewMode.descriptionResId(): Int = when (this) {- VodViewMode.MODERN -> R.string.settings_vod_view_mode_modern_desc- VodViewMode.CLASSIC -> R.string.settings_vod_view_mode_classic_desc-}--private fun ChannelNumberingMode.labelResId(): Int = when (this) {- ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_group- ChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider-}--private fun ChannelNumberingMode.descriptionResId(): Int = when (this) {- ChannelNumberingMode.GROUP -> R.string.settings_live_channel_numbering_group_desc- ChannelNumberingMode.PROVIDER -> R.string.settings_live_channel_numbering_provider_desc-}-diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.ktnew file mode 100644index 00000000..52a93e32--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreenDialogs.kt@@ -0,0 +1,713 @@+package com.streamvault.app.ui.screens.settings++import android.content.Context+import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.input.key.onKeyEvent+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.TextButton+import androidx.compose.material3.AlertDialog+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PinDialog+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.TextSecondary+import com.streamvault.domain.model.CategorySortMode+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.DecoderMode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch++@Composable+internal fun SettingsScreenDialogs(+ uiState: SettingsUiState,+ viewModel: SettingsViewModel,+ context: Context,+ scope: CoroutineScope,+ showLiveTvModeDialog: Boolean,+ onShowLiveTvModeDialogChange: (Boolean) -> Unit,+ showLiveTvQuickFilterVisibilityDialog: Boolean,+ onShowLiveTvQuickFilterVisibilityDialogChange: (Boolean) -> Unit,+ showLiveChannelNumberingDialog: Boolean,+ onShowLiveChannelNumberingDialogChange: (Boolean) -> Unit,+ showVodViewModeDialog: Boolean,+ onShowVodViewModeDialogChange: (Boolean) -> Unit,+ showPlaybackSpeedDialog: Boolean,+ onShowPlaybackSpeedDialogChange: (Boolean) -> Unit,+ showDecoderModeDialog: Boolean,+ onShowDecoderModeDialogChange: (Boolean) -> Unit,+ showControlsTimeoutDialog: Boolean,+ onShowControlsTimeoutDialogChange: (Boolean) -> Unit,+ showLiveOverlayTimeoutDialog: Boolean,+ onShowLiveOverlayTimeoutDialogChange: (Boolean) -> Unit,+ showNoticeTimeoutDialog: Boolean,+ onShowNoticeTimeoutDialogChange: (Boolean) -> Unit,+ showDiagnosticsTimeoutDialog: Boolean,+ onShowDiagnosticsTimeoutDialogChange: (Boolean) -> Unit,+ showLiveTvFiltersDialog: Boolean,+ onShowLiveTvFiltersDialogChange: (Boolean) -> Unit,+ showAudioLanguageDialog: Boolean,+ onShowAudioLanguageDialogChange: (Boolean) -> Unit,+ showSubtitleSizeDialog: Boolean,+ onShowSubtitleSizeDialogChange: (Boolean) -> Unit,+ showSubtitleTextColorDialog: Boolean,+ onShowSubtitleTextColorDialogChange: (Boolean) -> Unit,+ showSubtitleBackgroundDialog: Boolean,+ onShowSubtitleBackgroundDialogChange: (Boolean) -> Unit,+ showWifiQualityDialog: Boolean,+ onShowWifiQualityDialogChange: (Boolean) -> Unit,+ showEthernetQualityDialog: Boolean,+ onShowEthernetQualityDialogChange: (Boolean) -> Unit,+ categorySortDialogType: String?,+ onCategorySortDialogTypeChange: (String?) -> Unit,+ showPinDialog: Boolean,+ onShowPinDialogChange: (Boolean) -> Unit,+ showLevelDialog: Boolean,+ onShowLevelDialogChange: (Boolean) -> Unit,+ pinError: String?,+ onPinErrorChange: (String?) -> Unit,+ pendingAction: ParentalAction?,+ onPendingActionChange: (ParentalAction?) -> Unit,+ pendingProtectionLevel: Int?,+ onPendingProtectionLevelChange: (Int?) -> Unit,+ showLanguageDialog: Boolean,+ onShowLanguageDialogChange: (Boolean) -> Unit,+ showRecordingPatternDialog: Boolean,+ onShowRecordingPatternDialogChange: (Boolean) -> Unit,+ showRecordingRetentionDialog: Boolean,+ onShowRecordingRetentionDialogChange: (Boolean) -> Unit,+ showRecordingConcurrencyDialog: Boolean,+ onShowRecordingConcurrencyDialogChange: (Boolean) -> Unit,+ showClearHistoryDialog: Boolean,+ onShowClearHistoryDialogChange: (Boolean) -> Unit,+ showCreateCombinedDialog: Boolean,+ onShowCreateCombinedDialogChange: (Boolean) -> Unit,+ showAddCombinedMemberDialog: Boolean,+ onShowAddCombinedMemberDialogChange: (Boolean) -> Unit,+ showRenameCombinedDialog: Boolean,+ onShowRenameCombinedDialogChange: (Boolean) -> Unit,+ selectedCombinedProfileId: Long?,+ showProviderSyncDialog: Boolean,+ onShowProviderSyncDialogChange: (Boolean) -> Unit,+ showCustomProviderSyncDialog: Boolean,+ onShowCustomProviderSyncDialogChange: (Boolean) -> Unit,+ pendingSyncProviderId: Long?,+ onPendingSyncProviderIdChange: (Long?) -> Unit,+ customSyncSelections: Set<ProviderSyncSelection>,+ onCustomSyncSelectionsChange: (Set<ProviderSyncSelection>) -> Unit+) {+ SyncingOverlay(isSyncing = uiState.isSyncing)++ if (showLiveTvModeDialog) {+ LiveTvChannelModeDialog(+ selectedMode = uiState.liveTvChannelMode,+ onDismiss = { onShowLiveTvModeDialogChange(false) },+ onModeSelected = { mode ->+ viewModel.setLiveTvChannelMode(mode)+ onShowLiveTvModeDialogChange(false)+ }+ )+ }++ if (showLiveTvQuickFilterVisibilityDialog) {+ LiveTvQuickFilterVisibilityDialog(+ selectedMode = uiState.liveTvQuickFilterVisibilityMode,+ onDismiss = { onShowLiveTvQuickFilterVisibilityDialogChange(false) },+ onModeSelected = { mode ->+ viewModel.setLiveTvQuickFilterVisibilityMode(mode)+ onShowLiveTvQuickFilterVisibilityDialogChange(false)+ }+ )+ }++ if (showLiveChannelNumberingDialog) {+ LiveChannelNumberingModeDialog(+ selectedMode = uiState.liveChannelNumberingMode,+ onDismiss = { onShowLiveChannelNumberingDialogChange(false) },+ onModeSelected = { mode ->+ viewModel.setLiveChannelNumberingMode(mode)+ onShowLiveChannelNumberingDialogChange(false)+ }+ )+ }++ if (showVodViewModeDialog) {+ VodViewModeDialog(+ selectedMode = uiState.vodViewMode,+ onDismiss = { onShowVodViewModeDialogChange(false) },+ onModeSelected = { mode ->+ viewModel.setVodViewMode(mode)+ onShowVodViewModeDialogChange(false)+ }+ )+ }++ if (showPlaybackSpeedDialog) {+ val speedOptions = remember { listOf(0.5f, 0.75f, 1f, 1.25f, 1.5f, 2f) }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_playback_speed),+ onDismiss = { onShowPlaybackSpeedDialogChange(false) }+ ) {+ speedOptions.forEachIndexed { index, speed ->+ LevelOption(+ level = index,+ text = formatPlaybackSpeedLabel(speed),+ currentLevel = if (speed == uiState.playerPlaybackSpeed) index else -1,+ onSelect = {+ viewModel.setDefaultPlaybackSpeed(speed)+ onShowPlaybackSpeedDialogChange(false)+ }+ )+ }+ }+ }++ if (showDecoderModeDialog) {+ val decoderOptions = remember(context) {+ listOf(+ DecoderMode.AUTO to context.getString(R.string.settings_decoder_auto),+ DecoderMode.HARDWARE to context.getString(R.string.settings_decoder_hardware),+ DecoderMode.SOFTWARE to context.getString(R.string.settings_decoder_software)+ )+ }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_decoder_mode),+ onDismiss = { onShowDecoderModeDialogChange(false) }+ ) {+ decoderOptions.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.second,+ currentLevel = if (uiState.playerDecoderMode == option.first) index else -1,+ onSelect = {+ viewModel.setPlayerDecoderMode(option.first)+ onShowDecoderModeDialogChange(false)+ }+ )+ }+ }+ }++ if (showControlsTimeoutDialog) {+ TimeoutValueDialog(+ title = stringResource(R.string.settings_player_controls_timeout),+ subtitle = stringResource(R.string.settings_timeout_vod_controls_subtitle),+ initialValue = uiState.playerControlsTimeoutSeconds,+ onDismiss = { onShowControlsTimeoutDialogChange(false) }+ ) { seconds ->+ viewModel.setPlayerControlsTimeoutSeconds(seconds)+ onShowControlsTimeoutDialogChange(false)+ }+ }++ if (showLiveOverlayTimeoutDialog) {+ TimeoutValueDialog(+ title = stringResource(R.string.settings_live_overlay_timeout),+ subtitle = stringResource(R.string.settings_timeout_live_overlays_subtitle),+ initialValue = uiState.playerLiveOverlayTimeoutSeconds,+ onDismiss = { onShowLiveOverlayTimeoutDialogChange(false) }+ ) { seconds ->+ viewModel.setPlayerLiveOverlayTimeoutSeconds(seconds)+ onShowLiveOverlayTimeoutDialogChange(false)+ }+ }++ if (showNoticeTimeoutDialog) {+ TimeoutValueDialog(+ title = stringResource(R.string.settings_player_notice_timeout),+ subtitle = stringResource(R.string.settings_timeout_notices_subtitle),+ initialValue = uiState.playerNoticeTimeoutSeconds,+ onDismiss = { onShowNoticeTimeoutDialogChange(false) }+ ) { seconds ->+ viewModel.setPlayerNoticeTimeoutSeconds(seconds)+ onShowNoticeTimeoutDialogChange(false)+ }+ }++ if (showDiagnosticsTimeoutDialog) {+ TimeoutValueDialog(+ title = stringResource(R.string.settings_player_diagnostics_timeout),+ subtitle = stringResource(R.string.settings_timeout_diagnostics_subtitle),+ initialValue = uiState.playerDiagnosticsTimeoutSeconds,+ onDismiss = { onShowDiagnosticsTimeoutDialogChange(false) }+ ) { seconds ->+ viewModel.setPlayerDiagnosticsTimeoutSeconds(seconds)+ onShowDiagnosticsTimeoutDialogChange(false)+ }+ }++ if (showLiveTvFiltersDialog) {+ LiveTvQuickFiltersDialog(+ filters = uiState.liveTvCategoryFilters,+ onDismiss = { onShowLiveTvFiltersDialogChange(false) },+ onAddFilter = viewModel::addLiveTvCategoryFilter,+ onRemoveFilter = viewModel::removeLiveTvCategoryFilter+ )+ }++ if (showAudioLanguageDialog) {+ val autoLabel = stringResource(R.string.settings_audio_language_auto)+ val audioLanguageOptions = remember(autoLabel) { supportedAudioLanguages(autoLabel) }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_audio_language),+ onDismiss = { onShowAudioLanguageDialogChange(false) }+ ) {+ audioLanguageOptions.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.label,+ currentLevel = if (uiState.preferredAudioLanguage == option.tag) index else -1,+ onSelect = {+ viewModel.setPreferredAudioLanguage(option.tag)+ onShowAudioLanguageDialogChange(false)+ }+ )+ }+ }+ }++ if (showSubtitleSizeDialog) {+ val subtitleSizeOptions = remember { subtitleSizeOptions() }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_subtitle_size),+ onDismiss = { onShowSubtitleSizeDialogChange(false) }+ ) {+ subtitleSizeOptions.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.label(context),+ currentLevel = if (uiState.subtitleTextScale == option.scale) index else -1,+ onSelect = {+ viewModel.setSubtitleTextScale(option.scale)+ onShowSubtitleSizeDialogChange(false)+ }+ )+ }+ }+ }++ if (showSubtitleTextColorDialog) {+ val options = remember(context) { subtitleTextColorOptions(context) }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_subtitle_text_color),+ onDismiss = { onShowSubtitleTextColorDialogChange(false) }+ ) {+ options.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.label,+ currentLevel = if (uiState.subtitleTextColor == option.colorArgb) index else -1,+ onSelect = {+ viewModel.setSubtitleTextColor(option.colorArgb)+ onShowSubtitleTextColorDialogChange(false)+ }+ )+ }+ }+ }++ if (showSubtitleBackgroundDialog) {+ val options = remember(context) { subtitleBackgroundColorOptions(context) }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_subtitle_background),+ onDismiss = { onShowSubtitleBackgroundDialogChange(false) }+ ) {+ options.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.label,+ currentLevel = if (uiState.subtitleBackgroundColor == option.colorArgb) index else -1,+ onSelect = {+ viewModel.setSubtitleBackgroundColor(option.colorArgb)+ onShowSubtitleBackgroundDialogChange(false)+ }+ )+ }+ }+ }++ if (showWifiQualityDialog) {+ QualityCapSelectionDialog(+ title = stringResource(R.string.settings_select_wifi_quality_cap),+ currentValue = uiState.wifiMaxVideoHeight,+ onDismiss = { onShowWifiQualityDialogChange(false) },+ onSelect = {+ viewModel.setWifiQualityCap(it)+ onShowWifiQualityDialogChange(false)+ }+ )+ }++ if (showEthernetQualityDialog) {+ QualityCapSelectionDialog(+ title = stringResource(R.string.settings_select_ethernet_quality_cap),+ currentValue = uiState.ethernetMaxVideoHeight,+ onDismiss = { onShowEthernetQualityDialogChange(false) },+ onSelect = {+ viewModel.setEthernetQualityCap(it)+ onShowEthernetQualityDialogChange(false)+ }+ )+ }++ categorySortDialogType?.let { typeName ->+ val type = ContentType.entries.firstOrNull { it.name == typeName }+ if (type != null) {+ CategorySortModeDialog(+ type = type,+ currentMode = uiState.categorySortModes[type] ?: CategorySortMode.DEFAULT,+ onDismiss = { onCategorySortDialogTypeChange(null) },+ onModeSelected = { mode ->+ viewModel.setCategorySortMode(type, mode)+ onCategorySortDialogTypeChange(null)+ }+ )+ }+ }++ if (showPinDialog) {+ PinDialog(+ onDismissRequest = {+ onShowPinDialogChange(false)+ onPinErrorChange(null)+ if (pendingAction == ParentalAction.SetNewPin) {+ onPendingActionChange(null)+ onPendingProtectionLevelChange(null)+ }+ },+ onPinEntered = { pin ->+ scope.launch {+ if (pendingAction == ParentalAction.SetNewPin) {+ viewModel.changePin(pin)+ pendingProtectionLevel?.let(viewModel::setParentalControlLevel)+ onPendingProtectionLevelChange(null)+ onShowPinDialogChange(false)+ onPendingActionChange(null)+ } else {+ if (viewModel.verifyPin(pin)) {+ onShowPinDialogChange(false)+ onPinErrorChange(null)+ when (pendingAction) {+ ParentalAction.ChangeLevel -> onShowLevelDialogChange(true)+ ParentalAction.ChangePin -> {+ onPendingActionChange(ParentalAction.SetNewPin)+ onShowPinDialogChange(true)+ }+ else -> onPendingActionChange(null)+ }+ } else {+ onPinErrorChange(context.getString(R.string.home_incorrect_pin))+ }+ }+ }+ },+ title = if (pendingAction == ParentalAction.SetNewPin) {+ stringResource(R.string.settings_enter_new_pin)+ } else {+ stringResource(R.string.settings_enter_pin)+ },+ error = pinError+ )+ }++ if (showLevelDialog) {+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_level),+ onDismiss = { onShowLevelDialogChange(false) }+ ) {+ LevelOption(0, stringResource(R.string.settings_level_off_desc), uiState.parentalControlLevel) {+ viewModel.setParentalControlLevel(0)+ onShowLevelDialogChange(false)+ }+ LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {+ if (uiState.hasParentalPin) {+ viewModel.setParentalControlLevel(1)+ } else {+ onPendingProtectionLevelChange(1)+ onPendingActionChange(ParentalAction.SetNewPin)+ onShowPinDialogChange(true)+ }+ onShowLevelDialogChange(false)+ }+ LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {+ if (uiState.hasParentalPin) {+ viewModel.setParentalControlLevel(2)+ } else {+ onPendingProtectionLevelChange(2)+ onPendingActionChange(ParentalAction.SetNewPin)+ onShowPinDialogChange(true)+ }+ onShowLevelDialogChange(false)+ }+ }+ }++ if (showLanguageDialog) {+ val systemDefaultLabel = stringResource(R.string.settings_system_default)+ val languageOptions = remember(systemDefaultLabel) { supportedAppLanguages(systemDefaultLabel) }+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_select_language),+ onDismiss = { onShowLanguageDialogChange(false) }+ ) {+ languageOptions.forEachIndexed { index, option ->+ LevelOption(+ level = index,+ text = option.label,+ currentLevel = if (uiState.appLanguage == option.tag) index else -1,+ onSelect = {+ viewModel.setAppLanguage(option.tag)+ onShowLanguageDialogChange(false)+ }+ )+ }+ }+ }++ val backupPreview = uiState.backupPreview+ if (backupPreview != null && uiState.pendingBackupUri != null) {+ BackupImportPreviewDialog(+ preview = backupPreview,+ plan = uiState.backupImportPlan,+ onDismiss = { viewModel.dismissBackupPreview() },+ onStrategySelected = { viewModel.setBackupConflictStrategy(it) },+ onImportPreferencesChanged = { viewModel.setImportPreferences(it) },+ onImportProvidersChanged = { viewModel.setImportProviders(it) },+ onImportSavedLibraryChanged = { viewModel.setImportSavedLibrary(it) },+ onImportPlaybackHistoryChanged = { viewModel.setImportPlaybackHistory(it) },+ onImportMultiViewChanged = { viewModel.setImportMultiViewPresets(it) },+ onImportRecordingSchedulesChanged = { viewModel.setImportRecordingSchedules(it) },+ onConfirm = { viewModel.confirmBackupImport() }+ )+ }++ if (showRecordingPatternDialog) {+ SimpleTextValueDialog(+ title = stringResource(R.string.settings_recording_pattern_title),+ subtitle = stringResource(R.string.settings_recording_pattern_hint),+ initialValue = uiState.recordingStorageState.fileNamePattern,+ onDismiss = { onShowRecordingPatternDialogChange(false) },+ onConfirm = { pattern ->+ viewModel.updateRecordingFileNamePattern(pattern)+ onShowRecordingPatternDialogChange(false)+ }+ )+ }++ if (showRecordingRetentionDialog) {+ val retentionOptions = listOf<Int?>(null, 7, 14, 30, 60, 90)+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_recording_retention_title),+ onDismiss = { onShowRecordingRetentionDialogChange(false) }+ ) {+ retentionOptions.forEachIndexed { index, days ->+ LevelOption(+ level = index,+ text = if (days == null) {+ stringResource(R.string.settings_recording_retention_keep_all)+ } else {+ stringResource(R.string.settings_recording_retention_days, days)+ },+ currentLevel = if (days == uiState.recordingStorageState.retentionDays) index else -1,+ onSelect = {+ viewModel.updateRecordingRetentionDays(days)+ onShowRecordingRetentionDialogChange(false)+ }+ )+ }+ }+ }++ if (showRecordingConcurrencyDialog) {+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_recording_concurrency_title),+ onDismiss = { onShowRecordingConcurrencyDialogChange(false) }+ ) {+ (1..4).forEach { value ->+ LevelOption(+ level = value,+ text = value.toString(),+ currentLevel = if (value == uiState.recordingStorageState.maxSimultaneousRecordings) value else -1,+ onSelect = {+ viewModel.updateRecordingMaxSimultaneous(value)+ onShowRecordingConcurrencyDialogChange(false)+ }+ )+ }+ }+ }++ if (showClearHistoryDialog) {+ AlertDialog(+ onDismissRequest = { onShowClearHistoryDialogChange(false) },+ title = { Text(text = stringResource(R.string.settings_clear_history_dialog_title)) },+ text = {+ Text(+ text = stringResource(R.string.settings_clear_history_dialog_body),+ color = OnSurface+ )+ },+ confirmButton = {+ TextButton(+ onClick = {+ viewModel.clearHistory()+ onShowClearHistoryDialogChange(false)+ }+ ) {+ Text(text = stringResource(R.string.settings_clear_history_confirm), color = Primary)+ }+ },+ dismissButton = {+ TextButton(onClick = { onShowClearHistoryDialogChange(false) }) {+ Text(text = stringResource(R.string.settings_cancel), color = OnSurface)+ }+ },+ containerColor = SurfaceElevated,+ titleContentColor = OnSurface,+ textContentColor = TextSecondary+ )+ }++ val pendingSyncProvider = pendingSyncProviderId?.let { providerId ->+ uiState.providers.firstOrNull { it.id == providerId }+ }+ if (showCreateCombinedDialog) {+ CreateCombinedM3uDialog(+ providers = uiState.availableM3uProviders,+ onDismiss = { onShowCreateCombinedDialogChange(false) },+ onCreate = { name, providerIds ->+ onShowCreateCombinedDialogChange(false)+ viewModel.createCombinedProfile(name, providerIds)+ }+ )+ }+ if (showRenameCombinedDialog) {+ val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == selectedCombinedProfileId }+ if (selectedProfile != null) {+ RenameCombinedM3uDialog(+ profile = selectedProfile,+ onDismiss = { onShowRenameCombinedDialogChange(false) },+ onRename = { name ->+ onShowRenameCombinedDialogChange(false)+ viewModel.renameCombinedProfile(selectedProfile.id, name)+ }+ )+ }+ }+ if (showAddCombinedMemberDialog) {+ val selectedProfile = uiState.combinedProfiles.firstOrNull { it.id == selectedCombinedProfileId }+ if (selectedProfile != null) {+ AddCombinedProviderDialog(+ profile = selectedProfile,+ availableProviders = uiState.availableM3uProviders,+ onDismiss = { onShowAddCombinedMemberDialogChange(false) },+ onAddProvider = { providerId ->+ onShowAddCombinedMemberDialogChange(false)+ viewModel.addProviderToCombinedProfile(selectedProfile.id, providerId)+ }+ )+ }+ }+ if (showProviderSyncDialog && pendingSyncProvider != null) {+ ProviderSyncOptionsDialog(+ provider = pendingSyncProvider,+ onDismiss = {+ onShowProviderSyncDialogChange(false)+ onPendingSyncProviderIdChange(null)+ },+ onSelect = { selection ->+ onShowProviderSyncDialogChange(false)+ if (selection == ProviderSyncSelection.ALL) {+ viewModel.syncProviderSection(pendingSyncProvider.id, selection)+ onPendingSyncProviderIdChange(null)+ } else if (selection == null) {+ onShowCustomProviderSyncDialogChange(true)+ } else {+ viewModel.syncProviderSection(pendingSyncProvider.id, selection)+ onPendingSyncProviderIdChange(null)+ }+ }+ )+ }+ if (showCustomProviderSyncDialog && pendingSyncProvider != null) {+ ProviderCustomSyncDialog(+ provider = pendingSyncProvider,+ selected = customSyncSelections,+ onToggle = { option ->+ onCustomSyncSelectionsChange(+ if (option in customSyncSelections) {+ customSyncSelections - option+ } else {+ customSyncSelections + option+ }+ )+ },+ onDismiss = {+ onShowCustomProviderSyncDialogChange(false)+ onPendingSyncProviderIdChange(null)+ },+ onConfirm = {+ onShowCustomProviderSyncDialogChange(false)+ viewModel.syncProviderCustom(pendingSyncProvider.id, customSyncSelections)+ onPendingSyncProviderIdChange(null)+ }+ )+ }+}++@Composable+private fun SyncingOverlay(isSyncing: Boolean) {+ if (!isSyncing) return++ BackHandler(enabled = true) {}++ val overlayFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) { overlayFocusRequester.requestFocus() }++ Box(+ modifier = Modifier+ .fillMaxSize()+ .background(Color.Black.copy(alpha = 0.7f))+ .clickable(enabled = true, onClick = {})+ .focusRequester(overlayFocusRequester)+ .focusable()+ .onKeyEvent { true },+ contentAlignment = Alignment.Center+ ) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ CircularProgressIndicator(color = Primary)+ Text(+ text = stringResource(R.string.settings_syncing_title),+ style = MaterialTheme.typography.titleMedium,+ color = OnSurface+ )+ Text(+ text = stringResource(R.string.settings_syncing_subtitle),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.ktnew file mode 100644index 00000000..c29d99b8--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt@@ -0,0 +1,359 @@+@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)++package com.streamvault.app.ui.screens.settings++import android.app.Application+import com.streamvault.app.R+import com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode+import com.streamvault.app.ui.model.VodViewMode+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.CategorySortMode+import com.streamvault.domain.model.ChannelNumberingMode+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.DecoderMode+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.VodSyncMode+import com.streamvault.domain.repository.CategoryRepository+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.SyncMetadataRepository+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.map+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++internal fun observeSettingsPreferenceSnapshot(+ providerRepository: ProviderRepository,+ activeProviderIdFlow: Flow<Long?>,+ preferencesRepository: PreferencesRepository+): Flow<SettingsPreferenceSnapshot> {+ return combine(+ providerRepository.getProviders(),+ activeProviderIdFlow,+ preferencesRepository.parentalControlLevel,+ preferencesRepository.hasParentalPin+ ) { providers, activeId, level, hasParentalPin ->+ SettingsPreferenceSnapshot(+ providers = providers,+ activeProviderId = activeId,+ parentalControlLevel = level,+ hasParentalPin = hasParentalPin,+ appLanguage = "system",+ preferredAudioLanguage = "auto",+ playerMediaSessionEnabled = true,+ playerDecoderMode = DecoderMode.AUTO,+ playerPlaybackSpeed = 1f,+ playerControlsTimeoutSeconds = 5,+ playerLiveOverlayTimeoutSeconds = 4,+ playerNoticeTimeoutSeconds = 6,+ playerDiagnosticsTimeoutSeconds = 15,+ subtitleTextScale = 1f,+ subtitleTextColor = 0xFFFFFFFF.toInt(),+ subtitleBackgroundColor = 0x80000000.toInt(),+ wifiMaxVideoHeight = null,+ ethernetMaxVideoHeight = null,+ lastSpeedTestMegabits = null,+ lastSpeedTestTimestamp = null,+ lastSpeedTestTransport = null,+ lastSpeedTestRecommendedHeight = null,+ lastSpeedTestEstimated = false,+ isIncognitoMode = false,+ useXtreamTextClassification = true,+ liveTvChannelMode = LiveTvChannelMode.PRO,+ showLiveSourceSwitcher = false,+ liveTvCategoryFilters = emptyList(),+ liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,+ liveChannelNumberingMode = ChannelNumberingMode.GROUP,+ vodViewMode = VodViewMode.MODERN,+ preventStandbyDuringPlayback = true,+ autoCheckAppUpdates = true,+ lastAppUpdateCheckAt = null,+ cachedAppUpdateVersionName = null,+ cachedAppUpdateVersionCode = null,+ cachedAppUpdateReleaseUrl = null,+ cachedAppUpdateDownloadUrl = null,+ cachedAppUpdateReleaseNotes = "",+ cachedAppUpdatePublishedAt = null+ )+ }.combine(preferencesRepository.appLanguage) { snapshot, language ->+ snapshot.copy(appLanguage = language)+ }.combine(preferencesRepository.preferredAudioLanguage) { snapshot, preferredAudioLanguage ->+ snapshot.copy(preferredAudioLanguage = preferredAudioLanguage ?: "auto")+ }.combine(preferencesRepository.playerMediaSessionEnabled) { snapshot, mediaSessionEnabled ->+ snapshot.copy(playerMediaSessionEnabled = mediaSessionEnabled)+ }.combine(preferencesRepository.playerDecoderMode) { snapshot, decoderMode ->+ snapshot.copy(playerDecoderMode = decoderMode)+ }.combine(preferencesRepository.playerPlaybackSpeed) { snapshot, playerPlaybackSpeed ->+ snapshot.copy(playerPlaybackSpeed = playerPlaybackSpeed)+ }.combine(preferencesRepository.playerControlsTimeoutSeconds) { snapshot, timeoutSeconds ->+ snapshot.copy(playerControlsTimeoutSeconds = timeoutSeconds)+ }.combine(preferencesRepository.playerLiveOverlayTimeoutSeconds) { snapshot, timeoutSeconds ->+ snapshot.copy(playerLiveOverlayTimeoutSeconds = timeoutSeconds)+ }.combine(preferencesRepository.playerNoticeTimeoutSeconds) { snapshot, timeoutSeconds ->+ snapshot.copy(playerNoticeTimeoutSeconds = timeoutSeconds)+ }.combine(preferencesRepository.playerDiagnosticsTimeoutSeconds) { snapshot, timeoutSeconds ->+ snapshot.copy(playerDiagnosticsTimeoutSeconds = timeoutSeconds)+ }.combine(preferencesRepository.playerSubtitleTextScale) { snapshot, subtitleTextScale ->+ snapshot.copy(subtitleTextScale = subtitleTextScale)+ }.combine(preferencesRepository.playerSubtitleTextColor) { snapshot, subtitleTextColor ->+ snapshot.copy(subtitleTextColor = subtitleTextColor)+ }.combine(preferencesRepository.playerSubtitleBackgroundColor) { snapshot, subtitleBackgroundColor ->+ snapshot.copy(subtitleBackgroundColor = subtitleBackgroundColor)+ }.combine(preferencesRepository.playerWifiMaxVideoHeight) { snapshot, wifiMaxVideoHeight ->+ snapshot.copy(wifiMaxVideoHeight = wifiMaxVideoHeight)+ }.combine(preferencesRepository.playerEthernetMaxVideoHeight) { snapshot, ethernetMaxVideoHeight ->+ snapshot.copy(ethernetMaxVideoHeight = ethernetMaxVideoHeight)+ }.combine(preferencesRepository.lastSpeedTestMegabits) { snapshot, lastSpeedTestMegabits ->+ snapshot.copy(lastSpeedTestMegabits = lastSpeedTestMegabits)+ }.combine(preferencesRepository.lastSpeedTestTimestamp) { snapshot, lastSpeedTestTimestamp ->+ snapshot.copy(lastSpeedTestTimestamp = lastSpeedTestTimestamp)+ }.combine(preferencesRepository.lastSpeedTestTransport) { snapshot, lastSpeedTestTransport ->+ snapshot.copy(lastSpeedTestTransport = lastSpeedTestTransport)+ }.combine(preferencesRepository.lastSpeedTestRecommendedHeight) { snapshot, lastSpeedTestRecommendedHeight ->+ snapshot.copy(lastSpeedTestRecommendedHeight = lastSpeedTestRecommendedHeight)+ }.combine(preferencesRepository.lastSpeedTestEstimated) { snapshot, lastSpeedTestEstimated ->+ snapshot.copy(lastSpeedTestEstimated = lastSpeedTestEstimated)+ }.combine(preferencesRepository.isIncognitoMode) { snapshot, incognito ->+ snapshot.copy(isIncognitoMode = incognito)+ }.combine(preferencesRepository.useXtreamTextClassification) { snapshot, useTextClass ->+ snapshot.copy(useXtreamTextClassification = useTextClass)+ }.combine(preferencesRepository.liveTvChannelMode) { snapshot, liveTvChannelMode ->+ snapshot.copy(liveTvChannelMode = LiveTvChannelMode.fromStorage(liveTvChannelMode))+ }.combine(preferencesRepository.showLiveSourceSwitcher) { snapshot, showLiveSourceSwitcher ->+ snapshot.copy(showLiveSourceSwitcher = showLiveSourceSwitcher)+ }.combine(preferencesRepository.liveTvCategoryFilters) { snapshot, liveTvCategoryFilters ->+ snapshot.copy(liveTvCategoryFilters = liveTvCategoryFilters)+ }.combine(preferencesRepository.liveTvQuickFilterVisibility) { snapshot, visibilityMode ->+ snapshot.copy(+ liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.fromStorage(visibilityMode)+ )+ }.combine(preferencesRepository.liveChannelNumberingMode) { snapshot, liveChannelNumberingMode ->+ snapshot.copy(liveChannelNumberingMode = liveChannelNumberingMode)+ }.combine(preferencesRepository.vodViewMode) { snapshot, vodViewMode ->+ snapshot.copy(vodViewMode = VodViewMode.fromStorage(vodViewMode))+ }.combine(preferencesRepository.preventStandbyDuringPlayback) { snapshot, preventStandby ->+ snapshot.copy(preventStandbyDuringPlayback = preventStandby)+ }.combine(preferencesRepository.autoCheckAppUpdates) { snapshot, autoCheckAppUpdates ->+ snapshot.copy(autoCheckAppUpdates = autoCheckAppUpdates)+ }.combine(preferencesRepository.lastAppUpdateCheckTimestamp) { snapshot, lastAppUpdateCheckAt ->+ snapshot.copy(lastAppUpdateCheckAt = lastAppUpdateCheckAt)+ }.combine(preferencesRepository.cachedAppUpdateVersionName) { snapshot, versionName ->+ snapshot.copy(cachedAppUpdateVersionName = versionName)+ }.combine(preferencesRepository.cachedAppUpdateVersionCode) { snapshot, versionCode ->+ snapshot.copy(cachedAppUpdateVersionCode = versionCode)+ }.combine(preferencesRepository.cachedAppUpdateReleaseUrl) { snapshot, releaseUrl ->+ snapshot.copy(cachedAppUpdateReleaseUrl = releaseUrl)+ }.combine(preferencesRepository.cachedAppUpdateDownloadUrl) { snapshot, downloadUrl ->+ snapshot.copy(cachedAppUpdateDownloadUrl = downloadUrl)+ }.combine(preferencesRepository.cachedAppUpdateReleaseNotes) { snapshot, releaseNotes ->+ snapshot.copy(cachedAppUpdateReleaseNotes = releaseNotes)+ }.combine(preferencesRepository.cachedAppUpdatePublishedAt) { snapshot, publishedAt ->+ snapshot.copy(cachedAppUpdatePublishedAt = publishedAt)+ }+}++internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferenceSnapshot): SettingsUiState {+ val cachedAppUpdate = snapshot.toCachedAppUpdateUiModel()+ return copy(+ providers = snapshot.providers,+ activeProviderId = snapshot.activeProviderId,+ parentalControlLevel = snapshot.parentalControlLevel,+ hasParentalPin = snapshot.hasParentalPin,+ appLanguage = snapshot.appLanguage,+ preferredAudioLanguage = snapshot.preferredAudioLanguage,+ playerMediaSessionEnabled = snapshot.playerMediaSessionEnabled,+ playerDecoderMode = snapshot.playerDecoderMode,+ playerPlaybackSpeed = snapshot.playerPlaybackSpeed,+ playerControlsTimeoutSeconds = snapshot.playerControlsTimeoutSeconds,+ playerLiveOverlayTimeoutSeconds = snapshot.playerLiveOverlayTimeoutSeconds,+ playerNoticeTimeoutSeconds = snapshot.playerNoticeTimeoutSeconds,+ playerDiagnosticsTimeoutSeconds = snapshot.playerDiagnosticsTimeoutSeconds,+ subtitleTextScale = snapshot.subtitleTextScale,+ subtitleTextColor = snapshot.subtitleTextColor,+ subtitleBackgroundColor = snapshot.subtitleBackgroundColor,+ wifiMaxVideoHeight = snapshot.wifiMaxVideoHeight,+ ethernetMaxVideoHeight = snapshot.ethernetMaxVideoHeight,+ lastSpeedTest = snapshot.lastSpeedTestMegabits?.let {+ InternetSpeedTestUiModel(+ megabitsPerSecond = it,+ measuredAtMs = snapshot.lastSpeedTestTimestamp ?: 0L,+ transportLabel = snapshot.lastSpeedTestTransport ?: InternetSpeedTestTransport.UNKNOWN.name,+ recommendedMaxVideoHeight = snapshot.lastSpeedTestRecommendedHeight,+ isEstimated = snapshot.lastSpeedTestEstimated+ )+ },+ isIncognitoMode = snapshot.isIncognitoMode,+ useXtreamTextClassification = snapshot.useXtreamTextClassification,+ liveTvChannelMode = snapshot.liveTvChannelMode,+ showLiveSourceSwitcher = snapshot.showLiveSourceSwitcher,+ liveTvCategoryFilters = snapshot.liveTvCategoryFilters,+ liveTvQuickFilterVisibilityMode = snapshot.liveTvQuickFilterVisibilityMode,+ liveChannelNumberingMode = snapshot.liveChannelNumberingMode,+ vodViewMode = snapshot.vodViewMode,+ preventStandbyDuringPlayback = snapshot.preventStandbyDuringPlayback,+ autoCheckAppUpdates = snapshot.autoCheckAppUpdates,+ appUpdate = cachedAppUpdate.copy(+ downloadStatus = appUpdate.downloadStatus,+ downloadedVersionName = appUpdate.downloadedVersionName,+ errorMessage = appUpdate.errorMessage+ )+ )+}++internal fun observeProviderDiagnostics(+ providerRepository: ProviderRepository,+ syncMetadataRepository: SyncMetadataRepository,+ application: Application+): Flow<Map<Long, ProviderDiagnosticsUiModel>> {+ return providerRepository.getProviders()+ .flatMapLatest { providers ->+ if (providers.isEmpty()) {+ flowOf(emptyMap())+ } else {+ combine(+ providers.map { provider ->+ syncMetadataRepository.observeMetadata(provider.id).map { metadata ->+ provider.id to ProviderDiagnosticsUiModel(+ lastSyncStatus = metadata?.lastSyncStatus ?: "NONE",+ lastLiveSync = metadata?.lastLiveSync ?: 0L,+ lastMovieSync = metadata?.lastMovieSync ?: 0L,+ lastMovieAttempt = metadata?.lastMovieAttempt ?: 0L,+ lastMovieSuccess = metadata?.lastMovieSuccess ?: 0L,+ lastMoviePartial = metadata?.lastMoviePartial ?: 0L,+ lastSeriesSync = metadata?.lastSeriesSync ?: 0L,+ lastEpgSync = metadata?.lastEpgSync ?: 0L,+ liveCount = metadata?.liveCount ?: 0,+ movieCount = metadata?.movieCount ?: 0,+ seriesCount = metadata?.seriesCount ?: 0,+ epgCount = metadata?.epgCount ?: 0,+ movieSyncMode = metadata?.movieSyncMode ?: VodSyncMode.UNKNOWN,+ movieWarningsCount = metadata?.movieWarningsCount ?: 0,+ movieCatalogStale = metadata?.movieCatalogStale ?: false,+ capabilitySummary = buildCapabilitySummary(application, provider),+ sourceLabel = provider.sourceLabel(),+ expirySummary = provider.expirySummary(),+ connectionSummary = "${provider.maxConnections} connection(s)",+ archiveSummary = provider.archiveSummary()+ )+ }+ }+ ) { pairs ->+ pairs.toMap()+ }+ }+ }+}++internal fun observeCategoryManagement(+ activeProviderIdFlow: Flow<Long?>,+ preferencesRepository: PreferencesRepository,+ categoryRepository: CategoryRepository+): Flow<CategoryManagementSnapshot> {+ return activeProviderIdFlow.flatMapLatest { providerId ->+ if (providerId == null) {+ flowOf(CategoryManagementSnapshot())+ } else {+ combine(+ observeCategorySortModes(providerId, preferencesRepository),+ categoryRepository.getCategories(providerId),+ observeHiddenCategoryIdsByType(providerId, preferencesRepository)+ ) { sortModes, categories, hiddenByType ->+ CategoryManagementSnapshot(+ categorySortModes = sortModes,+ hiddenCategories = categories+ .filter { category -> category.id in hiddenByType[category.type].orEmpty() }+ .sortedWith(compareBy<Category>({ it.type.ordinal }, { it.name.lowercase() }))+ )+ }+ }+ }+}++private fun observeCategorySortModes(+ providerId: Long,+ preferencesRepository: PreferencesRepository+): Flow<Map<ContentType, CategorySortMode>> {+ return combine(+ preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE),+ preferencesRepository.getCategorySortMode(providerId, ContentType.MOVIE),+ preferencesRepository.getCategorySortMode(providerId, ContentType.SERIES)+ ) { liveSort, movieSort, seriesSort ->+ mapOf(+ ContentType.LIVE to liveSort,+ ContentType.MOVIE to movieSort,+ ContentType.SERIES to seriesSort+ )+ }+}++private fun observeHiddenCategoryIdsByType(+ providerId: Long,+ preferencesRepository: PreferencesRepository+): Flow<Map<ContentType, Set<Long>>> {+ return combine(+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.MOVIE),+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.SERIES)+ ) { hiddenLive, hiddenMovies, hiddenSeries ->+ mapOf(+ ContentType.LIVE to hiddenLive,+ ContentType.MOVIE to hiddenMovies,+ ContentType.SERIES to hiddenSeries+ )+ }+}++private fun buildCapabilitySummary(application: Application, provider: Provider): String {+ return when (provider.type) {+ ProviderType.XTREAM_CODES -> {+ if (provider.epgUrl.isNotBlank()) {+ application.getString(R.string.settings_capability_xtream_with_epg)+ } else {+ application.getString(R.string.settings_capability_xtream_without_epg)+ }+ }+ ProviderType.M3U -> {+ if (provider.epgUrl.isNotBlank()) {+ application.getString(R.string.settings_capability_m3u_with_epg)+ } else {+ application.getString(R.string.settings_capability_m3u_without_epg)+ }+ }+ }+}++private fun Provider.sourceLabel(): String = when (type) {+ ProviderType.XTREAM_CODES -> "Xtream Codes"+ ProviderType.M3U -> "M3U Playlist"+}++private fun Provider.expirySummary(): String {+ val expirationDate = expirationDate+ return when {+ expirationDate == null -> "Expiry unknown"+ expirationDate == Long.MAX_VALUE -> "No expiry reported"+ expirationDate < System.currentTimeMillis() -> "Expired"+ else -> {+ val formatter = SimpleDateFormat("d MMM yyyy", Locale.getDefault())+ "Active until ${formatter.format(Date(expirationDate))}"+ }+ }+}++private fun Provider.archiveSummary(): String = when (type) {+ ProviderType.XTREAM_CODES -> "Catch-up depends on provider archive flags and replay stream ids."+ ProviderType.M3U -> {+ if (epgUrl.isBlank()) {+ "M3U replay is limited without guide coverage."+ } else {+ "M3U replay depends on channel templates and guide alignment."+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.ktnew file mode 100644index 00000000..6f0f4849--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsSyncActions.kt@@ -0,0 +1,146 @@+package com.streamvault.app.ui.screens.settings++import android.app.Application+import com.streamvault.app.R+import com.streamvault.app.tvinput.TvInputChannelSyncManager+import com.streamvault.data.sync.SyncManager+import com.streamvault.data.sync.SyncRepairSection+import com.streamvault.domain.model.Result+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class SettingsSyncActions(+ private val appContext: Application,+ private val syncManager: SyncManager,+ private val tvInputChannelSyncManager: TvInputChannelSyncManager,+ private val uiState: MutableStateFlow<SettingsUiState>,+ private val refreshProvider: (CoroutineScope, Long) -> Unit+) {+ fun syncProviderSection(scope: CoroutineScope, providerId: Long, selection: ProviderSyncSelection) {+ scope.launch {+ when (selection) {+ ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> refreshProvider(scope, providerId)+ else -> runSectionSync(providerId, listOf(selection))+ }+ }+ }++ fun syncProviderCustom(scope: CoroutineScope, providerId: Long, selections: Set<ProviderSyncSelection>) {+ scope.launch {+ val orderedSelections = listOf(+ ProviderSyncSelection.TV,+ ProviderSyncSelection.MOVIES,+ ProviderSyncSelection.SERIES,+ ProviderSyncSelection.EPG+ ).filter { it in selections }+ if (orderedSelections.isEmpty()) {+ uiState.update {+ it.copy(userMessage = appContext.getString(R.string.settings_sync_custom_required))+ }+ return@launch+ }+ runSectionSync(providerId, orderedSelections)+ }+ }++ fun retryWarningAction(scope: CoroutineScope, providerId: Long, action: ProviderWarningAction) {+ scope.launch {+ uiState.update { it.copy(isSyncing = true) }+ val section = when (action) {+ ProviderWarningAction.EPG -> SyncRepairSection.EPG+ ProviderWarningAction.MOVIES -> SyncRepairSection.MOVIES+ ProviderWarningAction.SERIES -> SyncRepairSection.SERIES+ }+ val result = syncManager.retrySection(providerId, section)+ uiState.update { state ->+ if (result is Result.Error) {+ state.copy(+ isSyncing = false,+ userMessage = "Retry failed: ${result.message}"+ )+ } else {+ val currentWarnings = state.syncWarningsByProvider[providerId].orEmpty()+ val updatedWarnings = currentWarnings.filterNot { warning ->+ when (action) {+ ProviderWarningAction.EPG -> warning.contains("EPG", ignoreCase = true)+ ProviderWarningAction.MOVIES -> warning.contains("Movies", ignoreCase = true)+ ProviderWarningAction.SERIES -> warning.contains("Series", ignoreCase = true)+ }+ }+ state.copy(+ isSyncing = false,+ userMessage = if (updatedWarnings.isEmpty()) {+ "Section retry succeeded. All current warnings cleared."+ } else {+ "Section retry succeeded."+ },+ syncWarningsByProvider = if (updatedWarnings.isEmpty()) {+ state.syncWarningsByProvider - providerId+ } else {+ state.syncWarningsByProvider + (providerId to updatedWarnings)+ }+ )+ }+ }+ }+ }++ private suspend fun runSectionSync(+ providerId: Long,+ selections: List<ProviderSyncSelection>+ ) {+ uiState.update { it.copy(isSyncing = true) }+ try {+ val failures = mutableListOf<String>()+ val completed = mutableListOf<String>()++ selections.forEach { selection ->+ val section = when (selection) {+ ProviderSyncSelection.TV -> SyncRepairSection.LIVE+ ProviderSyncSelection.MOVIES -> SyncRepairSection.MOVIES+ ProviderSyncSelection.SERIES -> SyncRepairSection.SERIES+ ProviderSyncSelection.EPG -> SyncRepairSection.EPG+ ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> null+ } ?: return@forEach++ when (val result = syncManager.retrySection(providerId, section)) {+ is Result.Error -> failures += "${selection.label(appContext)}: ${result.message}"+ else -> completed += selection.label(appContext)+ }+ }++ if (completed.any {+ it == appContext.getString(R.string.settings_sync_option_all) ||+ it == appContext.getString(R.string.settings_sync_option_tv)+ }+ ) {+ tvInputChannelSyncManager.refreshTvInputCatalog()+ }++ uiState.update { state ->+ state.copy(+ isSyncing = false,+ userMessage = when {+ failures.isEmpty() -> appContext.getString(+ R.string.settings_sync_sections_success,+ completed.joinToString()+ )+ completed.isEmpty() -> appContext.getString(+ R.string.settings_sync_sections_failed,+ failures.joinToString()+ )+ else -> appContext.getString(+ R.string.settings_sync_sections_partial,+ completed.joinToString(),+ failures.joinToString()+ )+ }+ )+ }+ } catch (e: Exception) {+ uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex 48a8dccd..f7b9f189 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -29,15 +29,12 @@ import com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.CombinedM3uProfile-import com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderStatus-import com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingStorageConfigimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.EpgResolutionSummaryimport com.streamvault.domain.model.Result-import com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.usecase.ExportBackupimport com.streamvault.domain.usecase.ExportBackupCommandimport com.streamvault.domain.usecase.ExportBackupResult@@ -60,78 +57,6 @@ import kotlinx.coroutines.launchimport kotlin.math.maximport javax.inject.Inject-enum class ProviderWarningAction {- EPG,- MOVIES,- SERIES-}--enum class ProviderSyncSelection {- ALL,- FAST,- TV,- MOVIES,- SERIES,- EPG-}--private data class SettingsPreferenceSnapshot(- val providers: List<Provider>,- val activeProviderId: Long?,- val parentalControlLevel: Int,- val hasParentalPin: Boolean,- val appLanguage: String,- val preferredAudioLanguage: String,- val playerMediaSessionEnabled: Boolean,- val playerDecoderMode: DecoderMode,- val playerPlaybackSpeed: Float,- val playerControlsTimeoutSeconds: Int,- val playerLiveOverlayTimeoutSeconds: Int,- val playerNoticeTimeoutSeconds: Int,- val playerDiagnosticsTimeoutSeconds: Int,- val subtitleTextScale: Float,- val subtitleTextColor: Int,- val subtitleBackgroundColor: Int,- val wifiMaxVideoHeight: Int?,- val ethernetMaxVideoHeight: Int?,- val lastSpeedTestMegabits: Double?,- val lastSpeedTestTimestamp: Long?,- val lastSpeedTestTransport: String?,- val lastSpeedTestRecommendedHeight: Int?,- val lastSpeedTestEstimated: Boolean,- val isIncognitoMode: Boolean,- val useXtreamTextClassification: Boolean,- val liveTvChannelMode: LiveTvChannelMode,- val showLiveSourceSwitcher: Boolean,- val liveTvCategoryFilters: List<String>,- val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode,- val liveChannelNumberingMode: ChannelNumberingMode,- val vodViewMode: VodViewMode,- val preventStandbyDuringPlayback: Boolean,- val autoCheckAppUpdates: Boolean,- val lastAppUpdateCheckAt: Long?,- val cachedAppUpdateVersionName: String?,- val cachedAppUpdateVersionCode: Int?,- val cachedAppUpdateReleaseUrl: String?,- val cachedAppUpdateDownloadUrl: String?,- val cachedAppUpdateReleaseNotes: String,- val cachedAppUpdatePublishedAt: String?-)--data class AppUpdateUiModel(- val latestVersionName: String? = null,- val latestVersionCode: Int? = null,- val releaseUrl: String? = null,- val downloadUrl: String? = null,- val releaseNotes: String = "",- val publishedAt: String? = null,- val isUpdateAvailable: Boolean = false,- val lastCheckedAt: Long? = null,- val errorMessage: String? = null,- val downloadStatus: AppUpdateDownloadStatus = AppUpdateDownloadStatus.Idle,- val downloadedVersionName: String? = null-)-@HiltViewModel@OptIn(ExperimentalCoroutinesApi::class)class SettingsViewModel @Inject constructor(@@ -155,184 +80,55 @@ class SettingsViewModel @Inject constructor(private val appContext = applicationprivate val exportBackup = ExportBackup(backupManager)private val importBackup = ImportBackup(backupManager)- private var updateCheckInFlight = falseprivate val _uiState = MutableStateFlow(SettingsUiState())val uiState: StateFlow<SettingsUiState> = _uiState.asStateFlow()private val activeProviderIdFlow = providerRepository.getActiveProvider().map { it?.id }+ private val appUpdateActions = SettingsAppUpdateActions(+ appContext = application,+ preferencesRepository = preferencesRepository,+ gitHubReleaseChecker = gitHubReleaseChecker,+ appUpdateInstaller = appUpdateInstaller,+ uiState = _uiState+ )+ private val backupActions = SettingsBackupActions(+ exportBackup = exportBackup,+ importBackup = importBackup,+ uiState = _uiState+ )+ private val recordingActions = SettingsRecordingActions(+ appContext = application,+ recordingManager = recordingManager,+ uiState = _uiState+ )+ private val providerActions = SettingsProviderActions(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ preferencesRepository = preferencesRepository,+ syncProvider = syncProvider,+ tvInputChannelSyncManager = tvInputChannelSyncManager,+ uiState = _uiState+ )+ private val syncActions = SettingsSyncActions(+ appContext = application,+ syncManager = syncManager,+ tvInputChannelSyncManager = tvInputChannelSyncManager,+ uiState = _uiState,+ refreshProvider = { scope, providerId -> providerActions.refreshProvider(scope, providerId) }+ )+ private val epgActions = SettingsEpgActions(+ epgSourceRepository = epgSourceRepository,+ uiState = _uiState+ )init {viewModelScope.launch {- combine(- providerRepository.getProviders(),- activeProviderIdFlow,- preferencesRepository.parentalControlLevel,- preferencesRepository.hasParentalPin- ) { providers, activeId, level, hasParentalPin ->- SettingsPreferenceSnapshot(- providers = providers,- activeProviderId = activeId,- parentalControlLevel = level,- hasParentalPin = hasParentalPin,- appLanguage = "system",- preferredAudioLanguage = "auto",- playerMediaSessionEnabled = true,- playerDecoderMode = DecoderMode.AUTO,- playerPlaybackSpeed = 1f,- playerControlsTimeoutSeconds = 5,- playerLiveOverlayTimeoutSeconds = 4,- playerNoticeTimeoutSeconds = 6,- playerDiagnosticsTimeoutSeconds = 15,- subtitleTextScale = 1f,- subtitleTextColor = 0xFFFFFFFF.toInt(),- subtitleBackgroundColor = 0x80000000.toInt(),- wifiMaxVideoHeight = null,- ethernetMaxVideoHeight = null,- lastSpeedTestMegabits = null,- lastSpeedTestTimestamp = null,- lastSpeedTestTransport = null,- lastSpeedTestRecommendedHeight = null,- lastSpeedTestEstimated = false,- isIncognitoMode = false,- useXtreamTextClassification = true,- liveTvChannelMode = LiveTvChannelMode.PRO,- showLiveSourceSwitcher = false,- liveTvCategoryFilters = emptyList(),- liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,- liveChannelNumberingMode = ChannelNumberingMode.GROUP,- vodViewMode = VodViewMode.MODERN,- preventStandbyDuringPlayback = true,- autoCheckAppUpdates = true,- lastAppUpdateCheckAt = null,- cachedAppUpdateVersionName = null,- cachedAppUpdateVersionCode = null,- cachedAppUpdateReleaseUrl = null,- cachedAppUpdateDownloadUrl = null,- cachedAppUpdateReleaseNotes = "",- cachedAppUpdatePublishedAt = null- )- }.combine(preferencesRepository.appLanguage) { snapshot, language ->- snapshot.copy(appLanguage = language)- }.combine(preferencesRepository.preferredAudioLanguage) { snapshot, preferredAudioLanguage ->- snapshot.copy(preferredAudioLanguage = preferredAudioLanguage ?: "auto")- }.combine(preferencesRepository.playerMediaSessionEnabled) { snapshot, mediaSessionEnabled ->- snapshot.copy(playerMediaSessionEnabled = mediaSessionEnabled)- }.combine(preferencesRepository.playerDecoderMode) { snapshot, decoderMode ->- snapshot.copy(playerDecoderMode = decoderMode)- }.combine(preferencesRepository.playerPlaybackSpeed) { snapshot, playerPlaybackSpeed ->- snapshot.copy(playerPlaybackSpeed = playerPlaybackSpeed)- }.combine(preferencesRepository.playerControlsTimeoutSeconds) { snapshot, timeoutSeconds ->- snapshot.copy(playerControlsTimeoutSeconds = timeoutSeconds)- }.combine(preferencesRepository.playerLiveOverlayTimeoutSeconds) { snapshot, timeoutSeconds ->- snapshot.copy(playerLiveOverlayTimeoutSeconds = timeoutSeconds)- }.combine(preferencesRepository.playerNoticeTimeoutSeconds) { snapshot, timeoutSeconds ->- snapshot.copy(playerNoticeTimeoutSeconds = timeoutSeconds)- }.combine(preferencesRepository.playerDiagnosticsTimeoutSeconds) { snapshot, timeoutSeconds ->- snapshot.copy(playerDiagnosticsTimeoutSeconds = timeoutSeconds)- }.combine(preferencesRepository.playerSubtitleTextScale) { snapshot, subtitleTextScale ->- snapshot.copy(subtitleTextScale = subtitleTextScale)- }.combine(preferencesRepository.playerSubtitleTextColor) { snapshot, subtitleTextColor ->- snapshot.copy(subtitleTextColor = subtitleTextColor)- }.combine(preferencesRepository.playerSubtitleBackgroundColor) { snapshot, subtitleBackgroundColor ->- snapshot.copy(subtitleBackgroundColor = subtitleBackgroundColor)- }.combine(preferencesRepository.playerWifiMaxVideoHeight) { snapshot, wifiMaxVideoHeight ->- snapshot.copy(wifiMaxVideoHeight = wifiMaxVideoHeight)- }.combine(preferencesRepository.playerEthernetMaxVideoHeight) { snapshot, ethernetMaxVideoHeight ->- snapshot.copy(ethernetMaxVideoHeight = ethernetMaxVideoHeight)- }.combine(preferencesRepository.lastSpeedTestMegabits) { snapshot, lastSpeedTestMegabits ->- snapshot.copy(lastSpeedTestMegabits = lastSpeedTestMegabits)- }.combine(preferencesRepository.lastSpeedTestTimestamp) { snapshot, lastSpeedTestTimestamp ->- snapshot.copy(lastSpeedTestTimestamp = lastSpeedTestTimestamp)- }.combine(preferencesRepository.lastSpeedTestTransport) { snapshot, lastSpeedTestTransport ->- snapshot.copy(lastSpeedTestTransport = lastSpeedTestTransport)- }.combine(preferencesRepository.lastSpeedTestRecommendedHeight) { snapshot, lastSpeedTestRecommendedHeight ->- snapshot.copy(lastSpeedTestRecommendedHeight = lastSpeedTestRecommendedHeight)- }.combine(preferencesRepository.lastSpeedTestEstimated) { snapshot, lastSpeedTestEstimated ->- snapshot.copy(lastSpeedTestEstimated = lastSpeedTestEstimated)- }.combine(preferencesRepository.isIncognitoMode) { snapshot, incognito ->- snapshot.copy(isIncognitoMode = incognito)- }.combine(preferencesRepository.useXtreamTextClassification) { snapshot, useTextClass ->- snapshot.copy(useXtreamTextClassification = useTextClass)- }.combine(preferencesRepository.liveTvChannelMode) { snapshot, liveTvChannelMode ->- snapshot.copy(liveTvChannelMode = LiveTvChannelMode.fromStorage(liveTvChannelMode))- }.combine(preferencesRepository.showLiveSourceSwitcher) { snapshot, showLiveSourceSwitcher ->- snapshot.copy(showLiveSourceSwitcher = showLiveSourceSwitcher)- }.combine(preferencesRepository.liveTvCategoryFilters) { snapshot, liveTvCategoryFilters ->- snapshot.copy(liveTvCategoryFilters = liveTvCategoryFilters)- }.combine(preferencesRepository.liveTvQuickFilterVisibility) { snapshot, visibilityMode ->- snapshot.copy(- liveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.fromStorage(visibilityMode)- )- }.combine(preferencesRepository.liveChannelNumberingMode) { snapshot, liveChannelNumberingMode ->- snapshot.copy(liveChannelNumberingMode = liveChannelNumberingMode)- }.combine(preferencesRepository.vodViewMode) { snapshot, vodViewMode ->- snapshot.copy(vodViewMode = VodViewMode.fromStorage(vodViewMode))- }.combine(preferencesRepository.preventStandbyDuringPlayback) { snapshot, preventStandby ->- snapshot.copy(preventStandbyDuringPlayback = preventStandby)- }.combine(preferencesRepository.autoCheckAppUpdates) { snapshot, autoCheckAppUpdates ->- snapshot.copy(autoCheckAppUpdates = autoCheckAppUpdates)- }.combine(preferencesRepository.lastAppUpdateCheckTimestamp) { snapshot, lastAppUpdateCheckAt ->- snapshot.copy(lastAppUpdateCheckAt = lastAppUpdateCheckAt)- }.combine(preferencesRepository.cachedAppUpdateVersionName) { snapshot, versionName ->- snapshot.copy(cachedAppUpdateVersionName = versionName)- }.combine(preferencesRepository.cachedAppUpdateVersionCode) { snapshot, versionCode ->- snapshot.copy(cachedAppUpdateVersionCode = versionCode)- }.combine(preferencesRepository.cachedAppUpdateReleaseUrl) { snapshot, releaseUrl ->- snapshot.copy(cachedAppUpdateReleaseUrl = releaseUrl)- }.combine(preferencesRepository.cachedAppUpdateDownloadUrl) { snapshot, downloadUrl ->- snapshot.copy(cachedAppUpdateDownloadUrl = downloadUrl)- }.combine(preferencesRepository.cachedAppUpdateReleaseNotes) { snapshot, releaseNotes ->- snapshot.copy(cachedAppUpdateReleaseNotes = releaseNotes)- }.combine(preferencesRepository.cachedAppUpdatePublishedAt) { snapshot, publishedAt ->- snapshot.copy(cachedAppUpdatePublishedAt = publishedAt)- }.collect { snapshot ->- val cachedAppUpdate = snapshot.toCachedAppUpdateUiModel()- _uiState.update {- it.copy(- providers = snapshot.providers,- activeProviderId = snapshot.activeProviderId,- parentalControlLevel = snapshot.parentalControlLevel,- hasParentalPin = snapshot.hasParentalPin,- appLanguage = snapshot.appLanguage,- preferredAudioLanguage = snapshot.preferredAudioLanguage,- playerMediaSessionEnabled = snapshot.playerMediaSessionEnabled,- playerDecoderMode = snapshot.playerDecoderMode,- playerPlaybackSpeed = snapshot.playerPlaybackSpeed,- playerControlsTimeoutSeconds = snapshot.playerControlsTimeoutSeconds,- playerLiveOverlayTimeoutSeconds = snapshot.playerLiveOverlayTimeoutSeconds,- playerNoticeTimeoutSeconds = snapshot.playerNoticeTimeoutSeconds,- playerDiagnosticsTimeoutSeconds = snapshot.playerDiagnosticsTimeoutSeconds,- subtitleTextScale = snapshot.subtitleTextScale,- subtitleTextColor = snapshot.subtitleTextColor,- subtitleBackgroundColor = snapshot.subtitleBackgroundColor,- wifiMaxVideoHeight = snapshot.wifiMaxVideoHeight,- ethernetMaxVideoHeight = snapshot.ethernetMaxVideoHeight,- lastSpeedTest = snapshot.lastSpeedTestMegabits?.let {- InternetSpeedTestUiModel(- megabitsPerSecond = it,- measuredAtMs = snapshot.lastSpeedTestTimestamp ?: 0L,- transportLabel = snapshot.lastSpeedTestTransport ?: InternetSpeedTestTransport.UNKNOWN.name,- recommendedMaxVideoHeight = snapshot.lastSpeedTestRecommendedHeight,- isEstimated = snapshot.lastSpeedTestEstimated- )- },- isIncognitoMode = snapshot.isIncognitoMode,- useXtreamTextClassification = snapshot.useXtreamTextClassification,- liveTvChannelMode = snapshot.liveTvChannelMode,- showLiveSourceSwitcher = snapshot.showLiveSourceSwitcher,- liveTvCategoryFilters = snapshot.liveTvCategoryFilters,- liveTvQuickFilterVisibilityMode = snapshot.liveTvQuickFilterVisibilityMode,- liveChannelNumberingMode = snapshot.liveChannelNumberingMode,- vodViewMode = snapshot.vodViewMode,- preventStandbyDuringPlayback = snapshot.preventStandbyDuringPlayback,- autoCheckAppUpdates = snapshot.autoCheckAppUpdates,- appUpdate = cachedAppUpdate.copy(- downloadStatus = it.appUpdate.downloadStatus,- downloadedVersionName = it.appUpdate.downloadedVersionName,- errorMessage = it.appUpdate.errorMessage- )- )- }+ observeSettingsPreferenceSnapshot(+ providerRepository = providerRepository,+ activeProviderIdFlow = activeProviderIdFlow,+ preferencesRepository = preferencesRepository+ ).collect { snapshot ->+ _uiState.update { it.applyPreferenceSnapshot(snapshot) }}}@@ -343,8 +139,12 @@ class SettingsViewModel @Inject constructor() { autoCheckEnabled, lastCheckedAt ->autoCheckEnabled to lastCheckedAt}.distinctUntilChanged().collect { (autoCheckEnabled, lastCheckedAt) ->- if (autoCheckEnabled && shouldAutoCheckForUpdates(lastCheckedAt)) {- checkForAppUpdates(manual = false)+ if (autoCheckEnabled && appUpdateActions.shouldAutoCheckForUpdates(lastCheckedAt)) {+ appUpdateActions.checkForAppUpdates(+ scope = viewModelScope,+ manual = false,+ isRemoteVersionNewer = ::isRemoteVersionNewer+ )}}}@@ -380,114 +180,28 @@ class SettingsViewModel @Inject constructor(}viewModelScope.launch {- providerRepository.getProviders()- .flatMapLatest { providers ->- if (providers.isEmpty()) {- flowOf(emptyMap())- } else {- combine(- providers.map { provider ->- syncMetadataRepository.observeMetadata(provider.id).map { metadata ->- provider.id to ProviderDiagnosticsUiModel(- lastSyncStatus = metadata?.lastSyncStatus ?: "NONE",- lastLiveSync = metadata?.lastLiveSync ?: 0L,- lastMovieSync = metadata?.lastMovieSync ?: 0L,- lastMovieAttempt = metadata?.lastMovieAttempt ?: 0L,- lastMovieSuccess = metadata?.lastMovieSuccess ?: 0L,- lastMoviePartial = metadata?.lastMoviePartial ?: 0L,- lastSeriesSync = metadata?.lastSeriesSync ?: 0L,- lastEpgSync = metadata?.lastEpgSync ?: 0L,- liveCount = metadata?.liveCount ?: 0,- movieCount = metadata?.movieCount ?: 0,- seriesCount = metadata?.seriesCount ?: 0,- epgCount = metadata?.epgCount ?: 0,- movieSyncMode = metadata?.movieSyncMode ?: VodSyncMode.UNKNOWN,- movieWarningsCount = metadata?.movieWarningsCount ?: 0,- movieCatalogStale = metadata?.movieCatalogStale ?: false,- capabilitySummary = buildCapabilitySummary(provider),- sourceLabel = when (provider.type) {- ProviderType.XTREAM_CODES -> "Xtream Codes"- ProviderType.M3U -> "M3U Playlist"- },- expirySummary = run {- val expirationDate = provider.expirationDate- when {- expirationDate == null -> "Expiry unknown"- expirationDate == Long.MAX_VALUE -> "No expiry reported"- expirationDate < System.currentTimeMillis() -> "Expired"- else -> "Active until ${java.text.SimpleDateFormat("d MMM yyyy", java.util.Locale.getDefault()).format(java.util.Date(expirationDate))}"- }- },- connectionSummary = "${provider.maxConnections} connection(s)",- archiveSummary = when (provider.type) {- ProviderType.XTREAM_CODES -> "Catch-up depends on provider archive flags and replay stream ids."- ProviderType.M3U -> if (provider.epgUrl.isBlank()) {- "M3U replay is limited without guide coverage."- } else {- "M3U replay depends on channel templates and guide alignment."- }- }- )- }- }- ) { pairs ->- pairs.toMap()- }- }- }- .collect { diagnosticsByProvider ->- _uiState.update { it.copy(diagnosticsByProvider = diagnosticsByProvider) }- }+ observeProviderDiagnostics(+ providerRepository = providerRepository,+ syncMetadataRepository = syncMetadataRepository,+ application = appContext+ ).collect { diagnosticsByProvider ->+ _uiState.update { it.copy(diagnosticsByProvider = diagnosticsByProvider) }+ }}viewModelScope.launch {- activeProviderIdFlow- .flatMapLatest { providerId ->- if (providerId == null) {- flowOf(CategoryManagementSnapshot())- } else {- combine(- preferencesRepository.getCategorySortMode(providerId, ContentType.LIVE),- preferencesRepository.getCategorySortMode(providerId, ContentType.MOVIE),- preferencesRepository.getCategorySortMode(providerId, ContentType.SERIES),- categoryRepository.getCategories(providerId),- preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),- preferencesRepository.getHiddenCategoryIds(providerId, ContentType.MOVIE),- preferencesRepository.getHiddenCategoryIds(providerId, ContentType.SERIES)- ) { values ->- val liveSort = values[0] as CategorySortMode- val movieSort = values[1] as CategorySortMode- val seriesSort = values[2] as CategorySortMode- val categories = values[3] as List<Category>- val hiddenLive = values[4] as Set<Long>- val hiddenMovies = values[5] as Set<Long>- val hiddenSeries = values[6] as Set<Long>- val hiddenByType = mapOf(- ContentType.LIVE to hiddenLive,- ContentType.MOVIE to hiddenMovies,- ContentType.SERIES to hiddenSeries- )- CategoryManagementSnapshot(- categorySortModes = mapOf(- ContentType.LIVE to liveSort,- ContentType.MOVIE to movieSort,- ContentType.SERIES to seriesSort- ),- hiddenCategories = categories- .filter { category -> category.id in hiddenByType[category.type].orEmpty() }- .sortedWith(compareBy<Category>({ it.type.ordinal }, { it.name.lowercase() }))- )- }- }- }- .collect { snapshot ->- _uiState.update {- it.copy(- categorySortModes = snapshot.categorySortModes,- hiddenCategories = snapshot.hiddenCategories- )- }+ observeCategoryManagement(+ activeProviderIdFlow = activeProviderIdFlow,+ preferencesRepository = preferencesRepository,+ categoryRepository = categoryRepository+ ).collect { snapshot ->+ _uiState.update {+ it.copy(+ categorySortModes = snapshot.categorySortModes,+ hiddenCategories = snapshot.hiddenCategories+ )}+ }}viewModelScope.launch {@@ -504,136 +218,43 @@ class SettingsViewModel @Inject constructor(}fun setActiveProvider(providerId: Long) {- viewModelScope.launch {- preferencesRepository.setLastActiveProviderId(providerId)- combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.ProviderSource(providerId))- providerRepository.setActiveProvider(providerId)- // Force sync on connect- refreshProvider(providerId)- }+ providerActions.setActiveProvider(viewModelScope, providerId)}fun setActiveCombinedProfile(profileId: Long) {- viewModelScope.launch {- when (combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(profileId))) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Combined M3U source activated") }- is Result.Error -> _uiState.update { it.copy(userMessage = "Could not activate combined source") }- Result.Loading -> Unit- }- }+ providerActions.setActiveCombinedProfile(viewModelScope, profileId)}fun createCombinedProfile(name: String, providerIds: List<Long>) {- viewModelScope.launch {- when (val result = combinedM3uRepository.createProfile(name, providerIds)) {- is Result.Success -> {- combinedM3uRepository.setActiveLiveSource(ActiveLiveSource.CombinedM3uSource(result.data.id))- _uiState.update { it.copy(userMessage = "Combined M3U source created") }- }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.createCombinedProfile(viewModelScope, name, providerIds)}fun deleteCombinedProfile(profileId: Long) {- viewModelScope.launch {- when (val result = combinedM3uRepository.deleteProfile(profileId)) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Combined M3U source deleted") }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.deleteCombinedProfile(viewModelScope, profileId)}fun addProviderToCombinedProfile(profileId: Long, providerId: Long) {- viewModelScope.launch {- when (val result = combinedM3uRepository.addProvider(profileId, providerId)) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Playlist added to combined source") }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.addProviderToCombinedProfile(viewModelScope, profileId, providerId)}fun renameCombinedProfile(profileId: Long, name: String) {- viewModelScope.launch {- when (val result = combinedM3uRepository.updateProfileName(profileId, name)) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Combined M3U source renamed") }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.renameCombinedProfile(viewModelScope, profileId, name)}fun removeProviderFromCombinedProfile(profileId: Long, providerId: Long) {- viewModelScope.launch {- when (val result = combinedM3uRepository.removeProvider(profileId, providerId)) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Playlist removed from combined source") }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.removeProviderFromCombinedProfile(viewModelScope, profileId, providerId)}fun moveCombinedProvider(profileId: Long, providerId: Long, moveUp: Boolean) {- viewModelScope.launch {- val profile = _uiState.value.combinedProfiles.firstOrNull { it.id == profileId }- ?: return@launch- val orderedProviderIds = profile.members- .sortedBy { it.priority }- .map { it.providerId }- .toMutableList()- val currentIndex = orderedProviderIds.indexOf(providerId)- if (currentIndex == -1) return@launch- val targetIndex = if (moveUp) currentIndex - 1 else currentIndex + 1- if (targetIndex !in orderedProviderIds.indices) return@launch- java.util.Collections.swap(orderedProviderIds, currentIndex, targetIndex)- when (val result = combinedM3uRepository.reorderMembers(profileId, orderedProviderIds)) {- is Result.Success -> _uiState.update { it.copy(userMessage = "Combined playlist order updated") }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.moveCombinedProvider(viewModelScope, profileId, providerId, moveUp)}fun setCombinedProviderEnabled(profileId: Long, providerId: Long, enabled: Boolean) {- viewModelScope.launch {- when (val result = combinedM3uRepository.setMemberEnabled(profileId, providerId, enabled)) {- is Result.Success -> _uiState.update {- it.copy(userMessage = if (enabled) "Playlist enabled in combined source" else "Playlist disabled in combined source")- }- is Result.Error -> _uiState.update { it.copy(userMessage = result.message) }- Result.Loading -> Unit- }- }+ providerActions.setCombinedProviderEnabled(viewModelScope, profileId, providerId, enabled)}fun setM3uVodClassificationEnabled(providerId: Long, enabled: Boolean) {- viewModelScope.launch {- val provider = providerRepository.getProvider(providerId) ?: return@launch- if (provider.type != ProviderType.M3U) return@launch- when (- val result = providerRepository.updateProvider(- provider.copy(m3uVodClassificationEnabled = enabled)- )- ) {- is Result.Error -> {- _uiState.update { it.copy(userMessage = "Could not save provider setting: ${result.message}") }- }- else -> {- _uiState.update {- it.copy(- userMessage = if (enabled) {- "M3U VOD classification enabled. Refresh the playlist to reclassify content."- } else {- "M3U VOD classification disabled. Refresh the playlist to reclassify content."- }- )- }- }- }- }+ providerActions.setM3uVodClassificationEnabled(viewModelScope, providerId, enabled)}fun refreshProviderClassification(providerId: Long) {@@ -730,42 +351,19 @@ class SettingsViewModel @Inject constructor(}fun checkForAppUpdates() {- checkForAppUpdates(manual = true)+ appUpdateActions.checkForAppUpdates(+ scope = viewModelScope,+ manual = true,+ isRemoteVersionNewer = ::isRemoteVersionNewer+ )}fun downloadLatestUpdate() {- val latestRelease = _uiState.value.appUpdate.toReleaseInfoOrNull() ?: run {- _uiState.update {- it.copy(userMessage = appContext.getString(R.string.settings_update_download_unavailable))- }- return- }-- viewModelScope.launch {- when (val result = appUpdateInstaller.startDownload(latestRelease)) {- is Result.Error -> _uiState.update {- it.copy(userMessage = result.message)- }- is Result.Success -> _uiState.update {- it.copy(userMessage = appContext.getString(R.string.settings_update_download_started))- }- else -> Unit- }- }+ appUpdateActions.downloadLatestUpdate(viewModelScope)}fun installDownloadedUpdate() {- viewModelScope.launch {- when (val result = appUpdateInstaller.installDownloadedUpdate()) {- is Result.Error -> _uiState.update {- it.copy(userMessage = result.message)- }- is Result.Success -> _uiState.update {- it.copy(userMessage = appContext.getString(R.string.settings_update_install_started))- }- else -> Unit- }- }+ appUpdateActions.installDownloadedUpdate(viewModelScope)}fun setCategorySortMode(type: ContentType, mode: CategorySortMode) {@@ -964,257 +562,29 @@ class SettingsViewModel @Inject constructor(}fun refreshProvider(providerId: Long, movieFastSyncOverride: Boolean? = null) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- try {- val result = syncProvider(- SyncProviderCommand(- providerId = providerId,- force = true,- movieFastSyncOverride = movieFastSyncOverride- )- )- if (result !is SyncProviderResult.Error) {- tvInputChannelSyncManager.refreshTvInputCatalog()- }- _uiState.update { state ->- val partialWarnings = (result as? SyncProviderResult.Success)?.warnings.orEmpty()- val warningsMessage = partialWarnings- .take(3)- .joinToString(separator = ", ")- .ifBlank { "Some sections are incomplete." }- state.copy(- isSyncing = false,- userMessage = when {- result is SyncProviderResult.Error -> "Refresh failed: ${result.message}"- (result as? SyncProviderResult.Success)?.isPartial == true -> "Refresh completed with warnings: $warningsMessage"- else -> "Provider refreshed successfully"- },- syncWarningsByProvider = when {- result is SyncProviderResult.Error -> state.syncWarningsByProvider - providerId- (result as? SyncProviderResult.Success)?.isPartial == true -> state.syncWarningsByProvider + (providerId to partialWarnings)- else -> state.syncWarningsByProvider - providerId- }- )- }- } catch (e: Exception) {- _uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }- }- }+ providerActions.refreshProvider(viewModelScope, providerId, movieFastSyncOverride)}fun syncProviderSection(providerId: Long, selection: ProviderSyncSelection) {- viewModelScope.launch {- when (selection) {- ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> refreshProvider(providerId)- else -> runSectionSync(providerId, listOf(selection))- }- }+ syncActions.syncProviderSection(viewModelScope, providerId, selection)}fun syncProviderCustom(providerId: Long, selections: Set<ProviderSyncSelection>) {- viewModelScope.launch {- val orderedSelections = listOf(- ProviderSyncSelection.TV,- ProviderSyncSelection.MOVIES,- ProviderSyncSelection.SERIES,- ProviderSyncSelection.EPG- ).filter { it in selections }- if (orderedSelections.isEmpty()) {- _uiState.update {- it.copy(userMessage = appContext.getString(R.string.settings_sync_custom_required))- }- return@launch- }- runSectionSync(providerId, orderedSelections)- }+ syncActions.syncProviderCustom(viewModelScope, providerId, selections)}fun retryWarningAction(providerId: Long, action: ProviderWarningAction) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val section = when (action) {- ProviderWarningAction.EPG -> SyncRepairSection.EPG- ProviderWarningAction.MOVIES -> SyncRepairSection.MOVIES- ProviderWarningAction.SERIES -> SyncRepairSection.SERIES- }- val result = syncManager.retrySection(providerId, section)- _uiState.update { state ->- if (result is Result.Error) {- state.copy(- isSyncing = false,- userMessage = "Retry failed: ${result.message}"- )- } else {- val currentWarnings = state.syncWarningsByProvider[providerId].orEmpty()- val updatedWarnings = currentWarnings.filterNot { warning ->- when (action) {- ProviderWarningAction.EPG -> warning.contains("EPG", ignoreCase = true)- ProviderWarningAction.MOVIES -> warning.contains("Movies", ignoreCase = true)- ProviderWarningAction.SERIES -> warning.contains("Series", ignoreCase = true)- }- }- state.copy(- isSyncing = false,- userMessage = if (updatedWarnings.isEmpty()) {- "Section retry succeeded. All current warnings cleared."- } else {- "Section retry succeeded."- },- syncWarningsByProvider = if (updatedWarnings.isEmpty()) {- state.syncWarningsByProvider - providerId- } else {- state.syncWarningsByProvider + (providerId to updatedWarnings)- }- )- }- }- }- }-- private suspend fun runSectionSync(- providerId: Long,- selections: List<ProviderSyncSelection>- ) {- _uiState.update { it.copy(isSyncing = true) }- try {- val failures = mutableListOf<String>()- val completed = mutableListOf<String>()-- selections.forEach { selection ->- val section = when (selection) {- ProviderSyncSelection.TV -> SyncRepairSection.LIVE- ProviderSyncSelection.MOVIES -> SyncRepairSection.MOVIES- ProviderSyncSelection.SERIES -> SyncRepairSection.SERIES- ProviderSyncSelection.EPG -> SyncRepairSection.EPG- ProviderSyncSelection.ALL, ProviderSyncSelection.FAST -> null- } ?: return@forEach-- when (val result = syncManager.retrySection(providerId, section)) {- is Result.Error -> failures += "${selection.label(appContext)}: ${result.message}"- else -> completed += selection.label(appContext)- }- }-- if (completed.any { it == appContext.getString(R.string.settings_sync_option_all) || it == appContext.getString(R.string.settings_sync_option_tv) }) {- tvInputChannelSyncManager.refreshTvInputCatalog()- }-- _uiState.update { state ->- state.copy(- isSyncing = false,- userMessage = when {- failures.isEmpty() -> appContext.getString(- R.string.settings_sync_sections_success,- completed.joinToString()- )- completed.isEmpty() -> appContext.getString(- R.string.settings_sync_sections_failed,- failures.joinToString()- )- else -> appContext.getString(- R.string.settings_sync_sections_partial,- completed.joinToString(),- failures.joinToString()- )- }- )- }- } catch (e: Exception) {- _uiState.update { it.copy(isSyncing = false, userMessage = "Sync failed: ${e.message}") }- }+ syncActions.retryWarningAction(viewModelScope, providerId, action)}fun deleteProvider(providerId: Long) {- viewModelScope.launch {- providerRepository.deleteProvider(providerId)- }+ providerActions.deleteProvider(viewModelScope, providerId)}fun userMessageShown() {_uiState.update { it.copy(userMessage = null) }}- private fun checkForAppUpdates(manual: Boolean) {- if (updateCheckInFlight) return- updateCheckInFlight = true- viewModelScope.launch {- val checkedAt = System.currentTimeMillis()- _uiState.update {- it.copy(- isCheckingForUpdates = true,- appUpdate = it.appUpdate.copy(errorMessage = null)- )- }- preferencesRepository.setLastAppUpdateCheckTimestamp(checkedAt)- when (val result = gitHubReleaseChecker.fetchLatestRelease()) {- is Result.Error -> {- _uiState.update {- it.copy(- isCheckingForUpdates = false,- userMessage = if (manual) result.message else it.userMessage,- appUpdate = it.appUpdate.copy(- lastCheckedAt = checkedAt,- errorMessage = result.message- )- )- }- }- is Result.Success -> {- val release = result.data- preferencesRepository.setCachedAppUpdateRelease(- versionName = release.versionName,- versionCode = release.versionCode,- releaseUrl = release.releaseUrl,- downloadUrl = release.downloadUrl,- releaseNotes = release.releaseNotes,- publishedAt = release.publishedAt- )- val updateAvailable = isRemoteVersionNewer(- remoteVersionCode = release.versionCode,- remoteVersionName = release.versionName- )- _uiState.update {- it.copy(- isCheckingForUpdates = false,- userMessage = if (manual) {- if (updateAvailable) {- appContext.getString(R.string.settings_update_available_message, release.versionName)- } else {- appContext.getString(R.string.settings_update_current_message)- }- } else {- it.userMessage- },- appUpdate = AppUpdateUiModel(- latestVersionName = release.versionName,- latestVersionCode = release.versionCode,- releaseUrl = release.releaseUrl,- downloadUrl = release.downloadUrl,- releaseNotes = release.releaseNotes,- publishedAt = release.publishedAt,- isUpdateAvailable = updateAvailable,- lastCheckedAt = checkedAt,- errorMessage = null- ).withDownloadState(it.appUpdate.toDownloadState())- )- }- appUpdateInstaller.refreshState()- }- else -> {- _uiState.update { it.copy(isCheckingForUpdates = false) }- }- }- updateCheckInFlight = false- }- }-- private fun shouldAutoCheckForUpdates(lastCheckedAt: Long?): Boolean {- val now = System.currentTimeMillis()- val checkIntervalMs = 24L * 60L * 60L * 1000L- return lastCheckedAt == null || now - lastCheckedAt >= checkIntervalMs- }-private fun isRemoteVersionNewer(remoteVersionCode: Int?, remoteVersionName: String): Boolean {if (remoteVersionCode != null && remoteVersionCode > BuildConfig.VERSION_CODE) {return true@@ -1237,598 +607,128 @@ class SettingsViewModel @Inject constructor(}fun exportConfig(uriString: String) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val result = exportBackup(ExportBackupCommand(uriString))- _uiState.update { state ->- state.copy(- isSyncing = false,- userMessage = if (result is ExportBackupResult.Error)- "Export failed: ${result.message}"- else "Configuration exported successfully"- )- }- }+ backupActions.exportConfig(viewModelScope, uriString)}fun inspectBackup(uriString: String) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val result = importBackup.inspect(InspectBackupCommand(uriString))- _uiState.update { state ->- when (result) {- is InspectBackupResult.Error -> state.copy(- isSyncing = false,- userMessage = "Import failed: ${result.message}"- )- is InspectBackupResult.Success -> state.copy(- isSyncing = false,- pendingBackupUri = result.uriString,- backupPreview = result.preview,- backupImportPlan = result.defaultPlan- )- }- }- }+ backupActions.inspectBackup(viewModelScope, uriString)}fun dismissBackupPreview() {- _uiState.update {- it.copy(- backupPreview = null,- pendingBackupUri = null,- backupImportPlan = BackupImportPlan()- )- }+ backupActions.dismissBackupPreview()}fun setBackupConflictStrategy(strategy: BackupConflictStrategy) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(conflictStrategy = strategy)) }+ backupActions.setBackupConflictStrategy(strategy)}fun setImportPreferences(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPreferences = enabled)) }+ backupActions.setImportPreferences(enabled)}fun setImportProviders(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importProviders = enabled)) }+ backupActions.setImportProviders(enabled)}fun setImportSavedLibrary(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importSavedLibrary = enabled)) }+ backupActions.setImportSavedLibrary(enabled)}fun setImportPlaybackHistory(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPlaybackHistory = enabled)) }+ backupActions.setImportPlaybackHistory(enabled)}fun setImportMultiViewPresets(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importMultiViewPresets = enabled)) }+ backupActions.setImportMultiViewPresets(enabled)}fun setImportRecordingSchedules(enabled: Boolean) {- _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importRecordingSchedules = enabled)) }+ backupActions.setImportRecordingSchedules(enabled)}fun confirmBackupImport() {- val uriString = _uiState.value.pendingBackupUri ?: return- val plan = _uiState.value.backupImportPlan- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val result = importBackup.confirm(ImportBackupCommand(uriString, plan))- _uiState.update { state ->- state.copy(- isSyncing = false,- userMessage = if (result is ImportBackupResult.Error)- "Import failed: ${result.message}"- else "Configuration imported: ${(result as ImportBackupResult.Success).importedSummary}",- backupPreview = null,- pendingBackupUri = null,- backupImportPlan = BackupImportPlan()- )- }- }+ backupActions.confirmBackupImport(viewModelScope)}fun stopRecording(recordingId: String) {- viewModelScope.launch {- val result = recordingManager.stopRecording(recordingId)- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_stop_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_stopped)- }- )- }- }+ recordingActions.stopRecording(viewModelScope, recordingId)}fun cancelRecording(recordingId: String) {- viewModelScope.launch {- val result = recordingManager.cancelRecording(recordingId)- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_cancel_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_cancelled)- }- )- }- }+ recordingActions.cancelRecording(viewModelScope, recordingId)}fun deleteRecording(recordingId: String) {- viewModelScope.launch {- val result = recordingManager.deleteRecording(recordingId)- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_delete_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_deleted)- }- )- }- }+ recordingActions.deleteRecording(viewModelScope, recordingId)}fun retryRecording(recordingId: String) {- viewModelScope.launch {- val result = recordingManager.retryRecording(recordingId)- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_retry_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_retry_started)- }- )- }- }+ recordingActions.retryRecording(viewModelScope, recordingId)}fun setRecordingScheduleEnabled(recordingId: String, enabled: Boolean) {- viewModelScope.launch {- val result = recordingManager.setScheduleEnabled(recordingId, enabled)- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_schedule_toggle_failed, result.message)- } else {- appContext.getString(- if (enabled) R.string.settings_recording_schedule_enabled- else R.string.settings_recording_schedule_disabled- )- }- )- }- }+ recordingActions.setRecordingScheduleEnabled(viewModelScope, recordingId, enabled)}fun reconcileRecordings() {- viewModelScope.launch {- val result = recordingManager.reconcileRecordingState()- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_reconcile_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_reconcile_complete)- }- )- }- }+ recordingActions.reconcileRecordings(viewModelScope)}fun updateRecordingFolder(treeUri: String?, displayName: String?) {- viewModelScope.launch {- val current = _uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = treeUri,- displayName = displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_storage_update_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_storage_updated)- }- )- }- }+ recordingActions.updateRecordingFolder(viewModelScope, treeUri, displayName)}fun updateRecordingFileNamePattern(pattern: String) {- viewModelScope.launch {- val current = _uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = pattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_pattern_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_pattern_saved)- }- )- }- }+ recordingActions.updateRecordingFileNamePattern(viewModelScope, pattern)}fun updateRecordingRetentionDays(retentionDays: Int?) {- viewModelScope.launch {- val current = _uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = retentionDays,- maxSimultaneousRecordings = current.maxSimultaneousRecordings- )- )- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_retention_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_retention_saved)- }- )- }- }+ recordingActions.updateRecordingRetentionDays(viewModelScope, retentionDays)}fun updateRecordingMaxSimultaneous(maxSimultaneousRecordings: Int) {- viewModelScope.launch {- val current = _uiState.value.recordingStorageState- val result = recordingManager.updateStorageConfig(- RecordingStorageConfig(- treeUri = current.treeUri,- displayName = current.displayName,- fileNamePattern = current.fileNamePattern,- retentionDays = current.retentionDays,- maxSimultaneousRecordings = maxSimultaneousRecordings- )- )- _uiState.update {- it.copy(- userMessage = if (result is Result.Error) {- appContext.getString(R.string.settings_recording_concurrency_failed, result.message)- } else {- appContext.getString(R.string.settings_recording_concurrency_saved)- }- )- }- }+ recordingActions.updateRecordingMaxSimultaneous(viewModelScope, maxSimultaneousRecordings)}// ── EPG Source Management ────────────────────────────────────────fun loadEpgSources() {- viewModelScope.launch {- epgSourceRepository.getAllSources().collect { sources ->- _uiState.update { it.copy(epgSources = sources) }- }- }+ epgActions.loadEpgSources(viewModelScope)}fun loadEpgAssignments(providerId: Long) {- viewModelScope.launch {- epgSourceRepository.getAssignmentsForProvider(providerId).collect { assignments ->- val summary = epgSourceRepository.getResolutionSummary(providerId)- _uiState.update {- it.copy(- epgSourceAssignments = it.epgSourceAssignments + (providerId to assignments),- epgResolutionSummaries = it.epgResolutionSummaries + (providerId to summary)- )- }- }- }+ epgActions.loadEpgAssignments(viewModelScope, providerId)}fun addEpgSource(name: String, url: String) {- viewModelScope.launch {- val result = epgSourceRepository.addSource(name, url)- if (result is Result.Error) {- _uiState.update { it.copy(userMessage = result.message) }- }- }+ epgActions.addEpgSource(viewModelScope, name, url)}fun deleteEpgSource(sourceId: Long) {- viewModelScope.launch {- val affectedProviders = loadedProvidersForSource(sourceId)- epgSourceRepository.deleteSource(sourceId)- refreshLoadedResolutionSummaries(affectedProviders)- }+ epgActions.deleteEpgSource(viewModelScope, sourceId)}fun toggleEpgSourceEnabled(sourceId: Long, enabled: Boolean) {- viewModelScope.launch {- val affectedProviders = loadedProvidersForSource(sourceId)- epgSourceRepository.setSourceEnabled(sourceId, enabled)- refreshLoadedResolutionSummaries(affectedProviders)- }+ epgActions.toggleEpgSourceEnabled(viewModelScope, sourceId, enabled)}fun refreshEpgSource(sourceId: Long) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val affectedProviders = loadedProvidersForSource(sourceId)- val result = epgSourceRepository.refreshSource(sourceId)- if (result !is Result.Error) {- refreshLoadedResolutionSummaries(affectedProviders)- }- _uiState.update {- it.copy(- isSyncing = false,- userMessage = if (result is Result.Error) result.message else "EPG source refreshed"- )- }- }+ epgActions.refreshEpgSource(viewModelScope, sourceId)}fun assignEpgSourceToProvider(providerId: Long, epgSourceId: Long) {- viewModelScope.launch {- val existingAssignments = _uiState.value.epgSourceAssignments[providerId].orEmpty()- val nextPriority = (existingAssignments.maxOfOrNull { it.priority } ?: 0) + 1- val result = epgSourceRepository.assignSourceToProvider(providerId, epgSourceId, nextPriority)- if (result is Result.Error) {- _uiState.update { it.copy(userMessage = result.message) }- } else {- refreshProviderEpgSummary(providerId)- }- }+ epgActions.assignEpgSourceToProvider(viewModelScope, providerId, epgSourceId)}fun unassignEpgSourceFromProvider(providerId: Long, epgSourceId: Long) {- viewModelScope.launch {- epgSourceRepository.unassignSourceFromProvider(providerId, epgSourceId)- refreshProviderEpgSummary(providerId)- }+ epgActions.unassignEpgSourceFromProvider(viewModelScope, providerId, epgSourceId)}fun moveEpgSourceAssignmentUp(providerId: Long, epgSourceId: Long) {- viewModelScope.launch {- val assignments = _uiState.value.epgSourceAssignments[providerId].orEmpty()- .sortedBy { it.priority }- val index = assignments.indexOfFirst { it.epgSourceId == epgSourceId }- if (index <= 0) return@launch- val current = assignments[index]- val previous = assignments[index - 1]- epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, previous.priority)- epgSourceRepository.updateAssignmentPriority(providerId, previous.epgSourceId, current.priority)- refreshProviderEpgSummary(providerId)- }+ epgActions.moveEpgSourceAssignmentUp(viewModelScope, providerId, epgSourceId)}fun moveEpgSourceAssignmentDown(providerId: Long, epgSourceId: Long) {- viewModelScope.launch {- val assignments = _uiState.value.epgSourceAssignments[providerId].orEmpty()- .sortedBy { it.priority }- val index = assignments.indexOfFirst { it.epgSourceId == epgSourceId }- if (index == -1 || index >= assignments.lastIndex) return@launch- val current = assignments[index]- val next = assignments[index + 1]- epgSourceRepository.updateAssignmentPriority(providerId, current.epgSourceId, next.priority)- epgSourceRepository.updateAssignmentPriority(providerId, next.epgSourceId, current.priority)- refreshProviderEpgSummary(providerId)- }- }-- private suspend fun refreshProviderEpgSummary(providerId: Long) {- val summary = epgSourceRepository.getResolutionSummary(providerId)- _uiState.update {- it.copy(epgResolutionSummaries = it.epgResolutionSummaries + (providerId to summary))- }- }-- private fun loadedProvidersForSource(sourceId: Long): List<Long> =- _uiState.value.epgSourceAssignments- .filterValues { assignments -> assignments.any { it.epgSourceId == sourceId } }- .keys- .toList()-- private suspend fun refreshLoadedResolutionSummaries(providerIds: Iterable<Long>) {- providerIds- .asSequence()- .distinct()- .forEach { providerId ->- refreshProviderEpgSummary(providerId)- }- }-- private fun buildCapabilitySummary(provider: Provider): String {- return when (provider.type) {- ProviderType.XTREAM_CODES -> {- if (provider.epgUrl.isNotBlank()) {- appContext.getString(R.string.settings_capability_xtream_with_epg)- } else {- appContext.getString(R.string.settings_capability_xtream_without_epg)- }- }- ProviderType.M3U -> {- if (provider.epgUrl.isNotBlank()) {- appContext.getString(R.string.settings_capability_m3u_with_epg)- } else {- appContext.getString(R.string.settings_capability_m3u_without_epg)- }- }- }+ epgActions.moveEpgSourceAssignmentDown(viewModelScope, providerId, epgSourceId)}}--data class ProviderDiagnosticsUiModel(- val lastSyncStatus: String = "NONE",- val lastLiveSync: Long = 0L,- val lastMovieSync: Long = 0L,- val lastMovieAttempt: Long = 0L,- val lastMovieSuccess: Long = 0L,- val lastMoviePartial: Long = 0L,- val lastSeriesSync: Long = 0L,- val lastEpgSync: Long = 0L,- val liveCount: Int = 0,- val movieCount: Int = 0,- val seriesCount: Int = 0,- val epgCount: Int = 0,- val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,- val movieWarningsCount: Int = 0,- val movieCatalogStale: Boolean = false,- val capabilitySummary: String = "",- val sourceLabel: String = "",- val expirySummary: String = "",- val connectionSummary: String = "",- val archiveSummary: String = ""-)--data class SettingsUiState(- val providers: List<Provider> = emptyList(),- val combinedProfiles: List<CombinedM3uProfile> = emptyList(),- val availableM3uProviders: List<Provider> = emptyList(),- val activeProviderId: Long? = null,- val activeLiveSource: ActiveLiveSource? = null,- val isSyncing: Boolean = false,- val userMessage: String? = null,- val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),- val diagnosticsByProvider: Map<Long, ProviderDiagnosticsUiModel> = emptyMap(),- val parentalControlLevel: Int = 0,- val hasParentalPin: Boolean = false,- val appLanguage: String = "system",- val preferredAudioLanguage: String = "auto",- val playerMediaSessionEnabled: Boolean = true,- val playerDecoderMode: DecoderMode = DecoderMode.AUTO,- val playerPlaybackSpeed: Float = 1f,- val playerControlsTimeoutSeconds: Int = 5,- val playerLiveOverlayTimeoutSeconds: Int = 4,- val playerNoticeTimeoutSeconds: Int = 6,- val playerDiagnosticsTimeoutSeconds: Int = 15,- val subtitleTextScale: Float = 1f,- val subtitleTextColor: Int = 0xFFFFFFFF.toInt(),- val subtitleBackgroundColor: Int = 0x80000000.toInt(),- val wifiMaxVideoHeight: Int? = null,- val ethernetMaxVideoHeight: Int? = null,- val lastSpeedTest: InternetSpeedTestUiModel? = null,- val isRunningInternetSpeedTest: Boolean = false,- val backupPreview: BackupPreview? = null,- val pendingBackupUri: String? = null,- val backupImportPlan: BackupImportPlan = BackupImportPlan(),- val recordingItems: List<RecordingItem> = emptyList(),- val recordingStorageState: RecordingStorageState = RecordingStorageState(),- val isIncognitoMode: Boolean = false,- val useXtreamTextClassification: Boolean = true,- val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.PRO,- val showLiveSourceSwitcher: Boolean = false,- val liveTvCategoryFilters: List<String> = emptyList(),- val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,- val liveChannelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP,- val vodViewMode: VodViewMode = VodViewMode.MODERN,- val preventStandbyDuringPlayback: Boolean = true,- val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),- val hiddenCategories: List<Category> = emptyList(),- val epgSources: List<com.streamvault.domain.model.EpgSource> = emptyList(),- val epgSourceAssignments: Map<Long, List<com.streamvault.domain.model.ProviderEpgSourceAssignment>> = emptyMap(),- val epgResolutionSummaries: Map<Long, EpgResolutionSummary> = emptyMap(),- val autoCheckAppUpdates: Boolean = true,- val isCheckingForUpdates: Boolean = false,- val appUpdate: AppUpdateUiModel = AppUpdateUiModel()-)--private fun AppUpdateUiModel.toReleaseInfoOrNull(): GitHubReleaseInfo? {- val versionName = latestVersionName ?: return null- val releaseUrl = releaseUrl ?: return null- return GitHubReleaseInfo(- versionName = versionName,- versionCode = latestVersionCode,- releaseUrl = releaseUrl,- downloadUrl = downloadUrl,- releaseNotes = releaseNotes,- publishedAt = publishedAt- )-}--private fun AppUpdateUiModel.withDownloadState(downloadState: AppUpdateDownloadState): AppUpdateUiModel {- return copy(- downloadStatus = downloadState.status,- downloadedVersionName = downloadState.versionName- )-}--private fun AppUpdateUiModel.toDownloadState(): AppUpdateDownloadState {- return AppUpdateDownloadState(- status = downloadStatus,- versionName = downloadedVersionName- )-}--private fun SettingsPreferenceSnapshot.toCachedAppUpdateUiModel(): AppUpdateUiModel {- val versionName = cachedAppUpdateVersionName- return AppUpdateUiModel(- latestVersionName = versionName,- latestVersionCode = cachedAppUpdateVersionCode,- releaseUrl = cachedAppUpdateReleaseUrl,- downloadUrl = cachedAppUpdateDownloadUrl,- releaseNotes = cachedAppUpdateReleaseNotes,- publishedAt = cachedAppUpdatePublishedAt,- isUpdateAvailable = versionName?.let {- if (cachedAppUpdateVersionCode != null && cachedAppUpdateVersionCode > BuildConfig.VERSION_CODE) {- true- } else {- compareVersionNamesStatic(it, BuildConfig.VERSION_NAME) > 0- }- } ?: false,- lastCheckedAt = lastAppUpdateCheckAt- )-}--private fun compareVersionNamesStatic(left: String, right: String): Int {- val leftParts = left.removePrefix("v").split('.')- val rightParts = right.removePrefix("v").split('.')- val length = max(leftParts.size, rightParts.size)- for (index in 0 until length) {- val leftValue = leftParts.getOrNull(index)?.toIntOrNull() ?: 0- val rightValue = rightParts.getOrNull(index)?.toIntOrNull() ?: 0- if (leftValue != rightValue) {- return leftValue.compareTo(rightValue)- }- }- return 0-}--private fun ProviderSyncSelection.label(application: Application): String = when (this) {- ProviderSyncSelection.ALL -> application.getString(R.string.settings_sync_option_all)- ProviderSyncSelection.FAST -> application.getString(R.string.settings_sync_option_fast)- ProviderSyncSelection.TV -> application.getString(R.string.settings_sync_option_tv)- ProviderSyncSelection.MOVIES -> application.getString(R.string.settings_sync_option_movies)- ProviderSyncSelection.SERIES -> application.getString(R.string.settings_sync_option_series)- ProviderSyncSelection.EPG -> application.getString(R.string.settings_sync_option_epg)-}--data class InternetSpeedTestUiModel(- val megabitsPerSecond: Double,- val measuredAtMs: Long,- val transportLabel: String,- val recommendedMaxVideoHeight: Int?,- val isEstimated: Boolean-)--private data class CategoryManagementSnapshot(- val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),- val hiddenCategories: List<Category> = emptyList()-)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.ktnew file mode 100644index 00000000..64f533a2--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModelModels.kt@@ -0,0 +1,256 @@+package com.streamvault.app.ui.screens.settings++import android.app.Application+import com.streamvault.app.BuildConfig+import com.streamvault.app.R+import com.streamvault.app.ui.model.LiveTvChannelMode+import com.streamvault.app.ui.model.LiveTvQuickFilterVisibilityMode+import com.streamvault.app.ui.model.VodViewMode+import com.streamvault.app.update.AppUpdateDownloadState+import com.streamvault.app.update.AppUpdateDownloadStatus+import com.streamvault.app.update.GitHubReleaseInfo+import com.streamvault.domain.manager.BackupImportPlan+import com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.CategorySortMode+import com.streamvault.domain.model.ChannelNumberingMode+import com.streamvault.domain.model.CombinedM3uProfile+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.DecoderMode+import com.streamvault.domain.model.EpgResolutionSummary+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingStorageState+import com.streamvault.domain.model.VodSyncMode+import kotlin.math.max++enum class ProviderWarningAction {+ EPG,+ MOVIES,+ SERIES+}++enum class ProviderSyncSelection {+ ALL,+ FAST,+ TV,+ MOVIES,+ SERIES,+ EPG+}++internal data class SettingsPreferenceSnapshot(+ val providers: List<Provider>,+ val activeProviderId: Long?,+ val parentalControlLevel: Int,+ val hasParentalPin: Boolean,+ val appLanguage: String,+ val preferredAudioLanguage: String,+ val playerMediaSessionEnabled: Boolean,+ val playerDecoderMode: DecoderMode,+ val playerPlaybackSpeed: Float,+ val playerControlsTimeoutSeconds: Int,+ val playerLiveOverlayTimeoutSeconds: Int,+ val playerNoticeTimeoutSeconds: Int,+ val playerDiagnosticsTimeoutSeconds: Int,+ val subtitleTextScale: Float,+ val subtitleTextColor: Int,+ val subtitleBackgroundColor: Int,+ val wifiMaxVideoHeight: Int?,+ val ethernetMaxVideoHeight: Int?,+ val lastSpeedTestMegabits: Double?,+ val lastSpeedTestTimestamp: Long?,+ val lastSpeedTestTransport: String?,+ val lastSpeedTestRecommendedHeight: Int?,+ val lastSpeedTestEstimated: Boolean,+ val isIncognitoMode: Boolean,+ val useXtreamTextClassification: Boolean,+ val liveTvChannelMode: LiveTvChannelMode,+ val showLiveSourceSwitcher: Boolean,+ val liveTvCategoryFilters: List<String>,+ val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode,+ val liveChannelNumberingMode: ChannelNumberingMode,+ val vodViewMode: VodViewMode,+ val preventStandbyDuringPlayback: Boolean,+ val autoCheckAppUpdates: Boolean,+ val lastAppUpdateCheckAt: Long?,+ val cachedAppUpdateVersionName: String?,+ val cachedAppUpdateVersionCode: Int?,+ val cachedAppUpdateReleaseUrl: String?,+ val cachedAppUpdateDownloadUrl: String?,+ val cachedAppUpdateReleaseNotes: String,+ val cachedAppUpdatePublishedAt: String?+)++data class AppUpdateUiModel(+ val latestVersionName: String? = null,+ val latestVersionCode: Int? = null,+ val releaseUrl: String? = null,+ val downloadUrl: String? = null,+ val releaseNotes: String = "",+ val publishedAt: String? = null,+ val isUpdateAvailable: Boolean = false,+ val lastCheckedAt: Long? = null,+ val errorMessage: String? = null,+ val downloadStatus: AppUpdateDownloadStatus = AppUpdateDownloadStatus.Idle,+ val downloadedVersionName: String? = null+)++data class ProviderDiagnosticsUiModel(+ val lastSyncStatus: String = "NONE",+ val lastLiveSync: Long = 0L,+ val lastMovieSync: Long = 0L,+ val lastMovieAttempt: Long = 0L,+ val lastMovieSuccess: Long = 0L,+ val lastMoviePartial: Long = 0L,+ val lastSeriesSync: Long = 0L,+ val lastEpgSync: Long = 0L,+ val liveCount: Int = 0,+ val movieCount: Int = 0,+ val seriesCount: Int = 0,+ val epgCount: Int = 0,+ val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,+ val movieWarningsCount: Int = 0,+ val movieCatalogStale: Boolean = false,+ val capabilitySummary: String = "",+ val sourceLabel: String = "",+ val expirySummary: String = "",+ val connectionSummary: String = "",+ val archiveSummary: String = ""+)++data class SettingsUiState(+ val providers: List<Provider> = emptyList(),+ val combinedProfiles: List<CombinedM3uProfile> = emptyList(),+ val availableM3uProviders: List<Provider> = emptyList(),+ val activeProviderId: Long? = null,+ val activeLiveSource: ActiveLiveSource? = null,+ val isSyncing: Boolean = false,+ val userMessage: String? = null,+ val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),+ val diagnosticsByProvider: Map<Long, ProviderDiagnosticsUiModel> = emptyMap(),+ val parentalControlLevel: Int = 0,+ val hasParentalPin: Boolean = false,+ val appLanguage: String = "system",+ val preferredAudioLanguage: String = "auto",+ val playerMediaSessionEnabled: Boolean = true,+ val playerDecoderMode: DecoderMode = DecoderMode.AUTO,+ val playerPlaybackSpeed: Float = 1f,+ val playerControlsTimeoutSeconds: Int = 5,+ val playerLiveOverlayTimeoutSeconds: Int = 4,+ val playerNoticeTimeoutSeconds: Int = 6,+ val playerDiagnosticsTimeoutSeconds: Int = 15,+ val subtitleTextScale: Float = 1f,+ val subtitleTextColor: Int = 0xFFFFFFFF.toInt(),+ val subtitleBackgroundColor: Int = 0x80000000.toInt(),+ val wifiMaxVideoHeight: Int? = null,+ val ethernetMaxVideoHeight: Int? = null,+ val lastSpeedTest: InternetSpeedTestUiModel? = null,+ val isRunningInternetSpeedTest: Boolean = false,+ val backupPreview: BackupPreview? = null,+ val pendingBackupUri: String? = null,+ val backupImportPlan: BackupImportPlan = BackupImportPlan(),+ val recordingItems: List<RecordingItem> = emptyList(),+ val recordingStorageState: RecordingStorageState = RecordingStorageState(),+ val isIncognitoMode: Boolean = false,+ val useXtreamTextClassification: Boolean = true,+ val liveTvChannelMode: LiveTvChannelMode = LiveTvChannelMode.PRO,+ val showLiveSourceSwitcher: Boolean = false,+ val liveTvCategoryFilters: List<String> = emptyList(),+ val liveTvQuickFilterVisibilityMode: LiveTvQuickFilterVisibilityMode = LiveTvQuickFilterVisibilityMode.ALWAYS_VISIBLE,+ val liveChannelNumberingMode: ChannelNumberingMode = ChannelNumberingMode.GROUP,+ val vodViewMode: VodViewMode = VodViewMode.MODERN,+ val preventStandbyDuringPlayback: Boolean = true,+ val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),+ val hiddenCategories: List<Category> = emptyList(),+ val epgSources: List<com.streamvault.domain.model.EpgSource> = emptyList(),+ val epgSourceAssignments: Map<Long, List<com.streamvault.domain.model.ProviderEpgSourceAssignment>> = emptyMap(),+ val epgResolutionSummaries: Map<Long, EpgResolutionSummary> = emptyMap(),+ val autoCheckAppUpdates: Boolean = true,+ val isCheckingForUpdates: Boolean = false,+ val appUpdate: AppUpdateUiModel = AppUpdateUiModel()+)++internal fun AppUpdateUiModel.toReleaseInfoOrNull(): GitHubReleaseInfo? {+ val versionName = latestVersionName ?: return null+ val releaseUrl = releaseUrl ?: return null+ return GitHubReleaseInfo(+ versionName = versionName,+ versionCode = latestVersionCode,+ releaseUrl = releaseUrl,+ downloadUrl = downloadUrl,+ releaseNotes = releaseNotes,+ publishedAt = publishedAt+ )+}++internal fun AppUpdateUiModel.withDownloadState(downloadState: AppUpdateDownloadState): AppUpdateUiModel {+ return copy(+ downloadStatus = downloadState.status,+ downloadedVersionName = downloadState.versionName+ )+}++internal fun AppUpdateUiModel.toDownloadState(): AppUpdateDownloadState {+ return AppUpdateDownloadState(+ status = downloadStatus,+ versionName = downloadedVersionName+ )+}++internal fun SettingsPreferenceSnapshot.toCachedAppUpdateUiModel(): AppUpdateUiModel {+ val versionName = cachedAppUpdateVersionName+ return AppUpdateUiModel(+ latestVersionName = versionName,+ latestVersionCode = cachedAppUpdateVersionCode,+ releaseUrl = cachedAppUpdateReleaseUrl,+ downloadUrl = cachedAppUpdateDownloadUrl,+ releaseNotes = cachedAppUpdateReleaseNotes,+ publishedAt = cachedAppUpdatePublishedAt,+ isUpdateAvailable = versionName?.let {+ if (cachedAppUpdateVersionCode != null && cachedAppUpdateVersionCode > BuildConfig.VERSION_CODE) {+ true+ } else {+ compareVersionNamesStatic(it, BuildConfig.VERSION_NAME) > 0+ }+ } ?: false,+ lastCheckedAt = lastAppUpdateCheckAt+ )+}++internal fun compareVersionNamesStatic(left: String, right: String): Int {+ val leftParts = left.removePrefix("v").split('.')+ val rightParts = right.removePrefix("v").split('.')+ val length = max(leftParts.size, rightParts.size)+ for (index in 0 until length) {+ val leftValue = leftParts.getOrNull(index)?.toIntOrNull() ?: 0+ val rightValue = rightParts.getOrNull(index)?.toIntOrNull() ?: 0+ if (leftValue != rightValue) {+ return leftValue.compareTo(rightValue)+ }+ }+ return 0+}++internal fun ProviderSyncSelection.label(application: Application): String = when (this) {+ ProviderSyncSelection.ALL -> application.getString(R.string.settings_sync_option_all)+ ProviderSyncSelection.FAST -> application.getString(R.string.settings_sync_option_fast)+ ProviderSyncSelection.TV -> application.getString(R.string.settings_sync_option_tv)+ ProviderSyncSelection.MOVIES -> application.getString(R.string.settings_sync_option_movies)+ ProviderSyncSelection.SERIES -> application.getString(R.string.settings_sync_option_series)+ ProviderSyncSelection.EPG -> application.getString(R.string.settings_sync_option_epg)+}++data class InternetSpeedTestUiModel(+ val megabitsPerSecond: Double,+ val measuredAtMs: Long,+ val transportLabel: String,+ val recommendedMaxVideoHeight: Int?,+ val isEstimated: Boolean+)++internal data class CategoryManagementSnapshot(+ val categorySortModes: Map<ContentType, CategorySortMode> = emptyMap(),+ val hiddenCategories: List<Category> = emptyList()+)diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 9c8a778d..19d840fa 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -52,15 +52,12 @@ import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext-import kotlinx.coroutines.TimeoutCancellationException-import kotlinx.coroutines.withTimeoutimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.serialization.json.Json@@ -76,7 +73,6 @@ import java.util.concurrent.ConcurrentHashMapimport java.util.zip.GZIPInputStreamimport javax.inject.Injectimport javax.inject.Singleton-import kotlin.random.Randomimport kotlin.system.measureTimeMillisprivate const val TAG = "SyncManager"@@ -124,177 +120,6 @@ class SyncManager @Inject constructor(private val transactionRunner: DatabaseTransactionRunner,private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository) {- private data class SyncOutcome(- val partial: Boolean = false,- val warnings: List<String> = emptyList()- )-- private sealed interface CatalogStrategyResult<out T> {- val strategyName: String-- data class Success<T>(- override val strategyName: String,- val items: List<T>,- val warnings: List<String> = emptyList()- ) : CatalogStrategyResult<T>-- data class Partial<T>(- override val strategyName: String,- val items: List<T>,- val warnings: List<String>- ) : CatalogStrategyResult<T>-- data class Failure(- override val strategyName: String,- val error: Throwable,- val warnings: List<String> = emptyList()- ) : CatalogStrategyResult<Nothing>-- data class EmptyValid(- override val strategyName: String,- val warnings: List<String> = emptyList()- ) : CatalogStrategyResult<Nothing>- }-- private data class XtreamStrategyFeedback(- val preferredSegmentedFirst: Boolean = false,- val attemptedFullCatalog: Boolean = false,- val fullCatalogUnsafe: Boolean = false,- val segmentedStressDetected: Boolean = false- )-- private data class MovieCatalogSyncResult(- val catalogResult: CatalogStrategyResult<Movie>,- val categories: List<CategoryEntity>?,- val syncMode: VodSyncMode,- val warnings: List<String> = emptyList(),- val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),- val stagedSessionId: Long? = null,- val stagedAcceptedCount: Int = 0- )-- private data class CatalogSyncPayload<T>(- val catalogResult: CatalogStrategyResult<T>,- val categories: List<CategoryEntity>?,- val warnings: List<String> = emptyList(),- val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),- val stagedSessionId: Long? = null,- val stagedAcceptedCount: Int = 0- )-- private data class LiveCatalogSnapshot(- val categories: List<CategoryEntity>?,- val channels: List<ChannelEntity>- )-- private data class SequentialProviderAdaptation(- val rememberSequential: Boolean,- val healthyStreak: Int- )-- private sealed interface Attempt<out T> {- data class Success<T>(val value: T) : Attempt<T>- data class Failure(val error: Exception) : Attempt<Nothing>- }-- private sealed interface CategoryFetchOutcome<out T> {- data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>- data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>- data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>- }-- private data class TimedCategoryOutcome<T>(- val category: XtreamCategory,- val outcome: CategoryFetchOutcome<T>,- val elapsedMs: Long- )-- private sealed interface PageFetchOutcome<out T> {- data class Success<T>(val items: List<T>, val rawCount: Int) : PageFetchOutcome<T>- data class Empty(val page: Int) : PageFetchOutcome<Nothing>- data class Failure(val page: Int, val error: Throwable) : PageFetchOutcome<Nothing>- }-- private data class TimedPageOutcome<T>(- val page: Int,- val outcome: PageFetchOutcome<T>,- val elapsedMs: Long- )-- private data class CategoryExecutionPlan<T>(- val outcomes: List<TimedCategoryOutcome<T>>,- val warnings: List<String> = emptyList()- )-- private data class PageExecutionPlan<T>(- val outcomes: List<TimedPageOutcome<T>>,- val warnings: List<String> = emptyList(),- val stoppedEarly: Boolean = false- )-- private data class M3uImportStats(- val header: M3uParser.M3uHeader,- val liveCount: Int,- val movieCount: Int,- val warnings: List<String> = emptyList()- )-- private data class StreamedPlaylist(- val inputStream: InputStream,- val contentEncoding: String? = null,- val sourceName: String? = null- )-- private class StableLongHasher {- private val digest = MessageDigest.getInstance("SHA-256")-- fun hash(input: String): Long {- val bytes = digest.digest(input.toByteArray(Charsets.UTF_8))- var result = 0L- for (i in 0 until 8) {- result = (result shl 8) or (bytes[i].toLong() and 0xFF)- }- return result and Long.MAX_VALUE- }- }-- private class CategoryAccumulator(- private val providerId: Long,- private val type: ContentType,- private val hasher: StableLongHasher- ) {- private val categoryIds = LinkedHashMap<String, Long>()- val count: Int- get() = categoryIds.size-- fun idFor(name: String): Long {- return categoryIds.getOrPut(name) { stableId(providerId, type, name, hasher) }- }-- fun entities(): List<CategoryEntity> {- return categoryIds.map { (name, id) ->- CategoryEntity(- categoryId = id,- name = name,- parentId = 0,- type = type,- providerId = providerId,- isAdult = AdultContentClassifier.isAdultCategoryName(name)- )- }- }-- /** Generates a stable, collision-resistant ID from the provider+type+name triple. */- private fun stableId(- providerId: Long,- type: ContentType,- name: String,- hasher: StableLongHasher- ): Long {- return hasher.hash("$providerId/${type.name}/$name").coerceAtLeast(1L)- }- }-private val syncStateTracker = SyncStateTracker()private val syncErrorSanitizer = SyncErrorSanitizer()private val xtreamAdaptiveSyncPolicy = XtreamAdaptiveSyncPolicy()@@ -303,6 +128,22 @@ class SyncManager @Inject constructor(catalogSyncDao = catalogSyncDao,transactionRunner = transactionRunner)+ private val m3uImporter = SyncManagerM3uImporter(+ m3uParser = m3uParser,+ okHttpClient = okHttpClient,+ syncCatalogStore = syncCatalogStore,+ retryTransient = { block -> retryTransient(block = block) },+ progress = ::progress+ )+ private val xtreamSupport = SyncManagerXtreamSupport(+ adaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,+ shouldRememberSequentialPreference = ::shouldRememberSequentialPreference,+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ progress = ::progress,+ movieRequestTimeoutMillis = XTREAM_MOVIE_REQUEST_TIMEOUT_MILLIS,+ seriesRequestTimeoutMillis = XTREAM_SERIES_REQUEST_TIMEOUT_MILLIS,+ recoveryAbortWarningSuffix = XTREAM_RECOVERY_ABORT_WARNING_SUFFIX+ )val syncState: StateFlow<SyncState> = syncStateTracker.aggregateStateval syncStatesByProvider: StateFlow<Map<Long, SyncState>> = syncStateTracker.statesByProviderprivate val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()@@ -315,6 +156,82 @@ class SyncManager @Inject constructor()}private val xtreamCatalogApiService: XtreamApiService by lazy { xtreamCatalogHttpService }+ private val xtreamFetcher: SyncManagerXtreamFetcher by lazy {+ SyncManagerXtreamFetcher(+ xtreamCatalogApiService = xtreamCatalogApiService,+ xtreamSupport = xtreamSupport,+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ pageSize = XTREAM_CATALOG_PAGE_SIZE+ )+ }+ private val catalogStrategySupport = SyncManagerCatalogStrategySupport(+ shouldRememberSequentialPreference = ::shouldRememberSequentialPreference,+ avoidFullCatalogCooldownMillis = XTREAM_AVOID_FULL_CATALOG_COOLDOWN_MILLIS+ )+ private val catalogStager = SyncManagerCatalogStager(+ syncCatalogStore = syncCatalogStore,+ fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE+ )+ private val xtreamLiveStrategy: SyncManagerXtreamLiveStrategy by lazy {+ SyncManagerXtreamLiveStrategy(+ xtreamCatalogApiService = xtreamCatalogApiService,+ xtreamAdaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,+ xtreamSupport = xtreamSupport,+ xtreamFetcher = xtreamFetcher,+ catalogStrategySupport = catalogStrategySupport,+ progress = ::progress,+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ fullCatalogFallbackWarning = ::fullCatalogFallbackWarning,+ categoryFailureWarning = ::categoryFailureWarning,+ liveCategorySequentialModeWarning = LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING+ )+ }+ private val xtreamMovieStrategy: SyncManagerXtreamMovieStrategy by lazy {+ SyncManagerXtreamMovieStrategy(+ xtreamCatalogApiService = xtreamCatalogApiService,+ xtreamCatalogHttpService = xtreamCatalogHttpService,+ xtreamAdaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,+ xtreamSupport = xtreamSupport,+ xtreamFetcher = xtreamFetcher,+ catalogStrategySupport = catalogStrategySupport,+ syncCatalogStore = syncCatalogStore,+ progress = ::progress,+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ fullCatalogFallbackWarning = ::fullCatalogFallbackWarning,+ categoryFailureWarning = ::categoryFailureWarning,+ pagingFailureWarning = ::pagingFailureWarning,+ stageMovieItems = catalogStager::stageMovieItems,+ stageMovieSequence = catalogStager::stageMovieSequence,+ movieCategorySequentialModeWarning = MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING,+ moviePagedSequentialModeWarning = MOVIE_PAGED_SEQUENTIAL_MODE_WARNING,+ fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE,+ maxCatalogPages = XTREAM_CATALOG_MAX_PAGES,+ pageSize = XTREAM_CATALOG_PAGE_SIZE+ )+ }+ private val xtreamSeriesStrategy: SyncManagerXtreamSeriesStrategy by lazy {+ SyncManagerXtreamSeriesStrategy(+ xtreamCatalogApiService = xtreamCatalogApiService,+ xtreamCatalogHttpService = xtreamCatalogHttpService,+ xtreamAdaptiveSyncPolicy = xtreamAdaptiveSyncPolicy,+ xtreamSupport = xtreamSupport,+ xtreamFetcher = xtreamFetcher,+ catalogStrategySupport = catalogStrategySupport,+ syncCatalogStore = syncCatalogStore,+ progress = ::progress,+ sanitizeThrowableMessage = ::sanitizeThrowableMessage,+ fullCatalogFallbackWarning = ::fullCatalogFallbackWarning,+ categoryFailureWarning = ::categoryFailureWarning,+ pagingFailureWarning = ::pagingFailureWarning,+ stageSeriesItems = catalogStager::stageSeriesItems,+ stageSeriesSequence = catalogStager::stageSeriesSequence,+ categorySequentialModeWarning = SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING,+ pagedSequentialModeWarning = SERIES_PAGED_SEQUENTIAL_MODE_WARNING,+ fallbackStageBatchSize = XTREAM_FALLBACK_STAGE_BATCH_SIZE,+ maxCatalogPages = XTREAM_CATALOG_MAX_PAGES,+ pageSize = XTREAM_CATALOG_PAGE_SIZE+ )+ }fun syncStateForProvider(providerId: Long): Flow<SyncState> =syncStatesByProvider.map { states -> states[providerId] ?: SyncState.Idle }@@ -437,58 +354,6 @@ class SyncManager @Inject constructor(}}- private class FallbackCategoryCollector(- private val providerId: Long,- private val type: ContentType- ) {- private val categories = LinkedHashMap<Long, CategoryEntity>()-- fun record(categoryId: Long?, categoryName: String?, isAdult: Boolean) {- val resolvedCategoryId = categoryId ?: return- val resolvedCategoryName = categoryName?.trim().takeUnless { it.isNullOrEmpty() }- ?: "Category $resolvedCategoryId"- val candidate = CategoryEntity(- categoryId = resolvedCategoryId,- name = resolvedCategoryName,- parentId = 0,- type = type,- providerId = providerId,- isAdult = isAdult || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)- )- val existing = categories[resolvedCategoryId]- categories[resolvedCategoryId] = if (existing == null) {- candidate- } else {- existing.copy(- name = preferredCategoryName(existing.name, candidate.name, resolvedCategoryId),- isAdult = existing.isAdult || candidate.isAdult,- isUserProtected = existing.isUserProtected || candidate.isUserProtected- )- }- }-- fun entities(): List<CategoryEntity> = categories.values.toList()-- private fun preferredCategoryName(- currentName: String,- candidateName: String,- categoryId: Long- ): String {- val placeholderName = "Category $categoryId"- return when {- currentName == placeholderName && candidateName != placeholderName -> candidateName- currentName != placeholderName -> currentName- else -> candidateName- }- }- }-- private data class StagedCatalogSnapshot(- val sessionId: Long?,- val acceptedCount: Int,- val fallbackCategories: List<CategoryEntity>?- )-fun resetState(providerId: Long? = null) {syncStateTracker.reset(providerId)}@@ -907,7 +772,7 @@ class SyncManager @Inject constructor(val now = System.currentTimeMillis()if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {- val stats = withContext(Dispatchers.IO) { importM3uPlaylist(provider, onProgress) }+ val stats = withContext(Dispatchers.IO) { m3uImporter.importPlaylist(provider, onProgress) }if (stats.liveCount == 0 && stats.movieCount == 0) {throw IllegalStateException("Playlist is empty or contains no supported entries")}@@ -1179,7 +1044,7 @@ class SyncManager @Inject constructor(ProviderType.M3U -> {progress(provider.id, onProgress, "Retrying Live TV...")val stats = withContext(Dispatchers.IO) {- importM3uPlaylist(provider, onProgress, includeLive = true, includeMovies = false)+ m3uImporter.importPlaylist(provider, onProgress, includeLive = true, includeMovies = false)}if (stats.liveCount == 0) {throw IllegalStateException("Playlist contains no live TV entries")@@ -1328,7 +1193,7 @@ class SyncManager @Inject constructor(ProviderType.M3U -> {progress(provider.id, onProgress, "Retrying Movies...")val stats = withContext(Dispatchers.IO) {- importM3uPlaylist(provider, onProgress, includeLive = false, includeMovies = true)+ m3uImporter.importPlaylist(provider, onProgress, includeLive = false, includeMovies = true)}if (stats.movieCount == 0) {throw IllegalStateException("Playlist contains no movie entries")@@ -1462,386 +1327,13 @@ class SyncManager @Inject constructor(api: XtreamProvider,existingMetadata: SyncMetadata,onProgress: ((String) -> Unit)?- ): MovieCatalogSyncResult {- Log.i(- TAG,- "Xtream movies strategy start for provider ${provider.id}. previousMode=${existingMetadata.movieSyncMode} rememberSequential=${existingMetadata.movieParallelFailuresRemembered}"- )- val rawVodCategories = fetchXtreamVodCategories(provider)- val resolvedCategories = rawVodCategories- ?.let { categories -> api.mapCategories(ContentType.MOVIE, categories) }- ?.map { category -> category.toEntity(provider.id) }- ?.takeIf { it.isNotEmpty() }-- var fullPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("full"),- categories = null- )- var pagedPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("paged"),- categories = null- )- var categoryPayload = CatalogSyncPayload<Movie>(- catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),- categories = null- )-- // Fast sync: skip all downloads, expose categories only and hydrate on demand.- if (provider.xtreamFastSyncEnabled) {- return if (!resolvedCategories.isNullOrEmpty()) {- Log.i(TAG, "Xtream movies fast sync: returning LAZY_BY_CATEGORY for provider ${provider.id} with ${resolvedCategories.size} categories.")- MovieCatalogSyncResult(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "fast_sync",- error = IllegalStateException("Fast sync enabled; movies will hydrate on demand"),- warnings = emptyList()- ),- categories = resolvedCategories,- syncMode = VodSyncMode.LAZY_BY_CATEGORY,- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)- )- } else {- Log.w(TAG, "Xtream movies fast sync: no categories available for provider ${provider.id}, falling through to standard strategies.")- // No categories — fall through to normal strategies below- MovieCatalogSyncResult(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "fast_sync_no_categories",- error = IllegalStateException("Fast sync enabled but no categories available"),- warnings = listOf("Fast sync enabled but no categories returned from server.")- ),- categories = null,- syncMode = VodSyncMode.UNKNOWN,- warnings = listOf("Fast sync enabled but no categories returned from server."),- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)- )- }- }-- progress(provider.id, onProgress, "Checking Movies full catalog...")- fullPayload = loadXtreamMoviesFull(provider, api)- when (val fullResult = fullPayload.catalogResult) {- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(- catalogResult = fullResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),- syncMode = VodSyncMode.FULL,- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = false,- attemptedFullCatalog = true,- fullCatalogUnsafe = false- ),- stagedSessionId = fullPayload.stagedSessionId,- stagedAcceptedCount = fullPayload.stagedAcceptedCount- ).also {- Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items.")- }- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(- catalogResult = fullResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),- syncMode = VodSyncMode.FULL,- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = false,- attemptedFullCatalog = true,- fullCatalogUnsafe = false- ),- stagedSessionId = fullPayload.stagedSessionId,- stagedAcceptedCount = fullPayload.stagedAcceptedCount- ).also {- Log.w(TAG, "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items.")- }- else -> Unit- }-- if (!resolvedCategories.isNullOrEmpty()) {- progress(provider.id, onProgress, "Preparing Movies category sync...")- categoryPayload = loadXtreamMoviesByCategory(- provider = provider,- api = api,- rawCategories = rawVodCategories.orEmpty(),- onProgress = onProgress,- preferSequential = existingMetadata.movieParallelFailuresRemembered- )- }- when (val categoryResult = categoryPayload.catalogResult) {- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(- catalogResult = categoryResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),- syncMode = VodSyncMode.CATEGORY_BULK,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- result = categoryResult,- sequentialWarnings = setOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, MOVIE_PAGED_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = categoryPayload.stagedSessionId,- stagedAcceptedCount = categoryPayload.stagedAcceptedCount- ).also {- Log.i(TAG, "Xtream movies strategy selected CATEGORY_BULK for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items.")- }- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(- catalogResult = categoryResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),- syncMode = VodSyncMode.CATEGORY_BULK,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- result = categoryResult,- sequentialWarnings = setOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, MOVIE_PAGED_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = categoryPayload.stagedSessionId,- stagedAcceptedCount = categoryPayload.stagedAcceptedCount- ).also {- Log.w(TAG, "Xtream movies strategy selected CATEGORY_BULK(partial) for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items.")- }- else -> Unit- }-- if (resolvedCategories.isNullOrEmpty()) {- progress(provider.id, onProgress, "Checking Movies paged catalog...")- pagedPayload = loadXtreamMoviesByPage(provider, api, onProgress)- when (val pagedResult = pagedPayload.catalogResult) {- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(- catalogResult = pagedResult,- categories = pagedPayload.categories,- syncMode = VodSyncMode.PAGED,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- result = pagedResult,- sequentialWarnings = setOf(MOVIE_PAGED_SEQUENTIAL_MODE_WARNING, MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = pagedPayload.stagedSessionId,- stagedAcceptedCount = pagedPayload.stagedAcceptedCount- ).also {- Log.i(TAG, "Xtream movies strategy selected PAGED for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items.")- }- is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(- catalogResult = pagedResult,- categories = pagedPayload.categories,- syncMode = VodSyncMode.PAGED,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- result = pagedResult,- sequentialWarnings = setOf(MOVIE_PAGED_SEQUENTIAL_MODE_WARNING, MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = pagedPayload.stagedSessionId,- stagedAcceptedCount = pagedPayload.stagedAcceptedCount- ).also {- Log.w(TAG, "Xtream movies strategy selected PAGED(partial) for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items.")- }- else -> Unit- }- }-- progress(provider.id, onProgress, "Checking Movies full catalog...")- fullPayload = loadXtreamMoviesFull(provider, api)- when (val fullResult = fullPayload.catalogResult) {- is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(- catalogResult = fullResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),- syncMode = VodSyncMode.FULL,- warnings = strategyWarnings(categoryPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- fullCatalogUnsafe = false- ),- stagedSessionId = fullPayload.stagedSessionId,- stagedAcceptedCount = fullPayload.stagedAcceptedCount- ).also {- val itemCount = fullPayload.stagedAcceptedCount.takeIf { it > 0 } ?: fullResult.items.size- Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with $itemCount items.")- }- else -> Unit- }-- val lazyWarnings = buildList {- addAll(strategyWarnings(categoryPayload.catalogResult))- addAll(strategyWarnings(fullPayload.catalogResult))- if (!resolvedCategories.isNullOrEmpty()) {- add("Movies entered lazy category-only mode after category-bulk and full strategies failed.")- } else {- addAll(strategyWarnings(pagedPayload.catalogResult))- add("Movies entered lazy category-only mode after category-bulk, paged, and full strategies failed.")- }- }- Log.w(- TAG,- "Xtream movies strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) VodSyncMode.LAZY_BY_CATEGORY else VodSyncMode.UNKNOWN}"- )-- return if (!resolvedCategories.isNullOrEmpty()) {- MovieCatalogSyncResult(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "lazy_by_category",- error = IllegalStateException("Movie catalog strategies failed; exposing categories only"),- warnings = lazyWarnings- ),- categories = resolvedCategories,- syncMode = VodSyncMode.LAZY_BY_CATEGORY,- warnings = lazyWarnings,- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- segmentedStressDetected = true- )- )- } else {- MovieCatalogSyncResult(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "movies",- error = IllegalStateException("Movie catalog strategies failed and no categories were available"),- warnings = lazyWarnings- ),- categories = null,- syncMode = VodSyncMode.UNKNOWN,- warnings = lazyWarnings,- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- segmentedStressDetected = true- )- )- }- }+ ): MovieCatalogSyncResult =+ xtreamMovieStrategy.syncXtreamMoviesCatalog(provider, api, existingMetadata, onProgress)private suspend fun loadXtreamMoviesFull(provider: Provider,api: XtreamProvider- ): CatalogSyncPayload<Movie> {- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)- val seenStreamIds = HashSet<Long>()- val rawBatch = ArrayList<XtreamStream>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)- var stagedSessionId: Long? = null- var acceptedCount = 0- var streamedRawCount = 0- var fullMoviesFailure: Throwable? = null-- suspend fun flushRawBatch() {- if (rawBatch.isEmpty()) return- val staged = stageMovieSequence(- providerId = provider.id,- items = api.mapVodStreamsSequence(rawBatch.asSequence()),- seenStreamIds = seenStreamIds,- fallbackCollector = fallbackCollector,- sessionId = stagedSessionId- )- stagedSessionId = staged.sessionId- acceptedCount += staged.acceptedCount- rawBatch.clear()- }-- val fullMoviesElapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withMovieRequestTimeout("full movie catalog") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {- xtreamCatalogHttpService.streamVodStreams(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_vod_streams"- )- ) { stream ->- rawBatch += stream- streamedRawCount++- if (rawBatch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {- flushRawBatch()- }- }.also {- flushRawBatch()- }- }- }- }- }) {- is Attempt.Success -> Unit- is Attempt.Failure -> {- fullMoviesFailure = attempt.error- stagedSessionId?.let { sessionId ->- syncCatalogStore.discardStagedImport(provider.id, sessionId)- stagedSessionId = null- }- }- }- }- if (streamedRawCount > 0) {- Log.i(- TAG,- "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."- )- if (acceptedCount == 0) {- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "full",- warnings = listOf("Movies full catalog returned raw items but none were usable after mapping.")- ),- categories = null- )- }- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success(- strategyName = "full",- items = emptyList()- ),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = stagedSessionId,- stagedAcceptedCount = acceptedCount- )- }- return if (fullMoviesFailure != null) {- logXtreamCatalogFallback(- provider = provider,- section = "movies",- stage = "full catalog",- elapsedMs = fullMoviesElapsedMs,- itemCount = streamedRawCount,- error = fullMoviesFailure,- nextStep = "category-bulk"- )- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "full",- error = fullMoviesFailure!!,- warnings = listOf(fullCatalogFallbackWarning("Movies", fullMoviesFailure))- ),- categories = null- )- } else {- logXtreamCatalogFallback(- provider = provider,- section = "movies",- stage = "full catalog",- elapsedMs = fullMoviesElapsedMs,- itemCount = streamedRawCount,- error = null,- nextStep = "category-bulk"- )- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "full",- warnings = listOf("Movies full catalog returned an empty valid result.")- ),- categories = null- )- }- }+ ): CatalogSyncPayload<Movie> = xtreamMovieStrategy.loadXtreamMoviesFull(provider, api)private suspend fun syncXtreamLiveCatalog(provider: Provider,@@ -1849,161 +1341,13 @@ class SyncManager @Inject constructor(existingMetadata: SyncMetadata,hiddenLiveCategoryIds: Set<Long>,onProgress: ((String) -> Unit)?- ): CatalogSyncPayload<Channel> {- Log.i(TAG, "Xtream live strategy start for provider ${provider.id}.")- val rawLiveCategories = when (val attempt = attemptNonCancellation {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {- xtreamCatalogApiService.getLiveCategories(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_live_categories"- )- )- }- }- }) {- is Attempt.Success -> attempt.value- is Attempt.Failure -> {- Log.w(TAG, "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")- null- }- }- val resolvedCategories = rawLiveCategories- ?.let { categories -> api.mapCategories(ContentType.LIVE, categories) }- ?.map { category -> category.toEntity(provider.id) }- ?.takeIf { it.isNotEmpty() }- val filteredRawLiveCategories = rawLiveCategories.orEmpty().filterNot { category ->- category.categoryId.toLongOrNull() in hiddenLiveCategoryIds- }- val visibleResolvedCategories = resolvedCategories- ?.filterNot { category -> category.categoryId in hiddenLiveCategoryIds }- ?.takeIf { it.isNotEmpty() }- var fullResult: CatalogStrategyResult<Channel> = CatalogStrategyResult.EmptyValid("full")- var categoryResult: CatalogStrategyResult<Channel> = CatalogStrategyResult.EmptyValid("category_bulk")- if (hiddenLiveCategoryIds.isEmpty()) {- progress(provider.id, onProgress, "Downloading Live TV...")- fullResult = loadXtreamLiveFull(provider, api)- when (fullResult) {- is CatalogStrategyResult.Success -> return CatalogSyncPayload(- catalogResult = fullResult,- categories = mergePreferredAndFallbackCategories(- visibleResolvedCategories,- buildFallbackLiveCategories(provider.id, fullResult.items)- ),- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(- attemptedFullCatalog = true,- fullCatalogUnsafe = false- )- )- is CatalogStrategyResult.Partial -> return CatalogSyncPayload(- catalogResult = fullResult,- categories = mergePreferredAndFallbackCategories(- visibleResolvedCategories,- buildFallbackLiveCategories(provider.id, fullResult.items)- ),- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(- attemptedFullCatalog = true,- fullCatalogUnsafe = false- )- )- else -> Unit- }- } else {- Log.i(TAG, "Xtream live full catalog skipped for provider ${provider.id} because ${hiddenLiveCategoryIds.size} live categories are hidden.")- }-- progress(provider.id, onProgress, "Downloading Live TV by category...")- categoryResult = loadXtreamLiveByCategory(- provider,- api,- filteredRawLiveCategories,- onProgress,- preferSequential = existingMetadata.liveSequentialFailuresRemembered- )- return CatalogSyncPayload(- catalogResult = categoryResult,- categories = when (categoryResult) {- is CatalogStrategyResult.Success -> mergePreferredAndFallbackCategories(- visibleResolvedCategories,- buildFallbackLiveCategories(provider.id, categoryResult.items)- )- is CatalogStrategyResult.Partial -> mergePreferredAndFallbackCategories(- visibleResolvedCategories,- buildFallbackLiveCategories(provider.id, categoryResult.items)- )- else -> null- },- warnings = strategyWarnings(fullResult),- strategyFeedback = XtreamStrategyFeedback(- attemptedFullCatalog = true,- fullCatalogUnsafe = (fullResult as? CatalogStrategyResult.Failure)?.error?.let(::shouldAvoidFullCatalogStrategy) == true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullResult),- result = categoryResult,- sequentialWarnings = setOf(LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)- )- )- )- }+ ): CatalogSyncPayload<Channel> =+ xtreamLiveStrategy.syncXtreamLiveCatalog(provider, api, existingMetadata, hiddenLiveCategoryIds, onProgress)private suspend fun loadXtreamLiveFull(provider: Provider,api: XtreamProvider- ): CatalogStrategyResult<Channel> {- var fullChannels: List<Channel>? = null- var fullChannelsFailure: Throwable? = null- val fullChannelsElapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {- api.getLiveStreams().getOrThrow("Live streams")- }- }- }) {- is Attempt.Success -> fullChannels = attempt.value- is Attempt.Failure -> fullChannelsFailure = attempt.error- }- }- if (!fullChannels.isNullOrEmpty()) {- Log.i(TAG, "Xtream live full catalog succeeded for provider ${provider.id} in ${fullChannelsElapsedMs}ms with ${fullChannels!!.size} items.")- return CatalogStrategyResult.Success("full", fullChannels!!)- }- return if (fullChannelsFailure != null) {- logXtreamCatalogFallback(- provider = provider,- section = "live",- stage = "full catalog",- elapsedMs = fullChannelsElapsedMs,- itemCount = fullChannels?.size,- error = fullChannelsFailure,- nextStep = "category-bulk"- )- CatalogStrategyResult.Failure(- strategyName = "full",- error = fullChannelsFailure!!,- warnings = listOf(fullCatalogFallbackWarning("Live TV", fullChannelsFailure))- )- } else {- logXtreamCatalogFallback(- provider = provider,- section = "live",- stage = "full catalog",- elapsedMs = fullChannelsElapsedMs,- itemCount = fullChannels?.size,- error = null,- nextStep = "category-bulk"- )- CatalogStrategyResult.EmptyValid(- strategyName = "full",- warnings = listOf("Live full catalog returned an empty valid result.")- )- }- }+ ): CatalogStrategyResult<Channel> = xtreamLiveStrategy.loadXtreamLiveFull(provider, api)private suspend fun loadXtreamLiveByCategory(provider: Provider,@@ -2011,1293 +1355,83 @@ class SyncManager @Inject constructor(rawCategories: List<XtreamCategory>,onProgress: ((String) -> Unit)?,preferSequential: Boolean- ): CatalogStrategyResult<Channel> {- val categories = rawCategories.filter { it.categoryId.isNotBlank() }- if (categories.isEmpty()) {- return CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("No live categories available"),- warnings = listOf("Live category-bulk strategy was unavailable because no categories were returned.")- )- }-- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(- providerId = provider.id,- workloadSize = categories.size,- preferSequential = preferSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY- )- progress(provider.id, onProgress, "Downloading Live TV by category 0/${categories.size}...")-- val executionPlan = executeCategoryRecoveryPlan(- provider = provider,- categories = categories,- initialConcurrency = concurrency,- sectionLabel = "Live TV",- sequentialModeWarning = LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING,- onProgress = onProgress,- fetch = { category -> fetchLiveCategoryOutcome(provider, api, category) }- )- var timedOutcomes = executionPlan.outcomes+ ): CatalogStrategyResult<Channel> =+ xtreamLiveStrategy.loadXtreamLiveByCategory(provider, api, rawCategories, onProgress, preferSequential)- val categoryOutcomes = timedOutcomes.map { it.outcome }- val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }- val fastFailureCount = timedOutcomes.count {- it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure- }-- val downgradeRecommended = shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)- var fallbackWarnings = executionPlan.warnings- if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {- Log.w(TAG, "Xtream live category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")- timedOutcomes = continueFailedCategoryOutcomes(- provider = provider,- timedOutcomes = timedOutcomes,- fetchSequentially = { category -> fetchLiveCategoryOutcome(provider, api, category) }- )- fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()- }+ private suspend fun loadXtreamMoviesByCategory(+ provider: Provider,+ api: XtreamProvider,+ rawCategories: List<XtreamCategory>,+ onProgress: ((String) -> Unit)?,+ preferSequential: Boolean+ ): CatalogSyncPayload<Movie> =+ xtreamMovieStrategy.loadXtreamMoviesByCategory(provider, api, rawCategories, onProgress, preferSequential)- val finalOutcomes = timedOutcomes.map { it.outcome }- val warnings = finalOutcomes- .filterIsInstance<CategoryFetchOutcome.Failure>()- .map { failure -> categoryFailureWarning("Live TV", failure.categoryName, failure.error) } +- fallbackWarnings+ private suspend fun loadXtreamMoviesByPage(+ provider: Provider,+ api: XtreamProvider,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Movie> = xtreamMovieStrategy.loadXtreamMoviesByPage(provider, api, onProgress)- val channels = finalOutcomes- .asSequence()- .filterIsInstance<CategoryFetchOutcome.Success<Channel>>()- .flatMap { it.items.asSequence() }- .filter { it.streamId > 0L }- .associateBy { it.streamId }- .values- .toList()- val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }- val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }- val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }- Log.i(TAG, "Xtream live category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedChannels=${channels.size} concurrency=$concurrency")+ private suspend fun syncXtreamSeriesCatalog(+ provider: Provider,+ api: XtreamProvider,+ existingMetadata: SyncMetadata,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Series> =+ xtreamSeriesStrategy.syncXtreamSeriesCatalog(provider, api, existingMetadata, onProgress)- return when {- channels.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", channels, warnings.toList())- channels.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", channels, warnings.toList())- failedCategories > 0 -> CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("Live category-bulk sync failed for all usable categories"),- warnings = warnings.toList()- )- else -> CatalogStrategyResult.EmptyValid(- strategyName = "category_bulk",- warnings = listOf("All live categories returned valid empty results.")- )- }- }+ private suspend fun loadXtreamSeriesFull(+ provider: Provider,+ api: XtreamProvider+ ): CatalogSyncPayload<Series> = xtreamSeriesStrategy.loadXtreamSeriesFull(provider, api)- private suspend fun loadXtreamMoviesByCategory(+ private suspend fun loadXtreamSeriesByCategory(provider: Provider,api: XtreamProvider,rawCategories: List<XtreamCategory>,onProgress: ((String) -> Unit)?,preferSequential: Boolean- ): CatalogSyncPayload<Movie> {- val categories = rawCategories.filter { it.categoryId.isNotBlank() }- if (categories.isEmpty()) {- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("No VOD categories available"),- warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")- ),- categories = null- )- }+ ): CatalogSyncPayload<Series> =+ xtreamSeriesStrategy.loadXtreamSeriesByCategory(provider, api, rawCategories, onProgress, preferSequential)- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(- providerId = provider.id,- workloadSize = categories.size,- preferSequential = preferSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY- )- progress(provider.id, onProgress, "Downloading Movies by category 0/${categories.size}...")+ private suspend fun loadXtreamSeriesByPage(+ provider: Provider,+ api: XtreamProvider,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Series> = xtreamSeriesStrategy.loadXtreamSeriesByPage(provider, api, onProgress)- val executionPlan = executeCategoryRecoveryPlan(- provider = provider,- categories = categories,- initialConcurrency = concurrency,- sectionLabel = "Movies",- sequentialModeWarning = MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING,- onProgress = onProgress,- fetch = { category -> fetchMovieCategoryOutcome(provider, api, category) }- )- var timedOutcomes = executionPlan.outcomes+ private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {+ val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId))+ .copy(lastSyncStatus = status)+ syncMetadataRepository.updateMetadata(metadata)+ }- val categoryOutcomes = timedOutcomes.map { it.outcome }- val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }- val fastFailureCount = timedOutcomes.count {- it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure- }+ private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? =+ xtreamMovieStrategy.fetchXtreamVodCategories(provider)- val downgradeRecommended = shouldDowngradeCategorySync(- totalCategories = categories.size,- failures = failureCount,- fastFailures = fastFailureCount,- outcomes = categoryOutcomes- )- var fallbackWarnings = executionPlan.warnings- if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {- val downgradeReasons = buildList {- add("failures=$failureCount/${categories.size}")- if (fastFailureCount > 0) add("fastFailures=$fastFailureCount")- val providerStressSignals = categoryOutcomes.count { outcome ->- outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- if (providerStressSignals > 0) add("providerStressSignals=$providerStressSignals")- }.joinToString(", ")- Log.w(- TAG,- "Xtream movie category sync is continuing in sequential mode for failed categories on provider ${provider.id}: $downgradeReasons"- )- timedOutcomes = continueFailedCategoryOutcomes(- provider = provider,- timedOutcomes = timedOutcomes,- fetchSequentially = { category -> fetchMovieCategoryOutcome(provider, api, category) }- )- fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()- }+ private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> =+ catalogStrategySupport.strategyWarnings(result)- val finalOutcomes = timedOutcomes.map { it.outcome }- val warnings = finalOutcomes- .filterIsInstance<CategoryFetchOutcome.Failure>()- .map { failure -> categoryFailureWarning("Movies", failure.categoryName, failure.error) } +- fallbackWarnings-- val seenStreamIds = HashSet<Long>()- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)- var sessionId: Long? = null- var acceptedCount = 0- finalOutcomes- .filterIsInstance<CategoryFetchOutcome.Success<Movie>>()- .forEach { success ->- val staged = stageMovieItems(- providerId = provider.id,- items = success.items,- seenStreamIds = seenStreamIds,- fallbackCollector = fallbackCollector,- sessionId = sessionId- )- sessionId = staged.sessionId- acceptedCount += staged.acceptedCount- }-- val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }- val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }- val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }- Log.i(- TAG,- "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=$acceptedCount concurrency=$concurrency"- )- return when {- acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success(- strategyName = "category_bulk",- items = emptyList(),- warnings = warnings.toList()- ),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- acceptedCount > 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Partial(- strategyName = "category_bulk",- items = emptyList(),- warnings = warnings.toList()- ),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- failedCategories > 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),- warnings = warnings.toList()- ),- categories = null- )- else -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "category_bulk",- warnings = listOf("All movie categories returned valid empty results.")- ),- categories = null- )- }- }-- private suspend fun loadXtreamMoviesByPage(- provider: Provider,- api: XtreamProvider,- onProgress: ((String) -> Unit)?- ): CatalogSyncPayload<Movie> {- val seenStreamIds = HashSet<Long>()- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)- val warnings = mutableListOf<String>()- var sessionId: Long? = null- var acceptedCount = 0- var nextPage = 1- var stopPaging = false- var forceSequential = false-- while (nextPage <= XTREAM_CATALOG_MAX_PAGES && !stopPaging) {- val remainingPages = XTREAM_CATALOG_MAX_PAGES - nextPage + 1- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(- providerId = provider.id,- workloadSize = remainingPages,- preferSequential = forceSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.PAGED- )- val pageWindow = (nextPage until (nextPage + concurrency))- .takeWhile { it <= XTREAM_CATALOG_MAX_PAGES }- progress(- provider.id,- onProgress,- if (pageWindow.size == 1) {- "Downloading Movies by page ${pageWindow.first()}..."- } else {- "Downloading Movies by page ${pageWindow.first()}-${pageWindow.last()}..."- }- )-- var timedOutcomes = coroutineScope {- pageWindow.map { page ->- async { fetchMoviePageOutcome(provider, api, page) }- }.awaitAll()- }- val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }- val recoveryPlan = evaluatePageRecoveryPlan(- provider = provider,- sectionLabel = "Movies",- pageWindow = pageWindow,- outcomes = timedOutcomes,- sequentialModeWarning = MOVIE_PAGED_SEQUENTIAL_MODE_WARNING- )- forceSequential = forceSequential || recoveryPlan.warnings.any { it == MOVIE_PAGED_SEQUENTIAL_MODE_WARNING }- warnings += recoveryPlan.warnings- if (recoveryPlan.stoppedEarly) {- stopPaging = true- }- if (!recoveryPlan.stoppedEarly && concurrency > 1 && shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {- timedOutcomes = continueFailedPageOutcomes(- provider = provider,- timedOutcomes = timedOutcomes,- fetchSequentially = { page -> fetchMoviePageOutcome(provider, api, page) }- )- }-- var terminalFailure: Throwable? = null- var terminalFailurePage: Int? = null- timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->- when (val outcome = timedOutcome.outcome) {- is PageFetchOutcome.Success -> {- val staged = stageMovieItems(- providerId = provider.id,- items = outcome.items,- seenStreamIds = seenStreamIds,- fallbackCollector = fallbackCollector,- sessionId = sessionId- )- sessionId = staged.sessionId- acceptedCount += staged.acceptedCount- val newItems = staged.acceptedCount- if (outcome.rawCount < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {- stopPaging = true- }- }- is PageFetchOutcome.Empty -> {- stopPaging = true- }- is PageFetchOutcome.Failure -> {- warnings += pagingFailureWarning("Movies", outcome.page, outcome.error)- if (terminalFailure == null) {- terminalFailure = outcome.error- terminalFailurePage = outcome.page- }- }- }- }-- if (terminalFailure != null) {- return if (acceptedCount == 0) {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "paged",- error = terminalFailure!!,- warnings = listOf(- pagingFailureWarning("Movies", terminalFailurePage ?: nextPage, terminalFailure!!)- )- )- ,- categories = null- )- } else {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Partial(- strategyName = "paged",- items = emptyList(),- warnings = warnings.toList()- ),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- }- }-- nextPage = pageWindow.last() + 1- }-- return if (acceptedCount > 0) {- Log.i(TAG, "Xtream paged movie strategy completed for provider ${provider.id} with $acceptedCount deduped items.")- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- } else {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "paged",- warnings = listOf("Paged movie catalog completed without items.")- ),- categories = null- )- }- }-- private suspend fun syncXtreamSeriesCatalog(- provider: Provider,- api: XtreamProvider,- existingMetadata: SyncMetadata,- onProgress: ((String) -> Unit)?- ): CatalogSyncPayload<Series> {- Log.i(TAG, "Xtream series strategy start for provider ${provider.id}.")- val rawSeriesCategories = when (val attempt = attemptNonCancellation {- withSeriesRequestTimeout("series categories") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {- xtreamCatalogApiService.getSeriesCategories(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_series_categories"- )- )- }- }- }- }) {- is Attempt.Success -> attempt.value- is Attempt.Failure -> {- Log.w(TAG, "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")- null- }- }- val resolvedCategories = rawSeriesCategories- ?.let { categories -> api.mapCategories(ContentType.SERIES, categories) }- ?.map { category -> category.toEntity(provider.id) }- ?.takeIf { it.isNotEmpty() }- var fullPayload = CatalogSyncPayload<Series>(- catalogResult = CatalogStrategyResult.EmptyValid("full"),- categories = null- )- var pagedPayload = CatalogSyncPayload<Series>(- catalogResult = CatalogStrategyResult.EmptyValid("paged"),- categories = null- )- var categoryPayload = CatalogSyncPayload<Series>(- catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),- categories = null- )-- // Fast sync: skip all downloads, expose categories only and hydrate on demand.- if (provider.xtreamFastSyncEnabled) {- return if (!resolvedCategories.isNullOrEmpty()) {- Log.i(TAG, "Xtream series fast sync: returning lazy_by_category for provider ${provider.id} with ${resolvedCategories.size} categories.")- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "lazy_by_category",- error = IllegalStateException("Fast sync enabled; series will hydrate on demand"),- warnings = emptyList()- ),- categories = resolvedCategories,- warnings = emptyList(),- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)- )- } else {- Log.w(TAG, "Xtream series fast sync: no categories available for provider ${provider.id}.")- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "fast_sync_no_categories",- error = IllegalStateException("Fast sync enabled but no series categories available"),- warnings = listOf("Fast sync enabled but no series categories returned from server.")- ),- categories = null,- warnings = listOf("Fast sync enabled but no series categories returned from server."),- strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)- )- }- }-- if (!resolvedCategories.isNullOrEmpty()) {- progress(provider.id, onProgress, "Preparing Series category sync...")- categoryPayload = loadXtreamSeriesByCategory(- provider,- api,- rawSeriesCategories.orEmpty(),- onProgress,- preferSequential = existingMetadata.seriesSequentialFailuresRemembered- )- when (val categoryResult = categoryPayload.catalogResult) {- is CatalogStrategyResult.Success,- is CatalogStrategyResult.Partial -> return CatalogSyncPayload(- catalogResult = categoryResult,- categories = mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),- warnings = strategyWarnings(fullPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult),- result = categoryResult,- sequentialWarnings = setOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = categoryPayload.stagedSessionId,- stagedAcceptedCount = categoryPayload.stagedAcceptedCount- )- else -> Unit- }- }-- if (resolvedCategories.isNullOrEmpty()) {- progress(provider.id, onProgress, "Checking Series paged catalog...")- pagedPayload = loadXtreamSeriesByPage(provider, api, onProgress)- when (val pagedResult = pagedPayload.catalogResult) {- is CatalogStrategyResult.Success,- is CatalogStrategyResult.Partial -> return CatalogSyncPayload(- catalogResult = pagedResult,- categories = pagedPayload.categories,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(categoryPayload.catalogResult),- result = pagedResult,- sequentialWarnings = setOf(SERIES_PAGED_SEQUENTIAL_MODE_WARNING, SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = pagedPayload.stagedSessionId,- stagedAcceptedCount = pagedPayload.stagedAcceptedCount- )- else -> Unit- }-- progress(provider.id, onProgress, "Preparing Series category sync...")- categoryPayload = loadXtreamSeriesByCategory(- provider,- api,- rawSeriesCategories.orEmpty(),- onProgress,- preferSequential = existingMetadata.seriesSequentialFailuresRemembered- )- when (val categoryResult = categoryPayload.catalogResult) {- is CatalogStrategyResult.Success,- is CatalogStrategyResult.Partial -> return CatalogSyncPayload(- catalogResult = categoryResult,- categories = categoryPayload.categories,- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- segmentedStressDetected = sawSegmentedStress(- warnings = strategyWarnings(fullPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- result = categoryResult,- sequentialWarnings = setOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING, SERIES_PAGED_SEQUENTIAL_MODE_WARNING)- )- ),- stagedSessionId = categoryPayload.stagedSessionId,- stagedAcceptedCount = categoryPayload.stagedAcceptedCount- )- else -> Unit- }- }-- progress(provider.id, onProgress, "Checking Series full catalog...")- fullPayload = loadXtreamSeriesFull(provider, api)- when (val fullResult = fullPayload.catalogResult) {- is CatalogStrategyResult.Success -> return CatalogSyncPayload(- catalogResult = fullResult,- categories = resolvedCategories ?: fullPayload.categories,- warnings = strategyWarnings(categoryPayload.catalogResult) + strategyWarnings(pagedPayload.catalogResult),- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- fullCatalogUnsafe = false- ),- stagedSessionId = fullPayload.stagedSessionId,- stagedAcceptedCount = fullPayload.stagedAcceptedCount- )- else -> Unit- }-- val lazyWarnings = buildList {- addAll(strategyWarnings(categoryPayload.catalogResult))- addAll(strategyWarnings(fullPayload.catalogResult))- if (!resolvedCategories.isNullOrEmpty()) {- add("Series entered lazy category-only mode after category-bulk and full strategies failed.")- } else {- addAll(strategyWarnings(pagedPayload.catalogResult))- add("Series entered lazy category-only mode after category-bulk, paged, and full strategies failed.")- }- }- Log.w(- TAG,- "Xtream series strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) "lazy_by_category" else "unavailable"}"- )-- return if (!resolvedCategories.isNullOrEmpty()) {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "lazy_by_category",- error = IllegalStateException("Series catalog strategies failed; exposing categories only"),- warnings = lazyWarnings- ),- categories = resolvedCategories,- warnings = lazyWarnings,- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- segmentedStressDetected = true- )- )- } else {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "series",- error = IllegalStateException("Series catalog strategies failed and no categories were available"),- warnings = lazyWarnings- ),- categories = null,- warnings = lazyWarnings,- strategyFeedback = XtreamStrategyFeedback(- preferredSegmentedFirst = true,- attemptedFullCatalog = true,- segmentedStressDetected = true- )- )- }- }-- private suspend fun loadXtreamSeriesFull(- provider: Provider,- api: XtreamProvider- ): CatalogSyncPayload<Series> {- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)- val seenSeriesIds = HashSet<Long>()- val rawBatch = ArrayList<XtreamSeriesItem>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)- var stagedSessionId: Long? = null- var acceptedCount = 0- var streamedRawCount = 0- var fullSeriesFailure: Throwable? = null-- suspend fun flushRawBatch() {- if (rawBatch.isEmpty()) return- val staged = stageSeriesSequence(- providerId = provider.id,- items = api.mapSeriesListSequence(rawBatch.asSequence()),- seenSeriesIds = seenSeriesIds,- fallbackCollector = fallbackCollector,- sessionId = stagedSessionId- )- stagedSessionId = staged.sessionId- acceptedCount += staged.acceptedCount- rawBatch.clear()- }-- val fullSeriesElapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withSeriesRequestTimeout("full series catalog") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {- xtreamCatalogHttpService.streamSeriesList(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_series"- )- ) { item ->- rawBatch += item- streamedRawCount++- if (rawBatch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {- flushRawBatch()- }- }.also {- flushRawBatch()- }- }- }- }- }) {- is Attempt.Success -> Unit- is Attempt.Failure -> {- fullSeriesFailure = attempt.error- stagedSessionId?.let { sessionId ->- syncCatalogStore.discardStagedImport(provider.id, sessionId)- stagedSessionId = null- }- }- }- }- if (streamedRawCount > 0) {- Log.i(- TAG,- "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."- )- if (acceptedCount == 0) {- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "full",- warnings = listOf("Series full catalog returned raw items but none were usable after mapping.")- ),- categories = null- )- }- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success("full", emptyList()),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = stagedSessionId,- stagedAcceptedCount = acceptedCount- )- }- return if (fullSeriesFailure != null) {- logXtreamCatalogFallback(- provider = provider,- section = "series",- stage = "full catalog",- elapsedMs = fullSeriesElapsedMs,- itemCount = streamedRawCount,- error = fullSeriesFailure,- nextStep = "category-bulk"- )- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "full",- error = fullSeriesFailure!!,- warnings = listOf(fullCatalogFallbackWarning("Series", fullSeriesFailure))- ),- categories = null- )- } else {- logXtreamCatalogFallback(- provider = provider,- section = "series",- stage = "full catalog",- elapsedMs = fullSeriesElapsedMs,- itemCount = streamedRawCount,- error = null,- nextStep = "category-bulk"- )- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "full",- warnings = listOf("Series full catalog returned an empty valid result.")- ),- categories = null- )- }- }-- private suspend fun loadXtreamSeriesByCategory(- provider: Provider,- api: XtreamProvider,- rawCategories: List<XtreamCategory>,- onProgress: ((String) -> Unit)?,- preferSequential: Boolean- ): CatalogSyncPayload<Series> {- val categories = rawCategories.filter { it.categoryId.isNotBlank() }- if (categories.isEmpty()) {- return CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("No series categories available"),- warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")- ),- categories = null- )- }-- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(- providerId = provider.id,- workloadSize = categories.size,- preferSequential = preferSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY- )- progress(provider.id, onProgress, "Downloading Series by category 0/${categories.size}...")-- val executionPlan = executeCategoryRecoveryPlan(- provider = provider,- categories = categories,- initialConcurrency = concurrency,- sectionLabel = "Series",- sequentialModeWarning = SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING,- onProgress = onProgress,- fetch = { category -> fetchSeriesCategoryOutcome(provider, api, category) }- )- var timedOutcomes = executionPlan.outcomes-- val categoryOutcomes = timedOutcomes.map { it.outcome }- val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }- val fastFailureCount = timedOutcomes.count {- it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure- }-- val downgradeRecommended = shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)- var fallbackWarnings = executionPlan.warnings- if (concurrency > 1 && shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {- Log.w(TAG, "Xtream series category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")- timedOutcomes = continueFailedCategoryOutcomes(- provider = provider,- timedOutcomes = timedOutcomes,- fetchSequentially = { category -> fetchSeriesCategoryOutcome(provider, api, category) }- )- fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING) else emptyList()).distinct()- }-- val finalOutcomes = timedOutcomes.map { it.outcome }- val warnings = finalOutcomes- .filterIsInstance<CategoryFetchOutcome.Failure>()- .map { failure -> categoryFailureWarning("Series", failure.categoryName, failure.error) } +- fallbackWarnings-- val seenSeriesIds = HashSet<Long>()- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)- var sessionId: Long? = null- var acceptedCount = 0- finalOutcomes- .filterIsInstance<CategoryFetchOutcome.Success<Series>>()- .forEach { success ->- val staged = stageSeriesItems(- providerId = provider.id,- items = success.items,- seenSeriesIds = seenSeriesIds,- fallbackCollector = fallbackCollector,- sessionId = sessionId- )- sessionId = staged.sessionId- acceptedCount += staged.acceptedCount- }- val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }- val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }- val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }- Log.i(TAG, "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=$acceptedCount concurrency=$concurrency")-- return when {- acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- acceptedCount > 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Partial("category_bulk", emptyList(), warnings.toList()),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- failedCategories > 0 -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "category_bulk",- error = IllegalStateException("Series category-bulk sync failed for all usable categories"),- warnings = warnings.toList()- ),- categories = null- )- else -> CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "category_bulk",- warnings = listOf("All series categories returned valid empty results.")- ),- categories = null- )- }- }-- private suspend fun loadXtreamSeriesByPage(- provider: Provider,- api: XtreamProvider,- onProgress: ((String) -> Unit)?- ): CatalogSyncPayload<Series> {- val seenSeriesIds = HashSet<Long>()- val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)- val warnings = mutableListOf<String>()- var sessionId: Long? = null- var acceptedCount = 0- var nextPage = 1- var stopPaging = false- var forceSequential = false-- while (nextPage <= XTREAM_CATALOG_MAX_PAGES && !stopPaging) {- val remainingPages = XTREAM_CATALOG_MAX_PAGES - nextPage + 1- val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(- providerId = provider.id,- workloadSize = remainingPages,- preferSequential = forceSequential,- stage = XtreamAdaptiveSyncPolicy.Stage.PAGED- )- val pageWindow = (nextPage until (nextPage + concurrency))- .takeWhile { it <= XTREAM_CATALOG_MAX_PAGES }- progress(- provider.id,- onProgress,- if (pageWindow.size == 1) {- "Downloading Series by page ${pageWindow.first()}..."- } else {- "Downloading Series by page ${pageWindow.first()}-${pageWindow.last()}..."- }- )-- var timedOutcomes = coroutineScope {- pageWindow.map { page ->- async { fetchSeriesPageOutcome(provider, api, page) }- }.awaitAll()- }- val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }- val recoveryPlan = evaluatePageRecoveryPlan(- provider = provider,- sectionLabel = "Series",- pageWindow = pageWindow,- outcomes = timedOutcomes,- sequentialModeWarning = SERIES_PAGED_SEQUENTIAL_MODE_WARNING- )- forceSequential = forceSequential || recoveryPlan.warnings.any { it == SERIES_PAGED_SEQUENTIAL_MODE_WARNING }- warnings += recoveryPlan.warnings- if (recoveryPlan.stoppedEarly) {- stopPaging = true- }- if (!recoveryPlan.stoppedEarly && concurrency > 1 && shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {- timedOutcomes = continueFailedPageOutcomes(- provider = provider,- timedOutcomes = timedOutcomes,- fetchSequentially = { page -> fetchSeriesPageOutcome(provider, api, page) }- )- }-- var terminalFailure: Throwable? = null- var terminalFailurePage: Int? = null- timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->- when (val outcome = timedOutcome.outcome) {- is PageFetchOutcome.Success -> {- val staged = stageSeriesItems(- providerId = provider.id,- items = outcome.items,- seenSeriesIds = seenSeriesIds,- fallbackCollector = fallbackCollector,- sessionId = sessionId- )- sessionId = staged.sessionId- acceptedCount += staged.acceptedCount- val newItems = staged.acceptedCount- if (outcome.rawCount < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {- stopPaging = true- }- }- is PageFetchOutcome.Empty -> {- stopPaging = true- }- is PageFetchOutcome.Failure -> {- warnings += pagingFailureWarning("Series", outcome.page, outcome.error)- if (terminalFailure == null) {- terminalFailure = outcome.error- terminalFailurePage = outcome.page- }- }- }- }-- if (terminalFailure != null) {- return if (acceptedCount == 0) {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Failure(- strategyName = "paged",- error = terminalFailure!!,- warnings = listOf(- pagingFailureWarning("Series", terminalFailurePage ?: nextPage, terminalFailure!!)- )- )- ,- categories = null- )- } else {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Partial(- strategyName = "paged",- items = emptyList(),- warnings = warnings.toList()- ),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- }- }-- nextPage = pageWindow.last() + 1- }-- return if (acceptedCount > 0) {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),- categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },- stagedSessionId = sessionId,- stagedAcceptedCount = acceptedCount- )- } else {- CatalogSyncPayload(- catalogResult = CatalogStrategyResult.EmptyValid(- strategyName = "paged",- warnings = listOf("Paged series catalog completed without items.")- ),- categories = null- )- }- }-- private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {- val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId))- .copy(lastSyncStatus = status)- syncMetadataRepository.updateMetadata(metadata)- }-- private suspend fun importM3uPlaylist(- provider: Provider,- onProgress: ((String) -> Unit)?,- includeLive: Boolean = true,- includeMovies: Boolean = true,- batchSize: Int = 1000- ): M3uImportStats {- UrlSecurityPolicy.validatePlaylistSourceUrl(provider.m3uUrl.ifBlank { provider.serverUrl })?.let { message ->- throw IllegalStateException(message)- }- progress(provider.id, onProgress, "Downloading Playlist...")- syncCatalogStore.clearProviderStaging(provider.id)- val sessionId = syncCatalogStore.newSessionId()- val stableLongHasher = StableLongHasher()- val liveCategories = CategoryAccumulator(provider.id, ContentType.LIVE, stableLongHasher)- val movieCategories = CategoryAccumulator(provider.id, ContentType.MOVIE, stableLongHasher)- val channelBatch = ArrayList<ChannelEntity>(batchSize)- val movieBatch = ArrayList<MovieEntity>(batchSize)- val seenLiveStreamIds = if (includeLive) mutableSetOf<Long>() else null- val seenMovieStreamIds = if (includeMovies) mutableSetOf<Long>() else null- var header = M3uParser.M3uHeader()- var liveCount = 0- var movieCount = 0- var parsedCount = 0- var nextMilestone = PROGRESS_INTERVAL- val warnings = mutableListOf<String>()- var insecureStreamCount = 0-- try {- openPlaylistStream(provider) { streamed ->- progress(provider.id, onProgress, "Parsing Playlist...")- maybeDecompressPlaylist(streamed).use { input ->- m3uParser.parseStreaming(- inputStream = input,- onHeader = { parsedHeader ->- val secureEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.isSecureRemoteUrl(it) }- if (parsedHeader.tvgUrl != null && secureEpgUrl == null) {- warnings += "Ignored insecure EPG URL from playlist header."- }- header = parsedHeader.copy(tvgUrl = secureEpgUrl)- }- ) { entry ->- parsedCount++- if (parsedCount >= nextMilestone) {- progress(provider.id, onProgress, "Imported $parsedCount playlist entries...")- nextMilestone += PROGRESS_INTERVAL- }- if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {- insecureStreamCount++- return@parseStreaming- }-- val safeLogoUrl = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.tvgLogo)- val safeCatchUpSource = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.catchUpSource)-- if (provider.m3uVodClassificationEnabled && isVodEntry(entry)) {- if (!includeMovies) {- return@parseStreaming- }- val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }- val stableStreamId = stableId(- providerId = provider.id,- contentType = ContentType.MOVIE,- tvgId = entry.tvgId,- url = entry.url,- title = entry.name,- groupTitle = groupTitle,- hasher = stableLongHasher- )- if (seenMovieStreamIds?.add(stableStreamId) != true) {- return@parseStreaming- }- val categoryId = movieCategories.idFor(groupTitle)- val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)- movieBatch.add(- MovieEntity(- streamId = stableStreamId,- name = entry.name,- posterUrl = safeLogoUrl,- categoryId = categoryId,- categoryName = groupTitle,- streamUrl = entry.url,- providerId = provider.id,- rating = entry.rating?.toFloatOrNull() ?: 0f,- year = entry.year,- genre = entry.genre,- isAdult = isAdult- )- )- movieCount++- if (movieBatch.size >= batchSize) {- flushMovieBatch(provider.id, sessionId, movieBatch)- }- } else {- if (!includeLive) {- return@parseStreaming- }- val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }- val stableStreamId = stableId(- providerId = provider.id,- contentType = ContentType.LIVE,- tvgId = entry.tvgId,- url = entry.url,- title = entry.name,- groupTitle = groupTitle,- hasher = stableLongHasher- )- if (seenLiveStreamIds?.add(stableStreamId) != true) {- return@parseStreaming- }- val categoryId = liveCategories.idFor(groupTitle)- val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)- channelBatch.add(- ChannelEntity(- streamId = stableStreamId,- name = entry.name,- logoUrl = safeLogoUrl,- groupTitle = groupTitle,- categoryId = categoryId,- categoryName = groupTitle,- epgChannelId = entry.tvgId ?: entry.tvgName,- number = entry.tvgChno ?: 0,- streamUrl = entry.url,- catchUpSupported = !entry.catchUp.isNullOrBlank() ||- !entry.catchUpSource.isNullOrBlank() ||- !entry.timeshift.isNullOrBlank(),- catchUpDays = entry.catchUpDays ?: 0,- catchUpSource = safeCatchUpSource,- providerId = provider.id,- isAdult = isAdult- )- )- liveCount++- if (channelBatch.size >= batchSize) {- flushChannelBatch(provider.id, sessionId, channelBatch)- }- }- }- }- }-- flushChannelBatch(provider.id, sessionId, channelBatch)- flushMovieBatch(provider.id, sessionId, movieBatch)- syncCatalogStore.finalizeStagedImport(- providerId = provider.id,- sessionId = sessionId,- liveCategories = if (includeLive) liveCategories.entities() else null,- movieCategories = if (includeMovies) movieCategories.entities() else null,- includeLive = includeLive,- includeMovies = includeMovies- )- } finally {- syncCatalogStore.discardStagedImport(provider.id, sessionId)- }-- if (insecureStreamCount > 0) {- warnings += "Ignored $insecureStreamCount insecure playlist stream URL(s)."- }-- return M3uImportStats(- header = header,- liveCount = liveCount,- movieCount = movieCount,- warnings = warnings- )- }-- private suspend fun openPlaylistStream(- provider: Provider,- block: suspend (StreamedPlaylist) -> Unit- ) {- val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }- if (urlStr.startsWith("file:")) {- java.io.File(java.net.URI(urlStr)).inputStream().use { input ->- block(StreamedPlaylist(inputStream = input, sourceName = urlStr))- }- return- }-- retryTransient {- okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->- ensureSuccessfulPlaylistResponse(response)- val body = response.body ?: throw IllegalStateException("Empty M3U response")- body.byteStream().use { input ->- block(- StreamedPlaylist(- inputStream = input,- contentEncoding = response.header("Content-Encoding"),- sourceName = urlStr- )- )- }- }- }- }-- private fun ensureSuccessfulPlaylistResponse(response: Response) {- if (response.isSuccessful) {- return- }- if (response.code in 500..599 || response.code == 429) {- throw IOException("Transient HTTP ${response.code}")- }- throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")- }-- private fun maybeDecompressPlaylist(streamed: StreamedPlaylist): InputStream {- val buffered = if (streamed.inputStream is BufferedInputStream) {- streamed.inputStream- } else {- BufferedInputStream(streamed.inputStream, 64 * 1024)- }- buffered.mark(2)- val first = buffered.read()- val second = buffered.read()- buffered.reset()- val gzipMagic = first == 0x1f && second == 0x8b- val encodedGzip = streamed.contentEncoding?.contains("gzip", ignoreCase = true) == true- val namedGzip = streamed.sourceName?.lowercase()?.endsWith(".gz") == true- return if (gzipMagic || encodedGzip || namedGzip) {- GZIPInputStream(buffered, 64 * 1024)- } else {- buffered- }- }-- private suspend fun flushChannelBatch(providerId: Long, sessionId: Long, batch: MutableList<ChannelEntity>) {- if (batch.isEmpty()) {- return- }- syncCatalogStore.stageChannelBatch(providerId, sessionId, batch)- batch.clear()- }-- private suspend fun flushMovieBatch(providerId: Long, sessionId: Long, batch: MutableList<MovieEntity>) {- if (batch.isEmpty()) {- return- }- syncCatalogStore.stageMovieBatch(providerId, sessionId, batch)- batch.clear()- }-- private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {- return when (val attempt = attemptNonCancellation {- withMovieRequestTimeout("movie categories") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {- xtreamCatalogApiService.getVodCategories(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_vod_categories"- )- )- }- }- }- }) {- is Attempt.Success -> attempt.value- is Attempt.Failure -> {- Log.w(TAG, "Xtream VOD categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}")- null- }- }- }-- private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {- is CatalogStrategyResult.Success -> result.warnings- is CatalogStrategyResult.Partial -> result.warnings- is CatalogStrategyResult.Failure -> result.warnings- is CatalogStrategyResult.EmptyValid -> result.warnings- }-- private fun <T> shouldDowngradeCategorySync(- totalCategories: Int,- failures: Int,- fastFailures: Int,- outcomes: List<CategoryFetchOutcome<T>>- ): Boolean {- if (totalCategories <= 1) return false- val failureRatio = failures.toFloat() / totalCategories.toFloat()- val firstWindow = outcomes.take(minOf(4, outcomes.size))- val firstWindowFailures = firstWindow.count { outcome ->- outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- return failureRatio >= 0.75f ||- fastFailures >= minOf(3, totalCategories) ||- firstWindowFailures >= minOf(3, firstWindow.size)- }+ private fun <T> shouldDowngradeCategorySync(+ totalCategories: Int,+ failures: Int,+ fastFailures: Int,+ outcomes: List<CategoryFetchOutcome<T>>+ ): Boolean = catalogStrategySupport.shouldDowngradeCategorySync(totalCategories, failures, fastFailures, outcomes)private fun <T> shouldRetryFailedCategories(totalCategories: Int,failures: Int,downgradeRecommended: Boolean,outcomes: List<CategoryFetchOutcome<T>>- ): Boolean {- if (totalCategories <= 1 || failures == 0) {- return false- }- val stressFailures = outcomes.count { outcome ->- outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- return downgradeRecommended || stressFailures > 0 || failures <= minOf(2, totalCategories)- }+ ): Boolean = catalogStrategySupport.shouldRetryFailedCategories(totalCategories, failures, downgradeRecommended, outcomes)private fun <T> shouldRetryFailedPages(totalPages: Int,failures: Int,outcomes: List<PageFetchOutcome<T>>- ): Boolean {- if (totalPages <= 1 || failures == 0) {- return false- }- val stressFailures = outcomes.count { outcome ->- outcome is PageFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- return stressFailures > 0 || failures <= minOf(2, totalPages)- }+ ): Boolean = catalogStrategySupport.shouldRetryFailedPages(totalPages, failures, outcomes)private fun shouldRememberSequentialPreference(error: Throwable): Boolean {return xtreamAdaptiveSyncPolicy.isProviderStress(error) ||@@ -3307,15 +1441,6 @@ class SyncManager @Inject constructor((error is XtreamNetworkException && error.message.orEmpty().contains("reset", ignoreCase = true))}- private fun paginationParamsForPage(page: Int): Map<String, String> {- return mapOf(- "page" to page.toString(),- "limit" to XTREAM_CATALOG_PAGE_SIZE.toString(),- "offset" to ((page - 1) * XTREAM_CATALOG_PAGE_SIZE).toString(),- "items_per_page" to XTREAM_CATALOG_PAGE_SIZE.toString()- )- }-private fun updateSequentialProviderAdaptation(previousRemembered: Boolean,previousHealthyStreak: Int,@@ -3339,383 +1464,45 @@ class SyncManager @Inject constructor(previousAvoidFullUntil: Long,now: Long,feedback: XtreamStrategyFeedback- ): Long {- return when {- feedback.attemptedFullCatalog && feedback.fullCatalogUnsafe -> now + XTREAM_AVOID_FULL_CATALOG_COOLDOWN_MILLIS- feedback.attemptedFullCatalog -> 0L- feedback.preferredSegmentedFirst && feedback.segmentedStressDetected -> 0L- previousAvoidFullUntil <= now -> 0L- else -> previousAvoidFullUntil- }- }+ ): Long = catalogStrategySupport.updateAvoidFullUntil(previousAvoidFullUntil, now, feedback)private fun shouldPreferSegmentedLiveSync(metadata: SyncMetadata,now: Long- ): Boolean {- return metadata.liveAvoidFullUntil > now- }+ ): Boolean = catalogStrategySupport.shouldPreferSegmentedLiveSync(metadata, now)private fun shouldPreferSegmentedMovieSync(metadata: SyncMetadata,now: Long- ): Boolean {- return metadata.movieAvoidFullUntil > now- }+ ): Boolean = catalogStrategySupport.shouldPreferSegmentedMovieSync(metadata, now)private fun shouldPreferSegmentedSeriesSync(metadata: SyncMetadata,now: Long- ): Boolean {- return metadata.seriesAvoidFullUntil > now- }+ ): Boolean = catalogStrategySupport.shouldPreferSegmentedSeriesSync(metadata, now)- private fun shouldAvoidFullCatalogStrategy(error: Throwable): Boolean {- return when (error) {- is XtreamResponseTooLargeException,- is XtreamParsingException -> true- is java.net.SocketTimeoutException,- is java.io.InterruptedIOException -> true- is XtreamNetworkException ->- error.message.orEmpty().contains("timed out", ignoreCase = true)- is IllegalStateException -> {- val normalized = error.message.orEmpty().lowercase()- normalized.contains("oversized") ||- normalized.contains("safe in-memory budget") ||- normalized.contains("unreadable response") ||- normalized.contains("invalid catalog data")- }- else -> false- }- }+ private fun shouldAvoidFullCatalogStrategy(error: Throwable): Boolean =+ catalogStrategySupport.shouldAvoidFullCatalogStrategy(error)private fun sawSegmentedStress(warnings: List<String>,result: CatalogStrategyResult<*>,sequentialWarnings: Set<String>- ): Boolean {- val warningMatched = warnings.any { warning ->- sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }- }- val resultWarningMatched = strategyWarnings(result).any { warning ->- sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }- }- val failureMatched = (- (result as? CatalogStrategyResult.Failure)- ?.error- ?.let(::shouldRememberSequentialPreference)- ) == true- return warningMatched || resultWarningMatched || failureMatched- }-- private fun stableId(- providerId: Long,- contentType: ContentType,- tvgId: String?,- url: String,- title: String,- groupTitle: String?,- hasher: StableLongHasher- ): Long {- val normalizedUrl = normalizeUrlForIdentity(url)- val normalizedTvgId = tvgId?.trim()?.lowercase().orEmpty()- val normalizedTitle = normalizeTextForIdentity(title)- val normalizedGroup = normalizeTextForIdentity(groupTitle)- val identity = if (normalizedTvgId.isNotBlank()) {- "$providerId|${contentType.name}|tvg=$normalizedTvgId|url=$normalizedUrl"- } else {- "$providerId|${contentType.name}|url=$normalizedUrl|title=$normalizedTitle|group=$normalizedGroup"- }- return hasher.hash(identity)- }-- private fun normalizeUrlForIdentity(url: String): String {- val parsed = runCatching { URI(url) }.getOrNull()- val scheme = parsed?.scheme?.lowercase().orEmpty()- val host = parsed?.host?.lowercase().orEmpty()- val path = parsed?.path.orEmpty().trimEnd('/')- val query = parsed?.query- ?.split('&')- ?.mapNotNull { pair ->- val key = pair.substringBefore('=').lowercase()- val value = pair.substringAfter('=', "")- when (key) {- "token", "auth", "password", "username" -> null- else -> "$key=$value"- }- }- ?.sorted()- ?.joinToString("&")- .orEmpty()- return listOf(scheme, host, path, query)- .joinToString("|")- .ifBlank { url.trim().lowercase() }- }+ ): Boolean = catalogStrategySupport.sawSegmentedStress(warnings, result, sequentialWarnings)- private fun normalizeTextForIdentity(value: String?): String {- return value- .orEmpty()- .lowercase()- .replace(Regex("\\s+"), " ")- .trim()- }-- private fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> {- return buildFallbackCategories(- providerId = providerId,- type = ContentType.MOVIE,- items = movies,- categoryId = { movie -> movie.categoryId },- categoryName = { movie -> movie.categoryName },- isAdult = { movie -> movie.isAdult }- )- }-- private fun buildFallbackLiveCategories(providerId: Long, channels: List<Channel>): List<CategoryEntity> {- return buildFallbackCategories(- providerId = providerId,- type = ContentType.LIVE,- items = channels,- categoryId = { channel -> channel.categoryId },- categoryName = { channel -> channel.categoryName ?: channel.groupTitle },- isAdult = { channel -> channel.isAdult }- )- }-- private fun buildFallbackSeriesCategories(providerId: Long, series: List<Series>): List<CategoryEntity> {- return buildFallbackCategories(- providerId = providerId,- type = ContentType.SERIES,- items = series,- categoryId = { item -> item.categoryId },- categoryName = { item -> item.categoryName },- isAdult = { item -> item.isAdult }- )- }+ private fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> =+ catalogStrategySupport.buildFallbackMovieCategories(providerId, movies)- private fun <T> buildFallbackCategories(- providerId: Long,- type: ContentType,- items: List<T>,- categoryId: (T) -> Long?,- categoryName: (T) -> String?,- isAdult: (T) -> Boolean- ): List<CategoryEntity> {- val categories = LinkedHashMap<Long, CategoryEntity>()- items.forEach { item ->- val resolvedCategoryId = categoryId(item) ?: return@forEach- val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }- ?: "Category $resolvedCategoryId"- val candidate = CategoryEntity(- categoryId = resolvedCategoryId,- name = resolvedCategoryName,- parentId = 0,- type = type,- providerId = providerId,- isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)- )- val existing = categories[resolvedCategoryId]- categories[resolvedCategoryId] = if (existing == null) {- candidate- } else {- existing.copy(- name = preferredFallbackCategoryName(existing.name, candidate.name, resolvedCategoryId),- isAdult = existing.isAdult || candidate.isAdult,- isUserProtected = existing.isUserProtected || candidate.isUserProtected- )- }- }- return categories.values.toList()- }+ private fun buildFallbackLiveCategories(providerId: Long, channels: List<Channel>): List<CategoryEntity> =+ catalogStrategySupport.buildFallbackLiveCategories(providerId, channels)- private fun preferredFallbackCategoryName(- currentName: String,- candidateName: String,- categoryId: Long- ): String {- val placeholderName = "Category $categoryId"- return when {- currentName == placeholderName && candidateName != placeholderName -> candidateName- currentName != placeholderName -> currentName- else -> candidateName- }- }+ private fun buildFallbackSeriesCategories(providerId: Long, series: List<Series>): List<CategoryEntity> =+ catalogStrategySupport.buildFallbackSeriesCategories(providerId, series)private fun mergePreferredAndFallbackCategories(preferred: List<CategoryEntity>?,fallback: List<CategoryEntity>?- ): List<CategoryEntity>? {- if (preferred.isNullOrEmpty()) return fallback?.takeIf { it.isNotEmpty() }- if (fallback.isNullOrEmpty()) return preferred-- val merged = LinkedHashMap<Pair<Long, ContentType>, CategoryEntity>()- preferred.forEach { category ->- merged[category.categoryId to category.type] = category- }- fallback.forEach { category ->- val key = category.categoryId to category.type- val existing = merged[key]- merged[key] = if (existing == null) {- category- } else {- existing.copy(- isAdult = existing.isAdult || category.isAdult,- isUserProtected = existing.isUserProtected || category.isUserProtected,- name = existing.name.ifBlank { category.name }- )- }- }- return merged.values.toList()- }-- private suspend fun stageMovieItems(- providerId: Long,- items: List<Movie>,- seenStreamIds: MutableSet<Long>,- fallbackCollector: FallbackCategoryCollector,- sessionId: Long?- ): StagedCatalogSnapshot {- var resolvedSessionId = sessionId- val acceptedEntities = ArrayList<MovieEntity>(items.size)- items.forEach { movie ->- val streamId = movieKey(movie)- if (streamId <= 0L || !seenStreamIds.add(streamId)) {- return@forEach- }- fallbackCollector.record(movie.categoryId, movie.categoryName, movie.isAdult)- acceptedEntities += movie.toEntity()- }- if (acceptedEntities.isNotEmpty()) {- if (resolvedSessionId == null) {- syncCatalogStore.clearProviderStaging(providerId)- resolvedSessionId = syncCatalogStore.newSessionId()- }- syncCatalogStore.stageMovieBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)- }- return StagedCatalogSnapshot(- sessionId = resolvedSessionId,- acceptedCount = acceptedEntities.size,- fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }- )- }-- private suspend fun stageSeriesItems(- providerId: Long,- items: List<Series>,- seenSeriesIds: MutableSet<Long>,- fallbackCollector: FallbackCategoryCollector,- sessionId: Long?- ): StagedCatalogSnapshot {- var resolvedSessionId = sessionId- val acceptedEntities = ArrayList<SeriesEntity>(items.size)- items.forEach { item ->- val seriesId = seriesKey(item)- if (seriesId <= 0L || !seenSeriesIds.add(seriesId)) {- return@forEach- }- fallbackCollector.record(item.categoryId, item.categoryName, item.isAdult)- acceptedEntities += item.toEntity()- }- if (acceptedEntities.isNotEmpty()) {- if (resolvedSessionId == null) {- syncCatalogStore.clearProviderStaging(providerId)- resolvedSessionId = syncCatalogStore.newSessionId()- }- syncCatalogStore.stageSeriesBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)- }- return StagedCatalogSnapshot(- sessionId = resolvedSessionId,- acceptedCount = acceptedEntities.size,- fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }- )- }-- private suspend fun stageMovieSequence(- providerId: Long,- items: Sequence<Movie>,- seenStreamIds: MutableSet<Long>,- fallbackCollector: FallbackCategoryCollector,- sessionId: Long?- ): StagedCatalogSnapshot {- val batch = ArrayList<Movie>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)- var currentSessionId = sessionId- var acceptedCount = 0-- suspend fun flushBatch() {- if (batch.isEmpty()) return- val staged = stageMovieItems(- providerId = providerId,- items = batch,- seenStreamIds = seenStreamIds,- fallbackCollector = fallbackCollector,- sessionId = currentSessionId- )- currentSessionId = staged.sessionId- acceptedCount += staged.acceptedCount- batch.clear()- }-- items.forEach { movie ->- batch += movie- if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {- flushBatch()- }- }- flushBatch()-- return StagedCatalogSnapshot(- sessionId = currentSessionId,- acceptedCount = acceptedCount,- fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }- )- }-- private suspend fun stageSeriesSequence(- providerId: Long,- items: Sequence<Series>,- seenSeriesIds: MutableSet<Long>,- fallbackCollector: FallbackCategoryCollector,- sessionId: Long?- ): StagedCatalogSnapshot {- val batch = ArrayList<Series>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)- var currentSessionId = sessionId- var acceptedCount = 0-- suspend fun flushBatch() {- if (batch.isEmpty()) return- val staged = stageSeriesItems(- providerId = providerId,- items = batch,- seenSeriesIds = seenSeriesIds,- fallbackCollector = fallbackCollector,- sessionId = currentSessionId- )- currentSessionId = staged.sessionId- acceptedCount += staged.acceptedCount- batch.clear()- }-- items.forEach { series ->- batch += series- if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {- flushBatch()- }- }- flushBatch()-- return StagedCatalogSnapshot(- sessionId = currentSessionId,- acceptedCount = acceptedCount,- fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }- )- }-- private fun movieKey(movie: Movie): Long = movie.streamId.takeIf { it > 0L } ?: movie.id-- private fun seriesKey(item: Series): Long = item.seriesId.takeIf { it > 0L } ?: item.id-- /** Delegates to M3uParser to avoid duplicate logic. */- internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean = M3uParser.isVodEntry(entry)+ ): List<CategoryEntity>? = catalogStrategySupport.mergePreferredAndFallbackCategories(preferred, fallback)private suspend fun mergeVisibleLiveSyncWithHiddenStoredContent(providerId: Long,@@ -3812,89 +1599,15 @@ class SyncManager @Inject constructor(sequentialModeWarning: String,onProgress: ((String) -> Unit)?,fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>- ): CategoryExecutionPlan<T> {- if (categories.isEmpty()) {- return CategoryExecutionPlan(emptyList())- }-- val outcomes = mutableListOf<TimedCategoryOutcome<T>>()- val warnings = mutableListOf<String>()- var nextIndex = 0- var forceSequential = initialConcurrency <= 1- var consecutiveSequentialStressFailures = 0- var stoppedEarly = false-- while (nextIndex < categories.size && !stoppedEarly) {- val windowConcurrency = if (forceSequential) 1 else initialConcurrency- val window = categories.subList(nextIndex, minOf(nextIndex + windowConcurrency, categories.size))- val windowOutcomes = coroutineScope {- window.map { category ->- async { fetch(category) }- }.awaitAll()- }- outcomes += windowOutcomes- nextIndex += window.size-- val completed = outcomes.size- progress(provider.id, onProgress, "Downloading $sectionLabel by category $completed/${categories.size}...")-- if (!forceSequential && shouldRecoverRemainingCategoryRequests(categories.size, completed, outcomes.map { it.outcome })) {- forceSequential = true- warnings += sequentialModeWarning- Log.w(- TAG,- "Xtream $sectionLabel category sync is switching remaining categories to sequential mode for provider ${provider.id} after $completed/${categories.size} categories."- )- }-- if (forceSequential) {- windowOutcomes.forEach { timedOutcome ->- val isStressFailure = (timedOutcome.outcome as? CategoryFetchOutcome.Failure)- ?.error- ?.let(::shouldRememberSequentialPreference)- ?: false- consecutiveSequentialStressFailures = if (isStressFailure) {- consecutiveSequentialStressFailures + 1- } else {- 0- }- }- if (consecutiveSequentialStressFailures >= 3 && nextIndex < categories.size) {- warnings += "$sectionLabel $XTREAM_RECOVERY_ABORT_WARNING_SUFFIX"- Log.w(- TAG,- "Xtream $sectionLabel category sync stopped early for provider ${provider.id} after repeated sequential stress failures. completed=$completed total=${categories.size}"- )- stoppedEarly = true- }- }- }-- return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())- }-- private fun <T> shouldRecoverRemainingCategoryRequests(- totalCategories: Int,- processedCategories: Int,- outcomes: List<CategoryFetchOutcome<T>>- ): Boolean {- if (processedCategories >= totalCategories || processedCategories <= 1) {- return false- }- val processedOutcomes = outcomes.take(processedCategories)- val failures = processedOutcomes.count { it is CategoryFetchOutcome.Failure }- val stressFailures = processedOutcomes.count { outcome ->- outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- val recentWindow = processedOutcomes.takeLast(minOf(4, processedOutcomes.size))- val recentStressFailures = recentWindow.count { outcome ->- outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)- }- val failureRatio = failures.toFloat() / processedCategories.toFloat()- return recentStressFailures >= minOf(2, recentWindow.size) ||- stressFailures >= minOf(3, processedCategories) ||- (processedCategories >= 6 && failureRatio >= 0.34f)- }+ ): CategoryExecutionPlan<T> = xtreamSupport.executeCategoryRecoveryPlan(+ provider = provider,+ categories = categories,+ initialConcurrency = initialConcurrency,+ sectionLabel = sectionLabel,+ sequentialModeWarning = sequentialModeWarning,+ onProgress = onProgress,+ fetch = fetch+ )private fun <T> evaluatePageRecoveryPlan(provider: Provider,@@ -3902,177 +1615,45 @@ class SyncManager @Inject constructor(pageWindow: List<Int>,outcomes: List<TimedPageOutcome<T>>,sequentialModeWarning: String- ): PageExecutionPlan<T> {- if (pageWindow.isEmpty()) {- return PageExecutionPlan(emptyList())- }- val warnings = mutableListOf<String>()- val stressFailures = outcomes.count { outcome ->- (outcome.outcome as? PageFetchOutcome.Failure)- ?.error- ?.let(::shouldRememberSequentialPreference)- ?: false- }- val stoppedEarly = stressFailures >= minOf(3, pageWindow.size)- val shouldDegrade = !stoppedEarly && pageWindow.size > 1 && stressFailures >= minOf(2, pageWindow.size)- if (shouldDegrade) {- warnings += sequentialModeWarning- Log.w(- TAG,- "Xtream $sectionLabel paged sync is switching remaining pages to sequential mode for provider ${provider.id} after window ${pageWindow.first()}-${pageWindow.last()}."- )- }- if (stoppedEarly) {- warnings += "$sectionLabel $XTREAM_RECOVERY_ABORT_WARNING_SUFFIX"- Log.w(- TAG,- "Xtream $sectionLabel paged sync stopped early for provider ${provider.id} after repeated stress failures in window ${pageWindow.first()}-${pageWindow.last()}."- )- }- return PageExecutionPlan(outcomes = outcomes, warnings = warnings.distinct(), stoppedEarly = stoppedEarly)- }+ ): PageExecutionPlan<T> = xtreamSupport.evaluatePageRecoveryPlan(+ provider = provider,+ sectionLabel = sectionLabel,+ pageWindow = pageWindow,+ outcomes = outcomes,+ sequentialModeWarning = sequentialModeWarning+ )private suspend fun <T> retryTransient(maxAttempts: Int = 3,initialDelayMs: Long = 700L,block: suspend () -> T- ): T {- var attempt = 0- var delayMs = initialDelayMs- var lastError: Exception? = null-- while (attempt < maxAttempts) {- try {- return block()- } catch (e: CancellationException) {- throw e- } catch (t: Exception) {- lastError = t- attempt++- if (attempt >= maxAttempts || !isRetryable(t)) {- throw t- }- delay(delayMs)- delayMs *= 2- }- }-- throw lastError ?: IllegalStateException("Unknown sync retry failure")- }+ ): T = xtreamSupport.retryTransient(+ maxAttempts = maxAttempts,+ initialDelayMs = initialDelayMs,+ block = block+ )- private suspend fun <T> attemptNonCancellation(block: suspend () -> T): Attempt<T> {- return try {- Attempt.Success(block())- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- Attempt.Failure(e)- }- }+ private suspend fun <T> attemptNonCancellation(block: suspend () -> T): Attempt<T> =+ xtreamSupport.attemptNonCancellation(block)private suspend fun <T> executeXtreamRequest(providerId: Long,stage: XtreamAdaptiveSyncPolicy.Stage,block: suspend () -> T- ): T {- xtreamAdaptiveSyncPolicy.awaitTurn(providerId, stage)- return try {- val timeoutMs = xtreamAdaptiveSyncPolicy.timeoutFor(providerId, stage)- val result = if (timeoutMs != null) {- withTimeout(timeoutMs) {- block()- }- } else {- block()- }- xtreamAdaptiveSyncPolicy.recordSuccess(providerId)- result- } catch (e: CancellationException) {- throw e- } catch (e: Exception) {- xtreamAdaptiveSyncPolicy.recordFailure(providerId, e)- throw e- }- }+ ): T = xtreamSupport.executeXtreamRequest(providerId, stage, block)private suspend fun <T> withMovieRequestTimeout(requestLabel: String,block: suspend () -> T- ): T {- return try {- withTimeout(XTREAM_MOVIE_REQUEST_TIMEOUT_MILLIS) {- block()- }- } catch (e: TimeoutCancellationException) {- throw IOException("Timed out after 60 seconds while loading $requestLabel", e)- }- }+ ): T = xtreamSupport.withMovieRequestTimeout(requestLabel, block)private suspend fun <T> withSeriesRequestTimeout(requestLabel: String,block: suspend () -> T- ): T {- return try {- withTimeout(XTREAM_SERIES_REQUEST_TIMEOUT_MILLIS) {- block()- }- } catch (e: TimeoutCancellationException) {- throw IOException("Timed out after 60 seconds while loading $requestLabel", e)- }- }-- private suspend fun <T> retryXtreamCatalogTransient(providerId: Long, block: suspend () -> T): T {- var attempt = 0- var lastError: Exception? = null-- while (attempt < 3) {- try {- return block()- } catch (e: CancellationException) {- throw e- } catch (t: Exception) {- lastError = t- attempt++- if (attempt >= 3 || !isXtreamCatalogRetryable(t, attempt)) {- throw t- }- val delayMs = xtreamAdaptiveSyncPolicy.retryDelayFor(providerId, attempt)- val jitterMs = Random.nextLong(0L, (delayMs / 3L).coerceAtLeast(1L) + 1L)- delay(delayMs + jitterMs)- }- }-- throw lastError ?: IllegalStateException("Unknown Xtream catalog retry failure")- }+ ): T = xtreamSupport.withSeriesRequestTimeout(requestLabel, block)- private fun isRetryable(error: Throwable): Boolean {- if (error is XtreamAuthenticationException) return false- if (error is XtreamParsingException) return false- if (error is XtreamRequestException) return false- if (error is XtreamNetworkException) return true- if (error is IOException) return true-- val message = error.message.orEmpty().lowercase()- return message.contains("timeout") ||- message.contains("timed out") ||- message.contains("unable to resolve host") ||- message.contains("connection reset") ||- message.contains("connect") ||- message.contains("network")- }-- private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {- return when (error) {- is XtreamAuthenticationException -> false- is XtreamResponseTooLargeException -> false- is XtreamParsingException -> attempt == 1- is XtreamRequestException ->- error.statusCode in setOf(403, 408, 409, 429) || error.statusCode in 500..599- is XtreamNetworkException -> true- is IOException -> true- else -> isRetryable(error)- }- }+ private suspend fun <T> retryXtreamCatalogTransient(providerId: Long, block: suspend () -> T): T =+ xtreamSupport.retryXtreamCatalogTransient(providerId, block)companion object {private const val PROGRESS_INTERVAL = 5_000@@ -4098,321 +1679,47 @@ class SyncManager @Inject constructor(itemCount: Int?,error: Throwable?,nextStep: String- ) {- val reason = when {- error != null -> "${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}"- itemCount == 0 -> "empty result"- else -> "no usable data"- }- Log.w(- TAG,- "Xtream $section $stage failed for provider ${provider.id} after ${elapsedMs}ms ($reason). Switching to $nextStep."- )- }-- private fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {- return when (this) {- is com.streamvault.domain.model.Result.Success -> data- is com.streamvault.domain.model.Result.Error ->- throw exception ?: IllegalStateException("Failed to fetch $resourceName: $message")- is com.streamvault.domain.model.Result.Loading ->- throw Exception("Unexpected loading state for $resourceName")- }- }+ ) = xtreamSupport.logXtreamCatalogFallback(provider, section, stage, elapsedMs, itemCount, error, nextStep)private suspend fun fetchLiveCategoryOutcome(provider: Provider,api: XtreamProvider,category: XtreamCategory- ): TimedCategoryOutcome<Channel> {- var rawStreams: List<XtreamStream> = emptyList()- var categoryFailure: Throwable? = null- val elapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {- xtreamCatalogApiService.getLiveStreams(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_live_streams",- extraQueryParams = mapOf("category_id" to category.categoryId)- )- )- }- }- }) {- is Attempt.Success -> rawStreams = attempt.value- is Attempt.Failure -> categoryFailure = attempt.error- }- }- val outcome = when {- categoryFailure != null -> {- Log.w(TAG, "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")- CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)- }- rawStreams.isEmpty() -> {- Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")- CategoryFetchOutcome.Empty(category.categoryName)- }- else -> {- Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")- CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))- }- }- return TimedCategoryOutcome(category, outcome, elapsedMs)- }+ ): TimedCategoryOutcome<Channel> = xtreamFetcher.fetchLiveCategoryOutcome(provider, api, category)private suspend fun fetchMovieCategoryOutcome(provider: Provider,api: XtreamProvider,category: XtreamCategory- ): TimedCategoryOutcome<Movie> {- var rawStreams: List<XtreamStream> = emptyList()- var categoryFailure: Throwable? = null- val elapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withMovieRequestTimeout("movie category '${category.categoryName}'") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {- xtreamCatalogApiService.getVodStreams(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_vod_streams",- extraQueryParams = mapOf("category_id" to category.categoryId)- )- )- }- }- }- }) {- is Attempt.Success -> rawStreams = attempt.value- is Attempt.Failure -> categoryFailure = attempt.error- }- }- val outcome = when {- categoryFailure != null -> {- Log.w(TAG, "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")- CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)- }- rawStreams.isEmpty() -> {- Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")- CategoryFetchOutcome.Empty(category.categoryName)- }- else -> {- Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")- CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))- }- }- return TimedCategoryOutcome(category, outcome, elapsedMs)- }+ ): TimedCategoryOutcome<Movie> = xtreamFetcher.fetchMovieCategoryOutcome(provider, api, category)private suspend fun fetchSeriesCategoryOutcome(provider: Provider,api: XtreamProvider,category: XtreamCategory- ): TimedCategoryOutcome<Series> {- var rawSeries: List<XtreamSeriesItem> = emptyList()- var categoryFailure: Throwable? = null- val elapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withSeriesRequestTimeout("series category '${category.categoryName}'") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {- xtreamCatalogApiService.getSeriesList(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_series",- extraQueryParams = mapOf("category_id" to category.categoryId)- )- )- }- }- }- }) {- is Attempt.Success -> rawSeries = attempt.value- is Attempt.Failure -> categoryFailure = attempt.error- }- }- val outcome = when {- categoryFailure != null -> {- Log.w(TAG, "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}")- CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)- }- rawSeries.isEmpty() -> {- Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")- CategoryFetchOutcome.Empty(category.categoryName)- }- else -> {- Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items.")- CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))- }- }- return TimedCategoryOutcome(category, outcome, elapsedMs)- }+ ): TimedCategoryOutcome<Series> = xtreamFetcher.fetchSeriesCategoryOutcome(provider, api, category)private suspend fun fetchMoviePageOutcome(provider: Provider,api: XtreamProvider,page: Int- ): TimedPageOutcome<Movie> {- var rawStreams: List<XtreamStream> = emptyList()- var pageFailure: Throwable? = null- val elapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withMovieRequestTimeout("movie page $page") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {- xtreamCatalogApiService.getVodStreams(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_vod_streams",- extraQueryParams = paginationParamsForPage(page)- )- )- }- }- }- }) {- is Attempt.Success -> rawStreams = attempt.value- is Attempt.Failure -> pageFailure = attempt.error- }- }- val outcome = when {- pageFailure != null -> {- Log.w(- TAG,- "Xtream paged movie request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"- )- PageFetchOutcome.Failure(page, pageFailure!!)- }- rawStreams.isEmpty() -> {- Log.i(- TAG,- "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."- )- PageFetchOutcome.Empty(page)- }- else -> {- Log.i(- TAG,- "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawStreams.size} raw items."- )- PageFetchOutcome.Success(api.mapVodStreamsResponse(rawStreams), rawStreams.size)- }- }- return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)- }+ ): TimedPageOutcome<Movie> = xtreamFetcher.fetchMoviePageOutcome(provider, api, page)private suspend fun fetchSeriesPageOutcome(provider: Provider,api: XtreamProvider,page: Int- ): TimedPageOutcome<Series> {- var rawSeries: List<XtreamSeriesItem> = emptyList()- var pageFailure: Throwable? = null- val elapsedMs = measureTimeMillis {- when (val attempt = attemptNonCancellation {- withSeriesRequestTimeout("series page $page") {- retryXtreamCatalogTransient(provider.id) {- executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {- xtreamCatalogApiService.getSeriesList(- XtreamUrlFactory.buildPlayerApiUrl(- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- action = "get_series",- extraQueryParams = paginationParamsForPage(page)- )- )- }- }- }- }) {- is Attempt.Success -> rawSeries = attempt.value- is Attempt.Failure -> pageFailure = attempt.error- }- }- val outcome = when {- pageFailure != null -> {- Log.w(- TAG,- "Xtream paged series request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"- )- PageFetchOutcome.Failure(page, pageFailure!!)- }- rawSeries.isEmpty() -> {- Log.i(- TAG,- "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."- )- PageFetchOutcome.Empty(page)- }- else -> {- Log.i(- TAG,- "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawSeries.size} raw items."- )- PageFetchOutcome.Success(api.mapSeriesListResponse(rawSeries), rawSeries.size)- }- }- return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)- }+ ): TimedPageOutcome<Series> = xtreamFetcher.fetchSeriesPageOutcome(provider, api, page)private suspend fun <T> continueFailedPageOutcomes(provider: Provider,timedOutcomes: List<TimedPageOutcome<T>>,fetchSequentially: suspend (Int) -> TimedPageOutcome<T>- ): List<TimedPageOutcome<T>> {- val failedPages = timedOutcomes- .filter { it.outcome is PageFetchOutcome.Failure }- .map { it.page }- if (failedPages.isEmpty()) {- return timedOutcomes- }- val replacements = LinkedHashMap<Int, TimedPageOutcome<T>>()- failedPages.forEach { page ->- replacements[page] = fetchSequentially(page)- }- return timedOutcomes.map { existing ->- replacements[existing.page] ?: existing- }.also {- Log.i(- TAG,- "Xtream continuation fallback kept ${timedOutcomes.size - failedPages.size} successful page results for provider ${provider.id} and retried only ${failedPages.size} failed pages."- )- }- }+ ): List<TimedPageOutcome<T>> = xtreamSupport.continueFailedPageOutcomes(provider, timedOutcomes, fetchSequentially)private suspend fun <T> continueFailedCategoryOutcomes(provider: Provider,timedOutcomes: List<TimedCategoryOutcome<T>>,fetchSequentially: suspend (XtreamCategory) -> TimedCategoryOutcome<T>- ): List<TimedCategoryOutcome<T>> {- val failedCategories = timedOutcomes- .filter { it.outcome is CategoryFetchOutcome.Failure }- .map { it.category }- if (failedCategories.isEmpty()) {- return timedOutcomes- }- val replacements = LinkedHashMap<String, TimedCategoryOutcome<T>>()- failedCategories.forEach { category ->- replacements[category.categoryId] = fetchSequentially(category)- }- return timedOutcomes.map { existing ->- replacements[existing.category.categoryId] ?: existing- }.also {- Log.i(- TAG,- "Xtream continuation fallback kept ${timedOutcomes.size - failedCategories.size} successful category results for provider ${provider.id} and retried only ${failedCategories.size} failed categories."- )- }- }+ ): List<TimedCategoryOutcome<T>> = xtreamSupport.continueFailedCategoryOutcomes(provider, timedOutcomes, fetchSequentially)}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStager.ktnew file mode 100644index 00000000..84b54aac--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStager.kt@@ -0,0 +1,158 @@+package com.streamvault.data.sync++import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Series++internal class SyncManagerCatalogStager(+ private val syncCatalogStore: SyncCatalogStore,+ private val fallbackStageBatchSize: Int+) {+ suspend fun stageMovieItems(+ providerId: Long,+ items: List<Movie>,+ seenStreamIds: MutableSet<Long>,+ fallbackCollector: FallbackCategoryCollector,+ sessionId: Long?+ ): StagedCatalogSnapshot {+ var resolvedSessionId = sessionId+ val acceptedEntities = ArrayList<MovieEntity>(items.size)+ items.forEach { movie ->+ val streamId = movieKey(movie)+ if (streamId <= 0L || !seenStreamIds.add(streamId)) {+ return@forEach+ }+ fallbackCollector.record(movie.categoryId, movie.categoryName, movie.isAdult)+ acceptedEntities += movie.toEntity()+ }+ if (acceptedEntities.isNotEmpty()) {+ if (resolvedSessionId == null) {+ syncCatalogStore.clearProviderStaging(providerId)+ resolvedSessionId = syncCatalogStore.newSessionId()+ }+ syncCatalogStore.stageMovieBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)+ }+ return StagedCatalogSnapshot(+ sessionId = resolvedSessionId,+ acceptedCount = acceptedEntities.size,+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }+ )+ }++ suspend fun stageSeriesItems(+ providerId: Long,+ items: List<Series>,+ seenSeriesIds: MutableSet<Long>,+ fallbackCollector: FallbackCategoryCollector,+ sessionId: Long?+ ): StagedCatalogSnapshot {+ var resolvedSessionId = sessionId+ val acceptedEntities = ArrayList<SeriesEntity>(items.size)+ items.forEach { item ->+ val seriesId = seriesKey(item)+ if (seriesId <= 0L || !seenSeriesIds.add(seriesId)) {+ return@forEach+ }+ fallbackCollector.record(item.categoryId, item.categoryName, item.isAdult)+ acceptedEntities += item.toEntity()+ }+ if (acceptedEntities.isNotEmpty()) {+ if (resolvedSessionId == null) {+ syncCatalogStore.clearProviderStaging(providerId)+ resolvedSessionId = syncCatalogStore.newSessionId()+ }+ syncCatalogStore.stageSeriesBatch(providerId, requireNotNull(resolvedSessionId), acceptedEntities)+ }+ return StagedCatalogSnapshot(+ sessionId = resolvedSessionId,+ acceptedCount = acceptedEntities.size,+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }+ )+ }++ suspend fun stageMovieSequence(+ providerId: Long,+ items: Sequence<Movie>,+ seenStreamIds: MutableSet<Long>,+ fallbackCollector: FallbackCategoryCollector,+ sessionId: Long?+ ): StagedCatalogSnapshot {+ val batch = ArrayList<Movie>(fallbackStageBatchSize)+ var currentSessionId = sessionId+ var acceptedCount = 0++ suspend fun flushBatch() {+ if (batch.isEmpty()) return+ val staged = stageMovieItems(+ providerId = providerId,+ items = batch,+ seenStreamIds = seenStreamIds,+ fallbackCollector = fallbackCollector,+ sessionId = currentSessionId+ )+ currentSessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ batch.clear()+ }++ items.forEach { movie ->+ batch += movie+ if (batch.size >= fallbackStageBatchSize) {+ flushBatch()+ }+ }+ flushBatch()++ return StagedCatalogSnapshot(+ sessionId = currentSessionId,+ acceptedCount = acceptedCount,+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }+ )+ }++ suspend fun stageSeriesSequence(+ providerId: Long,+ items: Sequence<Series>,+ seenSeriesIds: MutableSet<Long>,+ fallbackCollector: FallbackCategoryCollector,+ sessionId: Long?+ ): StagedCatalogSnapshot {+ val batch = ArrayList<Series>(fallbackStageBatchSize)+ var currentSessionId = sessionId+ var acceptedCount = 0++ suspend fun flushBatch() {+ if (batch.isEmpty()) return+ val staged = stageSeriesItems(+ providerId = providerId,+ items = batch,+ seenSeriesIds = seenSeriesIds,+ fallbackCollector = fallbackCollector,+ sessionId = currentSessionId+ )+ currentSessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ batch.clear()+ }++ items.forEach { series ->+ batch += series+ if (batch.size >= fallbackStageBatchSize) {+ flushBatch()+ }+ }+ flushBatch()++ return StagedCatalogSnapshot(+ sessionId = currentSessionId,+ acceptedCount = acceptedCount,+ fallbackCategories = fallbackCollector.entities().takeIf { it.isNotEmpty() }+ )+ }++ private fun movieKey(movie: Movie): Long = movie.streamId.takeIf { it > 0L } ?: movie.id++ private fun seriesKey(item: Series): Long = item.seriesId.takeIf { it > 0L } ?: item.id+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.ktnew file mode 100644index 00000000..1b2d012c--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerCatalogStrategySupport.kt@@ -0,0 +1,239 @@+package com.streamvault.data.sync++import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.util.AdultContentClassifier+import com.streamvault.data.remote.xtream.XtreamNetworkException+import com.streamvault.data.remote.xtream.XtreamParsingException+import com.streamvault.data.remote.xtream.XtreamResponseTooLargeException+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.SyncMetadata++internal class SyncManagerCatalogStrategySupport(+ private val shouldRememberSequentialPreference: (Throwable) -> Boolean,+ private val avoidFullCatalogCooldownMillis: Long+) {+ fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {+ is CatalogStrategyResult.Success -> result.warnings+ is CatalogStrategyResult.Partial -> result.warnings+ is CatalogStrategyResult.Failure -> result.warnings+ is CatalogStrategyResult.EmptyValid -> result.warnings+ }++ fun <T> shouldDowngradeCategorySync(+ totalCategories: Int,+ failures: Int,+ fastFailures: Int,+ outcomes: List<CategoryFetchOutcome<T>>+ ): Boolean {+ if (totalCategories <= 1) return false+ val failureRatio = failures.toFloat() / totalCategories.toFloat()+ val firstWindow = outcomes.take(minOf(4, outcomes.size))+ val firstWindowFailures = firstWindow.count { outcome ->+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)+ }+ return failureRatio >= 0.75f ||+ fastFailures >= minOf(3, totalCategories) ||+ firstWindowFailures >= minOf(3, firstWindow.size)+ }++ fun <T> shouldRetryFailedCategories(+ totalCategories: Int,+ failures: Int,+ downgradeRecommended: Boolean,+ outcomes: List<CategoryFetchOutcome<T>>+ ): Boolean {+ if (totalCategories <= 1 || failures == 0) {+ return false+ }+ val stressFailures = outcomes.count { outcome ->+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)+ }+ return downgradeRecommended || stressFailures > 0 || failures <= minOf(2, totalCategories)+ }++ fun <T> shouldRetryFailedPages(+ totalPages: Int,+ failures: Int,+ outcomes: List<PageFetchOutcome<T>>+ ): Boolean {+ if (totalPages <= 1 || failures == 0) {+ return false+ }+ val stressFailures = outcomes.count { outcome ->+ outcome is PageFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)+ }+ return stressFailures > 0 || failures <= minOf(2, totalPages)+ }++ fun updateAvoidFullUntil(+ previousAvoidFullUntil: Long,+ now: Long,+ feedback: XtreamStrategyFeedback+ ): Long {+ return when {+ feedback.attemptedFullCatalog && feedback.fullCatalogUnsafe -> now + avoidFullCatalogCooldownMillis+ feedback.attemptedFullCatalog -> 0L+ feedback.preferredSegmentedFirst && feedback.segmentedStressDetected -> 0L+ previousAvoidFullUntil <= now -> 0L+ else -> previousAvoidFullUntil+ }+ }++ fun shouldPreferSegmentedLiveSync(metadata: SyncMetadata, now: Long): Boolean =+ metadata.liveAvoidFullUntil > now++ fun shouldPreferSegmentedMovieSync(metadata: SyncMetadata, now: Long): Boolean =+ metadata.movieAvoidFullUntil > now++ fun shouldPreferSegmentedSeriesSync(metadata: SyncMetadata, now: Long): Boolean =+ metadata.seriesAvoidFullUntil > now++ fun shouldAvoidFullCatalogStrategy(error: Throwable): Boolean {+ return when (error) {+ is XtreamResponseTooLargeException,+ is XtreamParsingException -> true+ is java.net.SocketTimeoutException,+ is java.io.InterruptedIOException -> true+ is XtreamNetworkException ->+ error.message.orEmpty().contains("timed out", ignoreCase = true)+ is IllegalStateException -> {+ val normalized = error.message.orEmpty().lowercase()+ normalized.contains("oversized") ||+ normalized.contains("safe in-memory budget") ||+ normalized.contains("unreadable response") ||+ normalized.contains("invalid catalog data")+ }+ else -> false+ }+ }++ fun sawSegmentedStress(+ warnings: List<String>,+ result: CatalogStrategyResult<*>,+ sequentialWarnings: Set<String>+ ): Boolean {+ val warningMatched = warnings.any { warning ->+ sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }+ }+ val resultWarningMatched = strategyWarnings(result).any { warning ->+ sequentialWarnings.any { marker -> warning.contains(marker, ignoreCase = true) }+ }+ val failureMatched = (+ (result as? CatalogStrategyResult.Failure)+ ?.error+ ?.let(shouldRememberSequentialPreference)+ ) == true+ return warningMatched || resultWarningMatched || failureMatched+ }++ fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> {+ return buildFallbackCategories(+ providerId = providerId,+ type = ContentType.MOVIE,+ items = movies,+ categoryId = { movie -> movie.categoryId },+ categoryName = { movie -> movie.categoryName },+ isAdult = { movie -> movie.isAdult }+ )+ }++ fun buildFallbackLiveCategories(providerId: Long, channels: List<Channel>): List<CategoryEntity> {+ return buildFallbackCategories(+ providerId = providerId,+ type = ContentType.LIVE,+ items = channels,+ categoryId = { channel -> channel.categoryId },+ categoryName = { channel -> channel.categoryName ?: channel.groupTitle },+ isAdult = { channel -> channel.isAdult }+ )+ }++ fun buildFallbackSeriesCategories(providerId: Long, series: List<Series>): List<CategoryEntity> {+ return buildFallbackCategories(+ providerId = providerId,+ type = ContentType.SERIES,+ items = series,+ categoryId = { item -> item.categoryId },+ categoryName = { item -> item.categoryName },+ isAdult = { item -> item.isAdult }+ )+ }++ fun mergePreferredAndFallbackCategories(+ preferred: List<CategoryEntity>?,+ fallback: List<CategoryEntity>?+ ): List<CategoryEntity>? {+ if (preferred.isNullOrEmpty()) return fallback?.takeIf { it.isNotEmpty() }+ if (fallback.isNullOrEmpty()) return preferred++ val merged = LinkedHashMap<Pair<Long, ContentType>, CategoryEntity>()+ preferred.forEach { category ->+ merged[category.categoryId to category.type] = category+ }+ fallback.forEach { category ->+ val key = category.categoryId to category.type+ val existing = merged[key]+ merged[key] = if (existing == null) {+ category+ } else {+ existing.copy(+ isAdult = existing.isAdult || category.isAdult,+ isUserProtected = existing.isUserProtected || category.isUserProtected,+ name = existing.name.ifBlank { category.name }+ )+ }+ }+ return merged.values.toList()+ }++ private fun <T> buildFallbackCategories(+ providerId: Long,+ type: ContentType,+ items: List<T>,+ categoryId: (T) -> Long?,+ categoryName: (T) -> String?,+ isAdult: (T) -> Boolean+ ): List<CategoryEntity> {+ val categories = LinkedHashMap<Long, CategoryEntity>()+ items.forEach { item ->+ val resolvedCategoryId = categoryId(item) ?: return@forEach+ val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }+ ?: "Category $resolvedCategoryId"+ val candidate = CategoryEntity(+ categoryId = resolvedCategoryId,+ name = resolvedCategoryName,+ parentId = 0,+ type = type,+ providerId = providerId,+ isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)+ )+ val existing = categories[resolvedCategoryId]+ categories[resolvedCategoryId] = if (existing == null) {+ candidate+ } else {+ existing.copy(+ name = preferredFallbackCategoryName(existing.name, candidate.name, resolvedCategoryId),+ isAdult = existing.isAdult || candidate.isAdult,+ isUserProtected = existing.isUserProtected || candidate.isUserProtected+ )+ }+ }+ return categories.values.toList()+ }++ private fun preferredFallbackCategoryName(+ currentName: String,+ candidateName: String,+ categoryId: Long+ ): String {+ val placeholderName = "Category $categoryId"+ return when {+ currentName == placeholderName && candidateName != placeholderName -> candidateName+ currentName != placeholderName -> currentName+ else -> candidateName+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.ktnew file mode 100644index 00000000..f1ee0e75--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt@@ -0,0 +1,303 @@+package com.streamvault.data.sync++import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.parser.M3uParser+import com.streamvault.data.util.AdultContentClassifier+import com.streamvault.data.util.UrlSecurityPolicy+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Provider+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.Response+import java.io.BufferedInputStream+import java.io.IOException+import java.io.InputStream+import java.net.URI+import java.util.zip.GZIPInputStream++private const val M3U_PROGRESS_INTERVAL = 5_000++internal class SyncManagerM3uImporter(+ private val m3uParser: M3uParser,+ private val okHttpClient: OkHttpClient,+ private val syncCatalogStore: SyncCatalogStore,+ private val retryTransient: suspend (suspend () -> Unit) -> Unit,+ private val progress: (Long, ((String) -> Unit)?, String) -> Unit+) {+ suspend fun importPlaylist(+ provider: Provider,+ onProgress: ((String) -> Unit)?,+ includeLive: Boolean = true,+ includeMovies: Boolean = true,+ batchSize: Int = 1000+ ): M3uImportStats {+ UrlSecurityPolicy.validatePlaylistSourceUrl(provider.m3uUrl.ifBlank { provider.serverUrl })?.let { message ->+ throw IllegalStateException(message)+ }+ progress(provider.id, onProgress, "Downloading Playlist...")+ syncCatalogStore.clearProviderStaging(provider.id)+ val sessionId = syncCatalogStore.newSessionId()+ val stableLongHasher = StableLongHasher()+ val liveCategories = CategoryAccumulator(provider.id, ContentType.LIVE, stableLongHasher)+ val movieCategories = CategoryAccumulator(provider.id, ContentType.MOVIE, stableLongHasher)+ val channelBatch = ArrayList<ChannelEntity>(batchSize)+ val movieBatch = ArrayList<MovieEntity>(batchSize)+ val seenLiveStreamIds = if (includeLive) mutableSetOf<Long>() else null+ val seenMovieStreamIds = if (includeMovies) mutableSetOf<Long>() else null+ var header = M3uParser.M3uHeader()+ var liveCount = 0+ var movieCount = 0+ var parsedCount = 0+ var nextMilestone = M3U_PROGRESS_INTERVAL+ val warnings = mutableListOf<String>()+ var insecureStreamCount = 0++ try {+ openPlaylistStream(provider) { streamed ->+ progress(provider.id, onProgress, "Parsing Playlist...")+ maybeDecompressPlaylist(streamed).use { input ->+ m3uParser.parseStreaming(+ inputStream = input,+ onHeader = { parsedHeader ->+ val secureEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.isSecureRemoteUrl(it) }+ if (parsedHeader.tvgUrl != null && secureEpgUrl == null) {+ warnings += "Ignored insecure EPG URL from playlist header."+ }+ header = parsedHeader.copy(tvgUrl = secureEpgUrl)+ }+ ) { entry ->+ parsedCount+++ if (parsedCount >= nextMilestone) {+ progress(provider.id, onProgress, "Imported $parsedCount playlist entries...")+ nextMilestone += M3U_PROGRESS_INTERVAL+ }+ if (!UrlSecurityPolicy.isAllowedStreamEntryUrl(entry.url)) {+ insecureStreamCount+++ return@parseStreaming+ }++ val safeLogoUrl = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.tvgLogo)+ val safeCatchUpSource = UrlSecurityPolicy.sanitizeImportedAssetUrl(entry.catchUpSource)++ if (provider.m3uVodClassificationEnabled && M3uParser.isVodEntry(entry)) {+ if (!includeMovies) return@parseStreaming+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }+ val stableStreamId = stableId(+ providerId = provider.id,+ contentType = ContentType.MOVIE,+ tvgId = entry.tvgId,+ url = entry.url,+ title = entry.name,+ groupTitle = groupTitle,+ hasher = stableLongHasher+ )+ if (seenMovieStreamIds?.add(stableStreamId) != true) return@parseStreaming+ val categoryId = movieCategories.idFor(groupTitle)+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)+ movieBatch.add(+ MovieEntity(+ streamId = stableStreamId,+ name = entry.name,+ posterUrl = safeLogoUrl,+ categoryId = categoryId,+ categoryName = groupTitle,+ streamUrl = entry.url,+ providerId = provider.id,+ rating = entry.rating?.toFloatOrNull() ?: 0f,+ year = entry.year,+ genre = entry.genre,+ isAdult = isAdult+ )+ )+ movieCount+++ if (movieBatch.size >= batchSize) {+ flushMovieBatch(provider.id, sessionId, movieBatch)+ }+ } else {+ if (!includeLive) return@parseStreaming+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }+ val stableStreamId = stableId(+ providerId = provider.id,+ contentType = ContentType.LIVE,+ tvgId = entry.tvgId,+ url = entry.url,+ title = entry.name,+ groupTitle = groupTitle,+ hasher = stableLongHasher+ )+ if (seenLiveStreamIds?.add(stableStreamId) != true) return@parseStreaming+ val categoryId = liveCategories.idFor(groupTitle)+ val isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle)+ channelBatch.add(+ ChannelEntity(+ streamId = stableStreamId,+ name = entry.name,+ logoUrl = safeLogoUrl,+ groupTitle = groupTitle,+ categoryId = categoryId,+ categoryName = groupTitle,+ epgChannelId = entry.tvgId ?: entry.tvgName,+ number = entry.tvgChno ?: 0,+ streamUrl = entry.url,+ catchUpSupported = !entry.catchUp.isNullOrBlank() ||+ !entry.catchUpSource.isNullOrBlank() ||+ !entry.timeshift.isNullOrBlank(),+ catchUpDays = entry.catchUpDays ?: 0,+ catchUpSource = safeCatchUpSource,+ providerId = provider.id,+ isAdult = isAdult+ )+ )+ liveCount+++ if (channelBatch.size >= batchSize) {+ flushChannelBatch(provider.id, sessionId, channelBatch)+ }+ }+ }+ }+ }++ flushChannelBatch(provider.id, sessionId, channelBatch)+ flushMovieBatch(provider.id, sessionId, movieBatch)+ syncCatalogStore.finalizeStagedImport(+ providerId = provider.id,+ sessionId = sessionId,+ liveCategories = if (includeLive) liveCategories.entities() else null,+ movieCategories = if (includeMovies) movieCategories.entities() else null,+ includeLive = includeLive,+ includeMovies = includeMovies+ )+ } finally {+ syncCatalogStore.discardStagedImport(provider.id, sessionId)+ }++ if (insecureStreamCount > 0) {+ warnings += "Ignored $insecureStreamCount insecure playlist stream URL(s)."+ }++ return M3uImportStats(+ header = header,+ liveCount = liveCount,+ movieCount = movieCount,+ warnings = warnings+ )+ }++ private suspend fun openPlaylistStream(+ provider: Provider,+ block: suspend (StreamedPlaylist) -> Unit+ ) {+ val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }+ if (urlStr.startsWith("file:")) {+ java.io.File(java.net.URI(urlStr)).inputStream().use { input ->+ block(StreamedPlaylist(inputStream = input, sourceName = urlStr))+ }+ return+ }++ retryTransient {+ okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->+ ensureSuccessfulPlaylistResponse(response)+ val body = response.body ?: throw IllegalStateException("Empty M3U response")+ body.byteStream().use { input ->+ block(+ StreamedPlaylist(+ inputStream = input,+ contentEncoding = response.header("Content-Encoding"),+ sourceName = urlStr+ )+ )+ }+ }+ }+ }++ private fun ensureSuccessfulPlaylistResponse(response: Response) {+ if (response.isSuccessful) return+ if (response.code in 500..599 || response.code == 429) {+ throw IOException("Transient HTTP ${response.code}")+ }+ throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")+ }++ private fun maybeDecompressPlaylist(streamed: StreamedPlaylist): InputStream {+ val buffered = if (streamed.inputStream is BufferedInputStream) {+ streamed.inputStream+ } else {+ BufferedInputStream(streamed.inputStream, 64 * 1024)+ }+ buffered.mark(2)+ val first = buffered.read()+ val second = buffered.read()+ buffered.reset()+ val gzipMagic = first == 0x1f && second == 0x8b+ val encodedGzip = streamed.contentEncoding?.contains("gzip", ignoreCase = true) == true+ val namedGzip = streamed.sourceName?.lowercase()?.endsWith(".gz") == true+ return if (gzipMagic || encodedGzip || namedGzip) {+ GZIPInputStream(buffered, 64 * 1024)+ } else {+ buffered+ }+ }++ private suspend fun flushChannelBatch(providerId: Long, sessionId: Long, batch: MutableList<ChannelEntity>) {+ if (batch.isEmpty()) return+ syncCatalogStore.stageChannelBatch(providerId, sessionId, batch)+ batch.clear()+ }++ private suspend fun flushMovieBatch(providerId: Long, sessionId: Long, batch: MutableList<MovieEntity>) {+ if (batch.isEmpty()) return+ syncCatalogStore.stageMovieBatch(providerId, sessionId, batch)+ batch.clear()+ }++ private fun stableId(+ providerId: Long,+ contentType: ContentType,+ tvgId: String?,+ url: String,+ title: String,+ groupTitle: String?,+ hasher: StableLongHasher+ ): Long {+ val normalizedUrl = normalizeUrlForIdentity(url)+ val normalizedTvgId = tvgId?.trim()?.lowercase().orEmpty()+ val normalizedTitle = normalizeTextForIdentity(title)+ val normalizedGroup = normalizeTextForIdentity(groupTitle)+ val identity = if (normalizedTvgId.isNotBlank()) {+ "$providerId|${contentType.name}|tvg=$normalizedTvgId|url=$normalizedUrl"+ } else {+ "$providerId|${contentType.name}|url=$normalizedUrl|title=$normalizedTitle|group=$normalizedGroup"+ }+ return hasher.hash(identity)+ }++ private fun normalizeUrlForIdentity(url: String): String {+ val parsed = runCatching { URI(url) }.getOrNull()+ val scheme = parsed?.scheme?.lowercase().orEmpty()+ val host = parsed?.host?.lowercase().orEmpty()+ val path = parsed?.path.orEmpty().trimEnd('/')+ val query = parsed?.query+ ?.split('&')+ ?.mapNotNull { pair ->+ val key = pair.substringBefore('=').lowercase()+ val value = pair.substringAfter('=', "")+ when (key) {+ "token", "auth", "password", "username" -> null+ else -> "$key=$value"+ }+ }+ ?.sorted()+ ?.joinToString("&")+ .orEmpty()+ return listOf(scheme, host, path, query)+ .joinToString("|")+ .ifBlank { url.trim().lowercase() }+ }++ private fun normalizeTextForIdentity(value: String?): String {+ return value.orEmpty().lowercase().replace(Regex("\\s+"), " ").trim()+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.ktnew file mode 100644index 00000000..fee4a8bd--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt@@ -0,0 +1,234 @@+package com.streamvault.data.sync++import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.parser.M3uParser+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.util.AdultContentClassifier+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.VodSyncMode+import java.io.InputStream+import java.security.MessageDigest++internal data class SyncOutcome(+ val partial: Boolean = false,+ val warnings: List<String> = emptyList()+)++internal sealed interface CatalogStrategyResult<out T> {+ val strategyName: String++ data class Success<T>(+ override val strategyName: String,+ val items: List<T>,+ val warnings: List<String> = emptyList()+ ) : CatalogStrategyResult<T>++ data class Partial<T>(+ override val strategyName: String,+ val items: List<T>,+ val warnings: List<String>+ ) : CatalogStrategyResult<T>++ data class Failure(+ override val strategyName: String,+ val error: Throwable,+ val warnings: List<String> = emptyList()+ ) : CatalogStrategyResult<Nothing>++ data class EmptyValid(+ override val strategyName: String,+ val warnings: List<String> = emptyList()+ ) : CatalogStrategyResult<Nothing>+}++internal data class XtreamStrategyFeedback(+ val preferredSegmentedFirst: Boolean = false,+ val attemptedFullCatalog: Boolean = false,+ val fullCatalogUnsafe: Boolean = false,+ val segmentedStressDetected: Boolean = false+)++internal data class MovieCatalogSyncResult(+ val catalogResult: CatalogStrategyResult<Movie>,+ val categories: List<CategoryEntity>?,+ val syncMode: VodSyncMode,+ val warnings: List<String> = emptyList(),+ val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),+ val stagedSessionId: Long? = null,+ val stagedAcceptedCount: Int = 0+)++internal data class CatalogSyncPayload<T>(+ val catalogResult: CatalogStrategyResult<T>,+ val categories: List<CategoryEntity>?,+ val warnings: List<String> = emptyList(),+ val strategyFeedback: XtreamStrategyFeedback = XtreamStrategyFeedback(),+ val stagedSessionId: Long? = null,+ val stagedAcceptedCount: Int = 0+)++internal data class LiveCatalogSnapshot(+ val categories: List<CategoryEntity>?,+ val channels: List<ChannelEntity>+)++internal data class SequentialProviderAdaptation(+ val rememberSequential: Boolean,+ val healthyStreak: Int+)++internal sealed interface Attempt<out T> {+ data class Success<T>(val value: T) : Attempt<T>+ data class Failure(val error: Exception) : Attempt<Nothing>+}++internal sealed interface CategoryFetchOutcome<out T> {+ data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>+ data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>+ data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>+}++internal data class TimedCategoryOutcome<T>(+ val category: XtreamCategory,+ val outcome: CategoryFetchOutcome<T>,+ val elapsedMs: Long+)++internal sealed interface PageFetchOutcome<out T> {+ data class Success<T>(val items: List<T>, val rawCount: Int) : PageFetchOutcome<T>+ data class Empty(val page: Int) : PageFetchOutcome<Nothing>+ data class Failure(val page: Int, val error: Throwable) : PageFetchOutcome<Nothing>+}++internal data class TimedPageOutcome<T>(+ val page: Int,+ val outcome: PageFetchOutcome<T>,+ val elapsedMs: Long+)++internal data class CategoryExecutionPlan<T>(+ val outcomes: List<TimedCategoryOutcome<T>>,+ val warnings: List<String> = emptyList()+)++internal data class PageExecutionPlan<T>(+ val outcomes: List<TimedPageOutcome<T>>,+ val warnings: List<String> = emptyList(),+ val stoppedEarly: Boolean = false+)++internal data class M3uImportStats(+ val header: M3uParser.M3uHeader,+ val liveCount: Int,+ val movieCount: Int,+ val warnings: List<String> = emptyList()+)++internal data class StreamedPlaylist(+ val inputStream: InputStream,+ val contentEncoding: String? = null,+ val sourceName: String? = null+)++internal class FallbackCategoryCollector(+ private val providerId: Long,+ private val type: ContentType+) {+ private val categories = LinkedHashMap<Long, CategoryEntity>()++ fun record(categoryId: Long?, categoryName: String?, isAdult: Boolean) {+ val resolvedCategoryId = categoryId ?: return+ val resolvedCategoryName = categoryName?.trim().takeUnless { it.isNullOrEmpty() }+ ?: "Category $resolvedCategoryId"+ val candidate = CategoryEntity(+ categoryId = resolvedCategoryId,+ name = resolvedCategoryName,+ parentId = 0,+ type = type,+ providerId = providerId,+ isAdult = isAdult || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)+ )+ val existing = categories[resolvedCategoryId]+ categories[resolvedCategoryId] = if (existing == null) {+ candidate+ } else {+ existing.copy(+ name = preferredCategoryName(existing.name, candidate.name, resolvedCategoryId),+ isAdult = existing.isAdult || candidate.isAdult,+ isUserProtected = existing.isUserProtected || candidate.isUserProtected+ )+ }+ }++ fun entities(): List<CategoryEntity> = categories.values.toList()++ private fun preferredCategoryName(+ currentName: String,+ candidateName: String,+ categoryId: Long+ ): String {+ val placeholderName = "Category $categoryId"+ return when {+ currentName == placeholderName && candidateName != placeholderName -> candidateName+ currentName != placeholderName -> currentName+ else -> candidateName+ }+ }+}++internal data class StagedCatalogSnapshot(+ val sessionId: Long?,+ val acceptedCount: Int,+ val fallbackCategories: List<CategoryEntity>?+)++internal class StableLongHasher {+ private val digest = MessageDigest.getInstance("SHA-256")++ fun hash(input: String): Long {+ val bytes = digest.digest(input.toByteArray(Charsets.UTF_8))+ var result = 0L+ for (i in 0 until 8) {+ result = (result shl 8) or (bytes[i].toLong() and 0xFF)+ }+ return result and Long.MAX_VALUE+ }+}++internal class CategoryAccumulator(+ private val providerId: Long,+ private val type: ContentType,+ private val hasher: StableLongHasher+) {+ private val categoryIds = LinkedHashMap<String, Long>()+ val count: Int+ get() = categoryIds.size++ fun idFor(name: String): Long {+ return categoryIds.getOrPut(name) { stableId(providerId, type, name, hasher) }+ }++ fun entities(): List<CategoryEntity> {+ return categoryIds.map { (name, id) ->+ CategoryEntity(+ categoryId = id,+ name = name,+ parentId = 0,+ type = type,+ providerId = providerId,+ isAdult = AdultContentClassifier.isAdultCategoryName(name)+ )+ }+ }++ private fun stableId(+ providerId: Long,+ type: ContentType,+ name: String,+ hasher: StableLongHasher+ ): Long {+ return hasher.hash("$providerId/${type.name}/$name").coerceAtLeast(1L)+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.ktnew file mode 100644index 00000000..9a28143d--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamFetcher.kt@@ -0,0 +1,305 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.dto.XtreamSeriesItem+import com.streamvault.data.remote.dto.XtreamStream+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.Series+import kotlin.system.measureTimeMillis++private const val XTREAM_FETCHER_TAG = "SyncManager"++internal class SyncManagerXtreamFetcher(+ private val xtreamCatalogApiService: XtreamApiService,+ private val xtreamSupport: SyncManagerXtreamSupport,+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val pageSize: Int+) {+ suspend fun fetchLiveCategoryOutcome(+ provider: Provider,+ api: XtreamProvider,+ category: XtreamCategory+ ): TimedCategoryOutcome<Channel> {+ var rawStreams: List<XtreamStream> = emptyList()+ var categoryFailure: Throwable? = null+ val elapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {+ xtreamCatalogApiService.getLiveStreams(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_live_streams",+ extraQueryParams = mapOf("category_id" to category.categoryId)+ )+ )+ }+ }+ }) {+ is Attempt.Success -> rawStreams = attempt.value+ is Attempt.Failure -> categoryFailure = attempt.error+ }+ }+ val outcome = when {+ categoryFailure != null -> {+ Log.w(+ XTREAM_FETCHER_TAG,+ "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}"+ )+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)+ }+ rawStreams.isEmpty() -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result."+ )+ CategoryFetchOutcome.Empty(category.categoryName)+ }+ else -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items."+ )+ CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))+ }+ }+ return TimedCategoryOutcome(category, outcome, elapsedMs)+ }++ suspend fun fetchMovieCategoryOutcome(+ provider: Provider,+ api: XtreamProvider,+ category: XtreamCategory+ ): TimedCategoryOutcome<Movie> {+ var rawStreams: List<XtreamStream> = emptyList()+ var categoryFailure: Throwable? = null+ val elapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withMovieRequestTimeout("movie category '${category.categoryName}'") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {+ xtreamCatalogApiService.getVodStreams(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_vod_streams",+ extraQueryParams = mapOf("category_id" to category.categoryId)+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> rawStreams = attempt.value+ is Attempt.Failure -> categoryFailure = attempt.error+ }+ }+ val outcome = when {+ categoryFailure != null -> {+ Log.w(+ XTREAM_FETCHER_TAG,+ "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}"+ )+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)+ }+ rawStreams.isEmpty() -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result."+ )+ CategoryFetchOutcome.Empty(category.categoryName)+ }+ else -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items."+ )+ CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))+ }+ }+ return TimedCategoryOutcome(category, outcome, elapsedMs)+ }++ suspend fun fetchSeriesCategoryOutcome(+ provider: Provider,+ api: XtreamProvider,+ category: XtreamCategory+ ): TimedCategoryOutcome<Series> {+ var rawSeries: List<XtreamSeriesItem> = emptyList()+ var categoryFailure: Throwable? = null+ val elapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withSeriesRequestTimeout("series category '${category.categoryName}'") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.CATEGORY) {+ xtreamCatalogApiService.getSeriesList(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_series",+ extraQueryParams = mapOf("category_id" to category.categoryId)+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> rawSeries = attempt.value+ is Attempt.Failure -> categoryFailure = attempt.error+ }+ }+ val outcome = when {+ categoryFailure != null -> {+ Log.w(+ XTREAM_FETCHER_TAG,+ "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(categoryFailure)}"+ )+ CategoryFetchOutcome.Failure(category.categoryName, categoryFailure!!)+ }+ rawSeries.isEmpty() -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result."+ )+ CategoryFetchOutcome.Empty(category.categoryName)+ }+ else -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items."+ )+ CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))+ }+ }+ return TimedCategoryOutcome(category, outcome, elapsedMs)+ }++ suspend fun fetchMoviePageOutcome(+ provider: Provider,+ api: XtreamProvider,+ page: Int+ ): TimedPageOutcome<Movie> {+ var rawStreams: List<XtreamStream> = emptyList()+ var pageFailure: Throwable? = null+ val elapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withMovieRequestTimeout("movie page $page") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {+ xtreamCatalogApiService.getVodStreams(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_vod_streams",+ extraQueryParams = paginationParamsForPage(page)+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> rawStreams = attempt.value+ is Attempt.Failure -> pageFailure = attempt.error+ }+ }+ val outcome = when {+ pageFailure != null -> {+ Log.w(+ XTREAM_FETCHER_TAG,+ "Xtream paged movie request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"+ )+ PageFetchOutcome.Failure(page, pageFailure!!)+ }+ rawStreams.isEmpty() -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."+ )+ PageFetchOutcome.Empty(page)+ }+ else -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawStreams.size} raw items."+ )+ PageFetchOutcome.Success(api.mapVodStreamsResponse(rawStreams), rawStreams.size)+ }+ }+ return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)+ }++ suspend fun fetchSeriesPageOutcome(+ provider: Provider,+ api: XtreamProvider,+ page: Int+ ): TimedPageOutcome<Series> {+ var rawSeries: List<XtreamSeriesItem> = emptyList()+ var pageFailure: Throwable? = null+ val elapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withSeriesRequestTimeout("series page $page") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.PAGED) {+ xtreamCatalogApiService.getSeriesList(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_series",+ extraQueryParams = paginationParamsForPage(page)+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> rawSeries = attempt.value+ is Attempt.Failure -> pageFailure = attempt.error+ }+ }+ val outcome = when {+ pageFailure != null -> {+ Log.w(+ XTREAM_FETCHER_TAG,+ "Xtream paged series request failed for provider ${provider.id} on page $page after ${elapsedMs}ms: ${sanitizeThrowableMessage(pageFailure)}"+ )+ PageFetchOutcome.Failure(page, pageFailure!!)+ }+ rawSeries.isEmpty() -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with a valid empty result."+ )+ PageFetchOutcome.Empty(page)+ }+ else -> {+ Log.i(+ XTREAM_FETCHER_TAG,+ "Xtream paged series request for provider ${provider.id} page $page completed in ${elapsedMs}ms with ${rawSeries.size} raw items."+ )+ PageFetchOutcome.Success(api.mapSeriesListResponse(rawSeries), rawSeries.size)+ }+ }+ return TimedPageOutcome(page = page, outcome = outcome, elapsedMs = elapsedMs)+ }++ private fun paginationParamsForPage(page: Int): Map<String, String> {+ return mapOf(+ "page" to page.toString(),+ "limit" to pageSize.toString(),+ "offset" to ((page - 1) * pageSize).toString(),+ "items_per_page" to pageSize.toString()+ )+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktnew file mode 100644index 00000000..390938e3--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -0,0 +1,302 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.SyncMetadata+import kotlin.system.measureTimeMillis++private const val XTREAM_LIVE_STRATEGY_TAG = "SyncManager"++internal class SyncManagerXtreamLiveStrategy(+ private val xtreamCatalogApiService: XtreamApiService,+ private val xtreamAdaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,+ private val xtreamSupport: SyncManagerXtreamSupport,+ private val xtreamFetcher: SyncManagerXtreamFetcher,+ private val catalogStrategySupport: SyncManagerCatalogStrategySupport,+ private val progress: (Long, ((String) -> Unit)?, String) -> Unit,+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val fullCatalogFallbackWarning: (String, Throwable?) -> String,+ private val categoryFailureWarning: (String, String, Throwable) -> String,+ private val liveCategorySequentialModeWarning: String+) {+ suspend fun syncXtreamLiveCatalog(+ provider: Provider,+ api: XtreamProvider,+ existingMetadata: SyncMetadata,+ hiddenLiveCategoryIds: Set<Long>,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Channel> {+ Log.i(XTREAM_LIVE_STRATEGY_TAG, "Xtream live strategy start for provider ${provider.id}.")+ val rawLiveCategories = when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {+ xtreamCatalogApiService.getLiveCategories(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_live_categories"+ )+ )+ }+ }+ }) {+ is Attempt.Success -> attempt.value+ is Attempt.Failure -> {+ Log.w(+ XTREAM_LIVE_STRATEGY_TAG,+ "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}"+ )+ null+ }+ }+ val resolvedCategories = rawLiveCategories+ ?.let { categories -> api.mapCategories(ContentType.LIVE, categories) }+ ?.map { category -> category.toEntity(provider.id) }+ ?.takeIf { it.isNotEmpty() }+ val filteredRawLiveCategories = rawLiveCategories.orEmpty().filterNot { category ->+ category.categoryId.toLongOrNull() in hiddenLiveCategoryIds+ }+ val visibleResolvedCategories = resolvedCategories+ ?.filterNot { category -> category.categoryId in hiddenLiveCategoryIds }+ ?.takeIf { it.isNotEmpty() }++ var fullResult: CatalogStrategyResult<Channel> = CatalogStrategyResult.EmptyValid("full")+ if (hiddenLiveCategoryIds.isEmpty()) {+ progress(provider.id, onProgress, "Downloading Live TV...")+ fullResult = loadXtreamLiveFull(provider, api)+ when (fullResult) {+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(+ catalogResult = fullResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(+ visibleResolvedCategories,+ catalogStrategySupport.buildFallbackLiveCategories(provider.id, fullResult.items)+ ),+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ )+ )+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(+ catalogResult = fullResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(+ visibleResolvedCategories,+ catalogStrategySupport.buildFallbackLiveCategories(provider.id, fullResult.items)+ ),+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ )+ )+ else -> Unit+ }+ } else {+ Log.i(+ XTREAM_LIVE_STRATEGY_TAG,+ "Xtream live full catalog skipped for provider ${provider.id} because ${hiddenLiveCategoryIds.size} live categories are hidden."+ )+ }++ progress(provider.id, onProgress, "Downloading Live TV by category...")+ val categoryResult = loadXtreamLiveByCategory(+ provider = provider,+ api = api,+ rawCategories = filteredRawLiveCategories,+ onProgress = onProgress,+ preferSequential = existingMetadata.liveSequentialFailuresRemembered+ )+ return CatalogSyncPayload(+ catalogResult = categoryResult,+ categories = when (categoryResult) {+ is CatalogStrategyResult.Success -> catalogStrategySupport.mergePreferredAndFallbackCategories(+ visibleResolvedCategories,+ catalogStrategySupport.buildFallbackLiveCategories(provider.id, categoryResult.items)+ )+ is CatalogStrategyResult.Partial -> catalogStrategySupport.mergePreferredAndFallbackCategories(+ visibleResolvedCategories,+ catalogStrategySupport.buildFallbackLiveCategories(provider.id, categoryResult.items)+ )+ else -> null+ },+ warnings = catalogStrategySupport.strategyWarnings(fullResult),+ strategyFeedback = XtreamStrategyFeedback(+ attemptedFullCatalog = true,+ fullCatalogUnsafe = (fullResult as? CatalogStrategyResult.Failure)?.error?.let(catalogStrategySupport::shouldAvoidFullCatalogStrategy) == true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = catalogStrategySupport.strategyWarnings(fullResult),+ result = categoryResult,+ sequentialWarnings = setOf(liveCategorySequentialModeWarning)+ )+ )+ )+ }++ suspend fun loadXtreamLiveFull(+ provider: Provider,+ api: XtreamProvider+ ): CatalogStrategyResult<Channel> {+ var fullChannels: List<Channel>? = null+ var fullChannelsFailure: Throwable? = null+ val fullChannelsElapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {+ api.getLiveStreams().getOrThrow("Live streams")+ }+ }+ }) {+ is Attempt.Success -> fullChannels = attempt.value+ is Attempt.Failure -> fullChannelsFailure = attempt.error+ }+ }+ if (!fullChannels.isNullOrEmpty()) {+ Log.i(+ XTREAM_LIVE_STRATEGY_TAG,+ "Xtream live full catalog succeeded for provider ${provider.id} in ${fullChannelsElapsedMs}ms with ${fullChannels!!.size} items."+ )+ return CatalogStrategyResult.Success("full", fullChannels!!)+ }+ return if (fullChannelsFailure != null) {+ xtreamSupport.logXtreamCatalogFallback(+ provider = provider,+ section = "live",+ stage = "full catalog",+ elapsedMs = fullChannelsElapsedMs,+ itemCount = fullChannels?.size,+ error = fullChannelsFailure,+ nextStep = "category-bulk"+ )+ CatalogStrategyResult.Failure(+ strategyName = "full",+ error = fullChannelsFailure!!,+ warnings = listOf(fullCatalogFallbackWarning("Live TV", fullChannelsFailure))+ )+ } else {+ xtreamSupport.logXtreamCatalogFallback(+ provider = provider,+ section = "live",+ stage = "full catalog",+ elapsedMs = fullChannelsElapsedMs,+ itemCount = fullChannels?.size,+ error = null,+ nextStep = "category-bulk"+ )+ CatalogStrategyResult.EmptyValid(+ strategyName = "full",+ warnings = listOf("Live full catalog returned an empty valid result.")+ )+ }+ }++ suspend fun loadXtreamLiveByCategory(+ provider: Provider,+ api: XtreamProvider,+ rawCategories: List<XtreamCategory>,+ onProgress: ((String) -> Unit)?,+ preferSequential: Boolean+ ): CatalogStrategyResult<Channel> {+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }+ if (categories.isEmpty()) {+ return CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("No live categories available"),+ warnings = listOf("Live category-bulk strategy was unavailable because no categories were returned.")+ )+ }++ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(+ providerId = provider.id,+ workloadSize = categories.size,+ preferSequential = preferSequential,+ stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY+ )+ progress(provider.id, onProgress, "Downloading Live TV by category 0/${categories.size}...")++ val executionPlan = xtreamSupport.executeCategoryRecoveryPlan(+ provider = provider,+ categories = categories,+ initialConcurrency = concurrency,+ sectionLabel = "Live TV",+ sequentialModeWarning = liveCategorySequentialModeWarning,+ onProgress = onProgress,+ fetch = { category -> xtreamFetcher.fetchLiveCategoryOutcome(provider, api, category) }+ )+ var timedOutcomes = executionPlan.outcomes++ val categoryOutcomes = timedOutcomes.map { it.outcome }+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }+ val fastFailureCount = timedOutcomes.count {+ it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure+ }+ val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(+ categories.size,+ failureCount,+ fastFailureCount,+ categoryOutcomes+ )+ var fallbackWarnings = executionPlan.warnings+ if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(+ categories.size,+ failureCount,+ downgradeRecommended,+ categoryOutcomes+ )+ ) {+ Log.w(+ XTREAM_LIVE_STRATEGY_TAG,+ "Xtream live category sync is continuing in sequential mode for failed categories on provider ${provider.id}."+ )+ timedOutcomes = xtreamSupport.continueFailedCategoryOutcomes(+ provider = provider,+ timedOutcomes = timedOutcomes,+ fetchSequentially = { category -> xtreamFetcher.fetchLiveCategoryOutcome(provider, api, category) }+ )+ fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(liveCategorySequentialModeWarning) else emptyList()).distinct()+ }++ val finalOutcomes = timedOutcomes.map { it.outcome }+ val warnings = finalOutcomes+ .filterIsInstance<CategoryFetchOutcome.Failure>()+ .map { failure -> categoryFailureWarning("Live TV", failure.categoryName, failure.error) } ++ fallbackWarnings++ val channels = finalOutcomes+ .asSequence()+ .filterIsInstance<CategoryFetchOutcome.Success<Channel>>()+ .flatMap { it.items.asSequence() }+ .filter { it.streamId > 0L }+ .associateBy { it.streamId }+ .values+ .toList()+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }+ Log.i(+ XTREAM_LIVE_STRATEGY_TAG,+ "Xtream live category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedChannels=${channels.size} concurrency=$concurrency"+ )++ return when {+ channels.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", channels, warnings.toList())+ channels.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", channels, warnings.toList())+ failedCategories > 0 -> CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("Live category-bulk sync failed for all usable categories"),+ warnings = warnings.toList()+ )+ else -> CatalogStrategyResult.EmptyValid(+ strategyName = "category_bulk",+ warnings = listOf("All live categories returned valid empty results.")+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.ktnew file mode 100644index 00000000..eaf07ba1--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamMovieStrategy.kt@@ -0,0 +1,764 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.dto.XtreamStream+import com.streamvault.data.remote.xtream.OkHttpXtreamApiService+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.SyncMetadata+import com.streamvault.domain.model.VodSyncMode+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlin.system.measureTimeMillis++private const val XTREAM_MOVIE_STRATEGY_TAG = "SyncManager"++internal class SyncManagerXtreamMovieStrategy(+ private val xtreamCatalogApiService: XtreamApiService,+ private val xtreamCatalogHttpService: OkHttpXtreamApiService,+ private val xtreamAdaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,+ private val xtreamSupport: SyncManagerXtreamSupport,+ private val xtreamFetcher: SyncManagerXtreamFetcher,+ private val catalogStrategySupport: SyncManagerCatalogStrategySupport,+ private val syncCatalogStore: SyncCatalogStore,+ private val progress: (Long, ((String) -> Unit)?, String) -> Unit,+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val fullCatalogFallbackWarning: (String, Throwable?) -> String,+ private val categoryFailureWarning: (String, String, Throwable) -> String,+ private val pagingFailureWarning: (String, Int, Throwable) -> String,+ private val stageMovieItems: suspend (Long, List<Movie>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,+ private val stageMovieSequence: suspend (Long, Sequence<Movie>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,+ private val movieCategorySequentialModeWarning: String,+ private val moviePagedSequentialModeWarning: String,+ private val fallbackStageBatchSize: Int,+ private val maxCatalogPages: Int,+ private val pageSize: Int+) {+ suspend fun syncXtreamMoviesCatalog(+ provider: Provider,+ api: XtreamProvider,+ existingMetadata: SyncMetadata,+ onProgress: ((String) -> Unit)?+ ): MovieCatalogSyncResult {+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy start for provider ${provider.id}. previousMode=${existingMetadata.movieSyncMode} rememberSequential=${existingMetadata.movieParallelFailuresRemembered}"+ )+ val rawVodCategories = fetchXtreamVodCategories(provider)+ val resolvedCategories = rawVodCategories+ ?.let { categories -> api.mapCategories(ContentType.MOVIE, categories) }+ ?.map { category -> category.toEntity(provider.id) }+ ?.takeIf { it.isNotEmpty() }++ var fullPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("full"),+ categories = null+ )+ var pagedPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("paged"),+ categories = null+ )+ var categoryPayload = CatalogSyncPayload<Movie>(+ catalogResult = CatalogStrategyResult.EmptyValid("category_bulk"),+ categories = null+ )++ if (provider.xtreamFastSyncEnabled) {+ return if (!resolvedCategories.isNullOrEmpty()) {+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies fast sync: returning LAZY_BY_CATEGORY for provider ${provider.id} with ${resolvedCategories.size} categories."+ )+ MovieCatalogSyncResult(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "fast_sync",+ error = IllegalStateException("Fast sync enabled; movies will hydrate on demand"),+ warnings = emptyList()+ ),+ categories = resolvedCategories,+ syncMode = VodSyncMode.LAZY_BY_CATEGORY,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ } else {+ Log.w(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies fast sync: no categories available for provider ${provider.id}, falling through to standard strategies."+ )+ MovieCatalogSyncResult(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "fast_sync_no_categories",+ error = IllegalStateException("Fast sync enabled but no categories available"),+ warnings = listOf("Fast sync enabled but no categories returned from server.")+ ),+ categories = null,+ syncMode = VodSyncMode.UNKNOWN,+ warnings = listOf("Fast sync enabled but no categories returned from server."),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ }+ }++ progress(provider.id, onProgress, "Checking Movies full catalog...")+ fullPayload = loadXtreamMoviesFull(provider, api)+ when (val fullResult = fullPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(+ catalogResult = fullResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),+ syncMode = VodSyncMode.FULL,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = false,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ ).also {+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items."+ )+ }+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(+ catalogResult = fullResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),+ syncMode = VodSyncMode.FULL,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = false,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ ).also {+ Log.w(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullPayload.stagedAcceptedCount} items."+ )+ }+ else -> Unit+ }++ if (!resolvedCategories.isNullOrEmpty()) {+ progress(provider.id, onProgress, "Preparing Movies category sync...")+ categoryPayload = loadXtreamMoviesByCategory(+ provider = provider,+ api = api,+ rawCategories = rawVodCategories.orEmpty(),+ onProgress = onProgress,+ preferSequential = existingMetadata.movieParallelFailuresRemembered+ )+ }+ when (val categoryResult = categoryPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return buildCategoryResult(+ provider = provider,+ resolvedCategories = resolvedCategories,+ categoryPayload = categoryPayload,+ fullPayload = fullPayload,+ pagedPayload = pagedPayload,+ categoryResult = categoryResult,+ partial = false+ )+ is CatalogStrategyResult.Partial -> return buildCategoryResult(+ provider = provider,+ resolvedCategories = resolvedCategories,+ categoryPayload = categoryPayload,+ fullPayload = fullPayload,+ pagedPayload = pagedPayload,+ categoryResult = categoryResult,+ partial = true+ )+ else -> Unit+ }++ if (resolvedCategories.isNullOrEmpty()) {+ progress(provider.id, onProgress, "Checking Movies paged catalog...")+ pagedPayload = loadXtreamMoviesByPage(provider, api, onProgress)+ when (val pagedResult = pagedPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return buildPagedResult(+ provider = provider,+ pagedPayload = pagedPayload,+ fullPayload = fullPayload,+ categoryPayload = categoryPayload,+ pagedResult = pagedResult,+ partial = false+ )+ is CatalogStrategyResult.Partial -> return buildPagedResult(+ provider = provider,+ pagedPayload = pagedPayload,+ fullPayload = fullPayload,+ categoryPayload = categoryPayload,+ pagedResult = pagedResult,+ partial = true+ )+ else -> Unit+ }+ }++ progress(provider.id, onProgress, "Checking Movies full catalog...")+ fullPayload = loadXtreamMoviesFull(provider, api)+ when (val fullResult = fullPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(+ catalogResult = fullResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, fullPayload.categories),+ syncMode = VodSyncMode.FULL,+ warnings = catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ ).also {+ val itemCount = fullPayload.stagedAcceptedCount.takeIf { it > 0 } ?: fullResult.items.size+ Log.i(XTREAM_MOVIE_STRATEGY_TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with $itemCount items.")+ }+ else -> Unit+ }++ val lazyWarnings = buildList {+ addAll(catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult))+ addAll(catalogStrategySupport.strategyWarnings(fullPayload.catalogResult))+ if (!resolvedCategories.isNullOrEmpty()) {+ add("Movies entered lazy category-only mode after category-bulk and full strategies failed.")+ } else {+ addAll(catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult))+ add("Movies entered lazy category-only mode after category-bulk, paged, and full strategies failed.")+ }+ }+ Log.w(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) VodSyncMode.LAZY_BY_CATEGORY else VodSyncMode.UNKNOWN}"+ )++ return if (!resolvedCategories.isNullOrEmpty()) {+ MovieCatalogSyncResult(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "lazy_by_category",+ error = IllegalStateException("Movie catalog strategies failed; exposing categories only"),+ warnings = lazyWarnings+ ),+ categories = resolvedCategories,+ syncMode = VodSyncMode.LAZY_BY_CATEGORY,+ warnings = lazyWarnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ segmentedStressDetected = true+ )+ )+ } else {+ MovieCatalogSyncResult(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "movies",+ error = IllegalStateException("Movie catalog strategies failed and no categories were available"),+ warnings = lazyWarnings+ ),+ categories = null,+ syncMode = VodSyncMode.UNKNOWN,+ warnings = lazyWarnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ segmentedStressDetected = true+ )+ )+ }+ }++ suspend fun loadXtreamMoviesFull(+ provider: Provider,+ api: XtreamProvider+ ): CatalogSyncPayload<Movie> {+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)+ val seenStreamIds = HashSet<Long>()+ val rawBatch = ArrayList<XtreamStream>(fallbackStageBatchSize)+ var stagedSessionId: Long? = null+ var acceptedCount = 0+ var streamedRawCount = 0+ var fullMoviesFailure: Throwable? = null++ suspend fun flushRawBatch() {+ if (rawBatch.isEmpty()) return+ val staged = stageMovieSequence(+ provider.id,+ api.mapVodStreamsSequence(rawBatch.asSequence()),+ seenStreamIds,+ fallbackCollector,+ stagedSessionId+ )+ stagedSessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ rawBatch.clear()+ }++ val fullMoviesElapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withMovieRequestTimeout("full movie catalog") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {+ xtreamCatalogHttpService.streamVodStreams(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_vod_streams"+ )+ ) { stream ->+ rawBatch += stream+ streamedRawCount+++ if (rawBatch.size >= fallbackStageBatchSize) {+ flushRawBatch()+ }+ }.also {+ flushRawBatch()+ }+ }+ }+ }+ }) {+ is Attempt.Success -> Unit+ is Attempt.Failure -> {+ fullMoviesFailure = attempt.error+ stagedSessionId?.let { sessionId ->+ syncCatalogStore.discardStagedImport(provider.id, sessionId)+ stagedSessionId = null+ }+ }+ }+ }+ if (streamedRawCount > 0) {+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."+ )+ if (acceptedCount == 0) {+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "full",+ warnings = listOf("Movies full catalog returned raw items but none were usable after mapping.")+ ),+ categories = null+ )+ }+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success(+ strategyName = "full",+ items = emptyList()+ ),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = stagedSessionId,+ stagedAcceptedCount = acceptedCount+ )+ }+ return if (fullMoviesFailure != null) {+ xtreamSupport.logXtreamCatalogFallback(+ provider = provider,+ section = "movies",+ stage = "full catalog",+ elapsedMs = fullMoviesElapsedMs,+ itemCount = streamedRawCount,+ error = fullMoviesFailure,+ nextStep = "category-bulk"+ )+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "full",+ error = fullMoviesFailure!!,+ warnings = listOf(fullCatalogFallbackWarning("Movies", fullMoviesFailure))+ ),+ categories = null+ )+ } else {+ xtreamSupport.logXtreamCatalogFallback(+ provider = provider,+ section = "movies",+ stage = "full catalog",+ elapsedMs = fullMoviesElapsedMs,+ itemCount = streamedRawCount,+ error = null,+ nextStep = "category-bulk"+ )+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "full",+ warnings = listOf("Movies full catalog returned an empty valid result.")+ ),+ categories = null+ )+ }+ }++ suspend fun loadXtreamMoviesByCategory(+ provider: Provider,+ api: XtreamProvider,+ rawCategories: List<XtreamCategory>,+ onProgress: ((String) -> Unit)?,+ preferSequential: Boolean+ ): CatalogSyncPayload<Movie> {+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }+ if (categories.isEmpty()) {+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("No VOD categories available"),+ warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")+ ),+ categories = null+ )+ }++ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(+ providerId = provider.id,+ workloadSize = categories.size,+ preferSequential = preferSequential,+ stage = XtreamAdaptiveSyncPolicy.Stage.CATEGORY+ )+ progress(provider.id, onProgress, "Downloading Movies by category 0/${categories.size}...")++ val executionPlan = xtreamSupport.executeCategoryRecoveryPlan(+ provider = provider,+ categories = categories,+ initialConcurrency = concurrency,+ sectionLabel = "Movies",+ sequentialModeWarning = movieCategorySequentialModeWarning,+ onProgress = onProgress,+ fetch = { category -> xtreamFetcher.fetchMovieCategoryOutcome(provider, api, category) }+ )+ var timedOutcomes = executionPlan.outcomes++ val categoryOutcomes = timedOutcomes.map { it.outcome }+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }+ val fastFailureCount = timedOutcomes.count { it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure }++ val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(+ totalCategories = categories.size,+ failures = failureCount,+ fastFailures = fastFailureCount,+ outcomes = categoryOutcomes+ )+ var fallbackWarnings = executionPlan.warnings+ if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(+ categories.size,+ failureCount,+ downgradeRecommended,+ categoryOutcomes+ )+ ) {+ Log.w(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movie category sync is continuing in sequential mode for failed categories on provider ${provider.id}."+ )+ timedOutcomes = xtreamSupport.continueFailedCategoryOutcomes(+ provider = provider,+ timedOutcomes = timedOutcomes,+ fetchSequentially = { category -> xtreamFetcher.fetchMovieCategoryOutcome(provider, api, category) }+ )+ fallbackWarnings = (+ fallbackWarnings ++ if (downgradeRecommended) listOf(movieCategorySequentialModeWarning) else emptyList()+ ).distinct()+ }++ val finalOutcomes = timedOutcomes.map { it.outcome }+ val warnings = finalOutcomes+ .filterIsInstance<CategoryFetchOutcome.Failure>()+ .map { failure -> categoryFailureWarning("Movies", failure.categoryName, failure.error) } ++ fallbackWarnings++ val seenStreamIds = HashSet<Long>()+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)+ var sessionId: Long? = null+ var acceptedCount = 0+ finalOutcomes+ .filterIsInstance<CategoryFetchOutcome.Success<Movie>>()+ .forEach { success ->+ val staged = stageMovieItems(provider.id, success.items, seenStreamIds, fallbackCollector, sessionId)+ sessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ }+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=$acceptedCount concurrency=$concurrency"+ )++ return when {+ acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ acceptedCount > 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Partial("category_bulk", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ failedCategories > 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),+ warnings = warnings.toList()+ ),+ categories = null+ )+ else -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "category_bulk",+ warnings = listOf("All movie categories returned valid empty results.")+ ),+ categories = null+ )+ }+ }++ suspend fun loadXtreamMoviesByPage(+ provider: Provider,+ api: XtreamProvider,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Movie> {+ val seenStreamIds = HashSet<Long>()+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.MOVIE)+ val warnings = mutableListOf<String>()+ var sessionId: Long? = null+ var acceptedCount = 0+ var nextPage = 1+ var stopPaging = false+ var forceSequential = false++ while (nextPage <= maxCatalogPages && !stopPaging) {+ val remainingPages = maxCatalogPages - nextPage + 1+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(+ providerId = provider.id,+ workloadSize = remainingPages,+ preferSequential = forceSequential,+ stage = XtreamAdaptiveSyncPolicy.Stage.PAGED+ )+ val pageWindow = (nextPage until (nextPage + concurrency))+ .takeWhile { it <= maxCatalogPages }+ progress(+ provider.id,+ onProgress,+ if (pageWindow.size == 1) {+ "Downloading Movies by page ${pageWindow.first()}..."+ } else {+ "Downloading Movies by page ${pageWindow.first()}-${pageWindow.last()}..."+ }+ )++ var timedOutcomes = coroutineScope {+ pageWindow.map { page ->+ async { xtreamFetcher.fetchMoviePageOutcome(provider, api, page) }+ }.awaitAll()+ }+ val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }+ val recoveryPlan = xtreamSupport.evaluatePageRecoveryPlan(+ provider = provider,+ sectionLabel = "Movies",+ pageWindow = pageWindow,+ outcomes = timedOutcomes,+ sequentialModeWarning = moviePagedSequentialModeWarning+ )+ forceSequential = forceSequential || recoveryPlan.warnings.any { it == moviePagedSequentialModeWarning }+ warnings += recoveryPlan.warnings+ if (recoveryPlan.stoppedEarly) {+ stopPaging = true+ }+ if (!recoveryPlan.stoppedEarly && concurrency > 1 &&+ catalogStrategySupport.shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })+ ) {+ timedOutcomes = xtreamSupport.continueFailedPageOutcomes(+ provider = provider,+ timedOutcomes = timedOutcomes,+ fetchSequentially = { page -> xtreamFetcher.fetchMoviePageOutcome(provider, api, page) }+ )+ }++ var terminalFailure: Throwable? = null+ var terminalFailurePage: Int? = null+ timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->+ when (val outcome = timedOutcome.outcome) {+ is PageFetchOutcome.Success -> {+ val staged = stageMovieItems(provider.id, outcome.items, seenStreamIds, fallbackCollector, sessionId)+ sessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ val newItems = staged.acceptedCount+ if (outcome.rawCount < pageSize || newItems == 0) {+ stopPaging = true+ }+ }+ is PageFetchOutcome.Empty -> {+ stopPaging = true+ }+ is PageFetchOutcome.Failure -> {+ warnings += pagingFailureWarning("Movies", outcome.page, outcome.error)+ if (terminalFailure == null) {+ terminalFailure = outcome.error+ terminalFailurePage = outcome.page+ }+ }+ }+ }++ if (terminalFailure != null) {+ return if (acceptedCount == 0) {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "paged",+ error = terminalFailure!!,+ warnings = listOf(pagingFailureWarning("Movies", terminalFailurePage ?: nextPage, terminalFailure!!))+ ),+ categories = null+ )+ } else {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Partial(+ strategyName = "paged",+ items = emptyList(),+ warnings = warnings.toList()+ ),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ }+ }++ nextPage = pageWindow.last() + 1+ }++ return if (acceptedCount > 0) {+ Log.i(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream paged movie strategy completed for provider ${provider.id} with $acceptedCount deduped items."+ )+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ } else {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "paged",+ warnings = listOf("Paged movie catalog completed without items.")+ ),+ categories = null+ )+ }+ }++ suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {+ return when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withMovieRequestTimeout("movie categories") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {+ xtreamCatalogApiService.getVodCategories(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_vod_categories"+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> attempt.value+ is Attempt.Failure -> {+ Log.w(+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream VOD categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}"+ )+ null+ }+ }+ }++ private fun buildCategoryResult(+ provider: Provider,+ resolvedCategories: List<CategoryEntity>?,+ categoryPayload: CatalogSyncPayload<Movie>,+ fullPayload: CatalogSyncPayload<Movie>,+ pagedPayload: CatalogSyncPayload<Movie>,+ categoryResult: CatalogStrategyResult<Movie>,+ partial: Boolean+ ): MovieCatalogSyncResult {+ val warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult)+ return MovieCatalogSyncResult(+ catalogResult = categoryResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),+ syncMode = VodSyncMode.CATEGORY_BULK,+ warnings = warnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = warnings,+ result = categoryResult,+ sequentialWarnings = setOf(movieCategorySequentialModeWarning, moviePagedSequentialModeWarning)+ )+ ),+ stagedSessionId = categoryPayload.stagedSessionId,+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount+ ).also {+ Log.println(+ if (partial) Log.WARN else Log.INFO,+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy selected CATEGORY_BULK${if (partial) "(partial)" else ""} for provider ${provider.id} with ${categoryPayload.stagedAcceptedCount} items."+ )+ }+ }++ private fun buildPagedResult(+ provider: Provider,+ pagedPayload: CatalogSyncPayload<Movie>,+ fullPayload: CatalogSyncPayload<Movie>,+ categoryPayload: CatalogSyncPayload<Movie>,+ pagedResult: CatalogStrategyResult<Movie>,+ partial: Boolean+ ): MovieCatalogSyncResult {+ val warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult)+ return MovieCatalogSyncResult(+ catalogResult = pagedResult,+ categories = pagedPayload.categories,+ syncMode = VodSyncMode.PAGED,+ warnings = warnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = warnings,+ result = pagedResult,+ sequentialWarnings = setOf(moviePagedSequentialModeWarning, movieCategorySequentialModeWarning)+ )+ ),+ stagedSessionId = pagedPayload.stagedSessionId,+ stagedAcceptedCount = pagedPayload.stagedAcceptedCount+ ).also {+ Log.println(+ if (partial) Log.WARN else Log.INFO,+ XTREAM_MOVIE_STRATEGY_TAG,+ "Xtream movies strategy selected PAGED${if (partial) "(partial)" else ""} for provider ${provider.id} with ${pagedPayload.stagedAcceptedCount} items."+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.ktnew file mode 100644index 00000000..1c8d544e--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSeriesStrategy.kt@@ -0,0 +1,536 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.mapper.toEntity+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.dto.XtreamSeriesItem+import com.streamvault.data.remote.xtream.OkHttpXtreamApiService+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.data.remote.xtream.XtreamUrlFactory+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.SyncMetadata+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlin.system.measureTimeMillis++private const val XTREAM_SERIES_STRATEGY_TAG = "SyncManager"++internal class SyncManagerXtreamSeriesStrategy(+ private val xtreamCatalogApiService: XtreamApiService,+ private val xtreamCatalogHttpService: OkHttpXtreamApiService,+ private val xtreamAdaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,+ private val xtreamSupport: SyncManagerXtreamSupport,+ private val xtreamFetcher: SyncManagerXtreamFetcher,+ private val catalogStrategySupport: SyncManagerCatalogStrategySupport,+ private val syncCatalogStore: SyncCatalogStore,+ private val progress: (Long, ((String) -> Unit)?, String) -> Unit,+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val fullCatalogFallbackWarning: (String, Throwable?) -> String,+ private val categoryFailureWarning: (String, String, Throwable) -> String,+ private val pagingFailureWarning: (String, Int, Throwable) -> String,+ private val stageSeriesItems: suspend (Long, List<Series>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,+ private val stageSeriesSequence: suspend (Long, Sequence<Series>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,+ private val categorySequentialModeWarning: String,+ private val pagedSequentialModeWarning: String,+ private val fallbackStageBatchSize: Int,+ private val maxCatalogPages: Int,+ private val pageSize: Int+) {+ suspend fun syncXtreamSeriesCatalog(+ provider: Provider,+ api: XtreamProvider,+ existingMetadata: SyncMetadata,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Series> {+ Log.i(XTREAM_SERIES_STRATEGY_TAG, "Xtream series strategy start for provider ${provider.id}.")+ val rawSeriesCategories = when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withSeriesRequestTimeout("series categories") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.LIGHTWEIGHT) {+ xtreamCatalogApiService.getSeriesCategories(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_series_categories"+ )+ )+ }+ }+ }+ }) {+ is Attempt.Success -> attempt.value+ is Attempt.Failure -> {+ Log.w(+ XTREAM_SERIES_STRATEGY_TAG,+ "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(attempt.error)}"+ )+ null+ }+ }+ val resolvedCategories = rawSeriesCategories+ ?.let { categories -> api.mapCategories(ContentType.SERIES, categories) }+ ?.map { category -> category.toEntity(provider.id) }+ ?.takeIf { it.isNotEmpty() }++ var fullPayload = CatalogSyncPayload<Series>(CatalogStrategyResult.EmptyValid("full"), null)+ var pagedPayload = CatalogSyncPayload<Series>(CatalogStrategyResult.EmptyValid("paged"), null)+ var categoryPayload = CatalogSyncPayload<Series>(CatalogStrategyResult.EmptyValid("category_bulk"), null)++ if (provider.xtreamFastSyncEnabled) {+ return if (!resolvedCategories.isNullOrEmpty()) {+ Log.i(+ XTREAM_SERIES_STRATEGY_TAG,+ "Xtream series fast sync: returning lazy_by_category for provider ${provider.id} with ${resolvedCategories.size} categories."+ )+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "lazy_by_category",+ error = IllegalStateException("Fast sync enabled; series will hydrate on demand"),+ warnings = emptyList()+ ),+ categories = resolvedCategories,+ warnings = emptyList(),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ } else {+ Log.w(XTREAM_SERIES_STRATEGY_TAG, "Xtream series fast sync: no categories available for provider ${provider.id}.")+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "fast_sync_no_categories",+ error = IllegalStateException("Fast sync enabled but no series categories available"),+ warnings = listOf("Fast sync enabled but no series categories returned from server.")+ ),+ categories = null,+ warnings = listOf("Fast sync enabled but no series categories returned from server."),+ strategyFeedback = XtreamStrategyFeedback(preferredSegmentedFirst = false)+ )+ }+ }++ if (!resolvedCategories.isNullOrEmpty()) {+ progress(provider.id, onProgress, "Preparing Series category sync...")+ categoryPayload = loadXtreamSeriesByCategory(+ provider,+ api,+ rawSeriesCategories.orEmpty(),+ onProgress,+ preferSequential = existingMetadata.seriesSequentialFailuresRemembered+ )+ when (val categoryResult = categoryPayload.catalogResult) {+ is CatalogStrategyResult.Success, is CatalogStrategyResult.Partial -> return CatalogSyncPayload(+ catalogResult = categoryResult,+ categories = catalogStrategySupport.mergePreferredAndFallbackCategories(resolvedCategories, categoryPayload.categories),+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult),+ result = categoryResult,+ sequentialWarnings = setOf(categorySequentialModeWarning)+ )+ ),+ stagedSessionId = categoryPayload.stagedSessionId,+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount+ )+ else -> Unit+ }+ }++ if (resolvedCategories.isNullOrEmpty()) {+ progress(provider.id, onProgress, "Checking Series paged catalog...")+ pagedPayload = loadXtreamSeriesByPage(provider, api, onProgress)+ when (val pagedResult = pagedPayload.catalogResult) {+ is CatalogStrategyResult.Success, is CatalogStrategyResult.Partial -> return CatalogSyncPayload(+ catalogResult = pagedResult,+ categories = pagedPayload.categories,+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult),+ result = pagedResult,+ sequentialWarnings = setOf(pagedSequentialModeWarning, categorySequentialModeWarning)+ )+ ),+ stagedSessionId = pagedPayload.stagedSessionId,+ stagedAcceptedCount = pagedPayload.stagedAcceptedCount+ )+ else -> Unit+ }++ progress(provider.id, onProgress, "Preparing Series category sync...")+ categoryPayload = loadXtreamSeriesByCategory(+ provider,+ api,+ rawSeriesCategories.orEmpty(),+ onProgress,+ preferSequential = existingMetadata.seriesSequentialFailuresRemembered+ )+ when (val categoryResult = categoryPayload.catalogResult) {+ is CatalogStrategyResult.Success, is CatalogStrategyResult.Partial -> return CatalogSyncPayload(+ catalogResult = categoryResult,+ categories = categoryPayload.categories,+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ segmentedStressDetected = catalogStrategySupport.sawSegmentedStress(+ warnings = catalogStrategySupport.strategyWarnings(fullPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),+ result = categoryResult,+ sequentialWarnings = setOf(categorySequentialModeWarning, pagedSequentialModeWarning)+ )+ ),+ stagedSessionId = categoryPayload.stagedSessionId,+ stagedAcceptedCount = categoryPayload.stagedAcceptedCount+ )+ else -> Unit+ }+ }++ progress(provider.id, onProgress, "Checking Series full catalog...")+ fullPayload = loadXtreamSeriesFull(provider, api)+ when (val fullResult = fullPayload.catalogResult) {+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(+ catalogResult = fullResult,+ categories = resolvedCategories ?: fullPayload.categories,+ warnings = catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult) ++ catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult),+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ fullCatalogUnsafe = false+ ),+ stagedSessionId = fullPayload.stagedSessionId,+ stagedAcceptedCount = fullPayload.stagedAcceptedCount+ )+ else -> Unit+ }++ val lazyWarnings = buildList {+ addAll(catalogStrategySupport.strategyWarnings(categoryPayload.catalogResult))+ addAll(catalogStrategySupport.strategyWarnings(fullPayload.catalogResult))+ if (!resolvedCategories.isNullOrEmpty()) {+ add("Series entered lazy category-only mode after category-bulk and full strategies failed.")+ } else {+ addAll(catalogStrategySupport.strategyWarnings(pagedPayload.catalogResult))+ add("Series entered lazy category-only mode after category-bulk, paged, and full strategies failed.")+ }+ }+ Log.w(+ XTREAM_SERIES_STRATEGY_TAG,+ "Xtream series strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) "lazy_by_category" else "unavailable"}"+ )+ return if (!resolvedCategories.isNullOrEmpty()) {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "lazy_by_category",+ error = IllegalStateException("Series catalog strategies failed; exposing categories only"),+ warnings = lazyWarnings+ ),+ categories = resolvedCategories,+ warnings = lazyWarnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ segmentedStressDetected = true+ )+ )+ } else {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "series",+ error = IllegalStateException("Series catalog strategies failed and no categories were available"),+ warnings = lazyWarnings+ ),+ categories = null,+ warnings = lazyWarnings,+ strategyFeedback = XtreamStrategyFeedback(+ preferredSegmentedFirst = true,+ attemptedFullCatalog = true,+ segmentedStressDetected = true+ )+ )+ }+ }++ suspend fun loadXtreamSeriesFull(provider: Provider, api: XtreamProvider): CatalogSyncPayload<Series> {+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)+ val seenSeriesIds = HashSet<Long>()+ val rawBatch = ArrayList<XtreamSeriesItem>(fallbackStageBatchSize)+ var stagedSessionId: Long? = null+ var acceptedCount = 0+ var streamedRawCount = 0+ var fullSeriesFailure: Throwable? = null++ suspend fun flushRawBatch() {+ if (rawBatch.isEmpty()) return+ val staged = stageSeriesSequence(provider.id, api.mapSeriesListSequence(rawBatch.asSequence()), seenSeriesIds, fallbackCollector, stagedSessionId)+ stagedSessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ rawBatch.clear()+ }++ val fullSeriesElapsedMs = measureTimeMillis {+ when (val attempt = xtreamSupport.attemptNonCancellation {+ xtreamSupport.withSeriesRequestTimeout("full series catalog") {+ xtreamSupport.retryXtreamCatalogTransient(provider.id) {+ xtreamSupport.executeXtreamRequest(provider.id, XtreamAdaptiveSyncPolicy.Stage.HEAVY) {+ xtreamCatalogHttpService.streamSeriesList(+ XtreamUrlFactory.buildPlayerApiUrl(+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ action = "get_series"+ )+ ) { item ->+ rawBatch += item+ streamedRawCount+++ if (rawBatch.size >= fallbackStageBatchSize) flushRawBatch()+ }.also { flushRawBatch() }+ }+ }+ }+ }) {+ is Attempt.Success -> Unit+ is Attempt.Failure -> {+ fullSeriesFailure = attempt.error+ stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }+ stagedSessionId = null+ }+ }+ }+ if (streamedRawCount > 0) {+ Log.i(+ XTREAM_SERIES_STRATEGY_TAG,+ "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with $acceptedCount accepted items from $streamedRawCount raw items."+ )+ if (acceptedCount == 0) {+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "full",+ warnings = listOf("Series full catalog returned raw items but none were usable after mapping.")+ ),+ categories = null+ )+ }+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success("full", emptyList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = stagedSessionId,+ stagedAcceptedCount = acceptedCount+ )+ }+ return if (fullSeriesFailure != null) {+ xtreamSupport.logXtreamCatalogFallback(provider, "series", "full catalog", fullSeriesElapsedMs, streamedRawCount, fullSeriesFailure, "category-bulk")+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "full",+ error = fullSeriesFailure!!,+ warnings = listOf(fullCatalogFallbackWarning("Series", fullSeriesFailure))+ ),+ categories = null+ )+ } else {+ xtreamSupport.logXtreamCatalogFallback(provider, "series", "full catalog", fullSeriesElapsedMs, streamedRawCount, null, "category-bulk")+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "full",+ warnings = listOf("Series full catalog returned an empty valid result.")+ ),+ categories = null+ )+ }+ }++ suspend fun loadXtreamSeriesByCategory(+ provider: Provider,+ api: XtreamProvider,+ rawCategories: List<XtreamCategory>,+ onProgress: ((String) -> Unit)?,+ preferSequential: Boolean+ ): CatalogSyncPayload<Series> {+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }+ if (categories.isEmpty()) {+ return CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("No series categories available"),+ warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")+ ),+ categories = null+ )+ }+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(provider.id, categories.size, preferSequential, XtreamAdaptiveSyncPolicy.Stage.CATEGORY)+ progress(provider.id, onProgress, "Downloading Series by category 0/${categories.size}...")+ val executionPlan = xtreamSupport.executeCategoryRecoveryPlan(+ provider = provider,+ categories = categories,+ initialConcurrency = concurrency,+ sectionLabel = "Series",+ sequentialModeWarning = categorySequentialModeWarning,+ onProgress = onProgress,+ fetch = { category -> xtreamFetcher.fetchSeriesCategoryOutcome(provider, api, category) }+ )+ var timedOutcomes = executionPlan.outcomes+ val categoryOutcomes = timedOutcomes.map { it.outcome }+ val failureCount = timedOutcomes.count { it.outcome is CategoryFetchOutcome.Failure }+ val fastFailureCount = timedOutcomes.count { it.elapsedMs <= 5_000L && it.outcome is CategoryFetchOutcome.Failure }+ val downgradeRecommended = catalogStrategySupport.shouldDowngradeCategorySync(categories.size, failureCount, fastFailureCount, categoryOutcomes)+ var fallbackWarnings = executionPlan.warnings+ if (concurrency > 1 && catalogStrategySupport.shouldRetryFailedCategories(categories.size, failureCount, downgradeRecommended, categoryOutcomes)) {+ Log.w(XTREAM_SERIES_STRATEGY_TAG, "Xtream series category sync is continuing in sequential mode for failed categories on provider ${provider.id}.")+ timedOutcomes = xtreamSupport.continueFailedCategoryOutcomes(+ provider = provider,+ timedOutcomes = timedOutcomes,+ fetchSequentially = { category -> xtreamFetcher.fetchSeriesCategoryOutcome(provider, api, category) }+ )+ fallbackWarnings = (fallbackWarnings + if (downgradeRecommended) listOf(categorySequentialModeWarning) else emptyList()).distinct()+ }+ val finalOutcomes = timedOutcomes.map { it.outcome }+ val warnings = finalOutcomes.filterIsInstance<CategoryFetchOutcome.Failure>()+ .map { failure -> categoryFailureWarning("Series", failure.categoryName, failure.error) } + fallbackWarnings++ val seenSeriesIds = HashSet<Long>()+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)+ var sessionId: Long? = null+ var acceptedCount = 0+ finalOutcomes.filterIsInstance<CategoryFetchOutcome.Success<Series>>().forEach { success ->+ val staged = stageSeriesItems(provider.id, success.items, seenSeriesIds, fallbackCollector, sessionId)+ sessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ }+ val failedCategories = finalOutcomes.count { it is CategoryFetchOutcome.Failure }+ val emptyCategories = finalOutcomes.count { it is CategoryFetchOutcome.Empty }+ val successfulCategories = finalOutcomes.count { it is CategoryFetchOutcome.Success }+ Log.i(+ XTREAM_SERIES_STRATEGY_TAG,+ "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=$acceptedCount concurrency=$concurrency"+ )+ return when {+ acceptedCount > 0 && failedCategories == 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success("category_bulk", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ acceptedCount > 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Partial("category_bulk", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ failedCategories > 0 -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "category_bulk",+ error = IllegalStateException("Series category-bulk sync failed for all usable categories"),+ warnings = warnings.toList()+ ),+ categories = null+ )+ else -> CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "category_bulk",+ warnings = listOf("All series categories returned valid empty results.")+ ),+ categories = null+ )+ }+ }++ suspend fun loadXtreamSeriesByPage(+ provider: Provider,+ api: XtreamProvider,+ onProgress: ((String) -> Unit)?+ ): CatalogSyncPayload<Series> {+ val seenSeriesIds = HashSet<Long>()+ val fallbackCollector = FallbackCategoryCollector(provider.id, ContentType.SERIES)+ val warnings = mutableListOf<String>()+ var sessionId: Long? = null+ var acceptedCount = 0+ var nextPage = 1+ var stopPaging = false+ var forceSequential = false+ while (nextPage <= maxCatalogPages && !stopPaging) {+ val remainingPages = maxCatalogPages - nextPage + 1+ val concurrency = xtreamAdaptiveSyncPolicy.concurrencyFor(provider.id, remainingPages, forceSequential, XtreamAdaptiveSyncPolicy.Stage.PAGED)+ val pageWindow = (nextPage until (nextPage + concurrency)).takeWhile { it <= maxCatalogPages }+ progress(provider.id, onProgress, if (pageWindow.size == 1) "Downloading Series by page ${pageWindow.first()}..." else "Downloading Series by page ${pageWindow.first()}-${pageWindow.last()}...")+ var timedOutcomes = coroutineScope { pageWindow.map { page -> async { xtreamFetcher.fetchSeriesPageOutcome(provider, api, page) } }.awaitAll() }+ val failures = timedOutcomes.count { it.outcome is PageFetchOutcome.Failure }+ val recoveryPlan = xtreamSupport.evaluatePageRecoveryPlan(provider, "Series", pageWindow, timedOutcomes, pagedSequentialModeWarning)+ forceSequential = forceSequential || recoveryPlan.warnings.any { it == pagedSequentialModeWarning }+ warnings += recoveryPlan.warnings+ if (recoveryPlan.stoppedEarly) stopPaging = true+ if (!recoveryPlan.stoppedEarly && concurrency > 1 && catalogStrategySupport.shouldRetryFailedPages(pageWindow.size, failures, timedOutcomes.map { it.outcome })) {+ timedOutcomes = xtreamSupport.continueFailedPageOutcomes(provider, timedOutcomes) { page ->+ xtreamFetcher.fetchSeriesPageOutcome(provider, api, page)+ }+ }+ var terminalFailure: Throwable? = null+ var terminalFailurePage: Int? = null+ timedOutcomes.sortedBy { it.page }.forEach { timedOutcome ->+ when (val outcome = timedOutcome.outcome) {+ is PageFetchOutcome.Success -> {+ val staged = stageSeriesItems(provider.id, outcome.items, seenSeriesIds, fallbackCollector, sessionId)+ sessionId = staged.sessionId+ acceptedCount += staged.acceptedCount+ if (outcome.rawCount < pageSize || staged.acceptedCount == 0) stopPaging = true+ }+ is PageFetchOutcome.Empty -> stopPaging = true+ is PageFetchOutcome.Failure -> {+ warnings += pagingFailureWarning("Series", outcome.page, outcome.error)+ if (terminalFailure == null) {+ terminalFailure = outcome.error+ terminalFailurePage = outcome.page+ }+ }+ }+ }+ if (terminalFailure != null) {+ return if (acceptedCount == 0) {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Failure(+ strategyName = "paged",+ error = terminalFailure!!,+ warnings = listOf(pagingFailureWarning("Series", terminalFailurePage ?: nextPage, terminalFailure!!))+ ),+ categories = null+ )+ } else {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Partial("paged", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ }+ }+ nextPage = pageWindow.last() + 1+ }+ return if (acceptedCount > 0) {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.Success("paged", emptyList(), warnings.toList()),+ categories = fallbackCollector.entities().takeIf { it.isNotEmpty() },+ stagedSessionId = sessionId,+ stagedAcceptedCount = acceptedCount+ )+ } else {+ CatalogSyncPayload(+ catalogResult = CatalogStrategyResult.EmptyValid(+ strategyName = "paged",+ warnings = listOf("Paged series catalog completed without items.")+ ),+ categories = null+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.ktnew file mode 100644index 00000000..1e23930a--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamSupport.kt@@ -0,0 +1,382 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.remote.dto.XtreamCategory+import com.streamvault.data.remote.xtream.XtreamAuthenticationException+import com.streamvault.data.remote.xtream.XtreamNetworkException+import com.streamvault.data.remote.xtream.XtreamParsingException+import com.streamvault.data.remote.xtream.XtreamRequestException+import com.streamvault.data.remote.xtream.XtreamResponseTooLargeException+import com.streamvault.domain.model.Provider+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.withTimeout+import java.io.IOException+import kotlin.random.Random++private const val XTREAM_SUPPORT_TAG = "SyncManager"++internal class SyncManagerXtreamSupport(+ private val adaptiveSyncPolicy: XtreamAdaptiveSyncPolicy,+ private val shouldRememberSequentialPreference: (Throwable) -> Boolean,+ private val sanitizeThrowableMessage: (Throwable?) -> String,+ private val progress: (Long, ((String) -> Unit)?, String) -> Unit,+ private val movieRequestTimeoutMillis: Long,+ private val seriesRequestTimeoutMillis: Long,+ private val recoveryAbortWarningSuffix: String+) {+ suspend fun <T> executeCategoryRecoveryPlan(+ provider: Provider,+ categories: List<XtreamCategory>,+ initialConcurrency: Int,+ sectionLabel: String,+ sequentialModeWarning: String,+ onProgress: ((String) -> Unit)?,+ fetch: suspend (XtreamCategory) -> TimedCategoryOutcome<T>+ ): CategoryExecutionPlan<T> {+ if (categories.isEmpty()) {+ return CategoryExecutionPlan(emptyList())+ }++ val outcomes = mutableListOf<TimedCategoryOutcome<T>>()+ val warnings = mutableListOf<String>()+ var nextIndex = 0+ var forceSequential = initialConcurrency <= 1+ var consecutiveSequentialStressFailures = 0+ var stoppedEarly = false++ while (nextIndex < categories.size && !stoppedEarly) {+ val windowConcurrency = if (forceSequential) 1 else initialConcurrency+ val window = categories.subList(nextIndex, minOf(nextIndex + windowConcurrency, categories.size))+ val windowOutcomes = coroutineScope {+ window.map { category ->+ async { fetch(category) }+ }.awaitAll()+ }+ outcomes += windowOutcomes+ nextIndex += window.size++ val completed = outcomes.size+ progress(provider.id, onProgress, "Downloading $sectionLabel by category $completed/${categories.size}...")++ if (!forceSequential && shouldRecoverRemainingCategoryRequests(categories.size, completed, outcomes.map { it.outcome })) {+ forceSequential = true+ warnings += sequentialModeWarning+ Log.w(+ XTREAM_SUPPORT_TAG,+ "Xtream $sectionLabel category sync is switching remaining categories to sequential mode for provider ${provider.id} after $completed/${categories.size} categories."+ )+ }++ if (forceSequential) {+ windowOutcomes.forEach { timedOutcome ->+ val isStressFailure = (timedOutcome.outcome as? CategoryFetchOutcome.Failure)+ ?.error+ ?.let(shouldRememberSequentialPreference)+ ?: false+ consecutiveSequentialStressFailures = if (isStressFailure) {+ consecutiveSequentialStressFailures + 1+ } else {+ 0+ }+ }+ if (consecutiveSequentialStressFailures >= 3 && nextIndex < categories.size) {+ warnings += "$sectionLabel $recoveryAbortWarningSuffix"+ Log.w(+ XTREAM_SUPPORT_TAG,+ "Xtream $sectionLabel category sync stopped early for provider ${provider.id} after repeated sequential stress failures. completed=$completed total=${categories.size}"+ )+ stoppedEarly = true+ }+ }+ }++ return CategoryExecutionPlan(outcomes = outcomes, warnings = warnings.distinct())+ }++ fun <T> evaluatePageRecoveryPlan(+ provider: Provider,+ sectionLabel: String,+ pageWindow: List<Int>,+ outcomes: List<TimedPageOutcome<T>>,+ sequentialModeWarning: String+ ): PageExecutionPlan<T> {+ if (pageWindow.isEmpty()) {+ return PageExecutionPlan(emptyList())+ }+ val warnings = mutableListOf<String>()+ val stressFailures = outcomes.count { outcome ->+ (outcome.outcome as? PageFetchOutcome.Failure)+ ?.error+ ?.let(shouldRememberSequentialPreference)+ ?: false+ }+ val stoppedEarly = stressFailures >= minOf(3, pageWindow.size)+ val shouldDegrade = !stoppedEarly && pageWindow.size > 1 && stressFailures >= minOf(2, pageWindow.size)+ if (shouldDegrade) {+ warnings += sequentialModeWarning+ Log.w(+ XTREAM_SUPPORT_TAG,+ "Xtream $sectionLabel paged sync is switching remaining pages to sequential mode for provider ${provider.id} after window ${pageWindow.first()}-${pageWindow.last()}."+ )+ }+ if (stoppedEarly) {+ warnings += "$sectionLabel $recoveryAbortWarningSuffix"+ Log.w(+ XTREAM_SUPPORT_TAG,+ "Xtream $sectionLabel paged sync stopped early for provider ${provider.id} after repeated stress failures in window ${pageWindow.first()}-${pageWindow.last()}."+ )+ }+ return PageExecutionPlan(outcomes = outcomes, warnings = warnings.distinct(), stoppedEarly = stoppedEarly)+ }++ suspend fun <T> retryTransient(+ maxAttempts: Int = 3,+ initialDelayMs: Long = 700L,+ block: suspend () -> T+ ): T {+ var attempt = 0+ var delayMs = initialDelayMs+ var lastError: Exception? = null++ while (attempt < maxAttempts) {+ try {+ return block()+ } catch (e: CancellationException) {+ throw e+ } catch (t: Exception) {+ lastError = t+ attempt+++ if (attempt >= maxAttempts || !isRetryable(t)) {+ throw t+ }+ delay(delayMs)+ delayMs *= 2+ }+ }++ throw lastError ?: IllegalStateException("Unknown sync retry failure")+ }++ suspend fun <T> attemptNonCancellation(block: suspend () -> T): Attempt<T> {+ return try {+ Attempt.Success(block())+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Attempt.Failure(e)+ }+ }++ suspend fun <T> executeXtreamRequest(+ providerId: Long,+ stage: XtreamAdaptiveSyncPolicy.Stage,+ block: suspend () -> T+ ): T {+ adaptiveSyncPolicy.awaitTurn(providerId, stage)+ return try {+ val timeoutMs = adaptiveSyncPolicy.timeoutFor(providerId, stage)+ val result = if (timeoutMs != null) {+ withTimeout(timeoutMs) {+ block()+ }+ } else {+ block()+ }+ adaptiveSyncPolicy.recordSuccess(providerId)+ result+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ adaptiveSyncPolicy.recordFailure(providerId, e)+ throw e+ }+ }++ suspend fun <T> withMovieRequestTimeout(+ requestLabel: String,+ block: suspend () -> T+ ): T {+ return withRequestTimeout(movieRequestTimeoutMillis, requestLabel, block)+ }++ suspend fun <T> withSeriesRequestTimeout(+ requestLabel: String,+ block: suspend () -> T+ ): T {+ return withRequestTimeout(seriesRequestTimeoutMillis, requestLabel, block)+ }++ suspend fun <T> retryXtreamCatalogTransient(providerId: Long, block: suspend () -> T): T {+ var attempt = 0+ var lastError: Exception? = null++ while (attempt < 3) {+ try {+ return block()+ } catch (e: CancellationException) {+ throw e+ } catch (t: Exception) {+ lastError = t+ attempt+++ if (attempt >= 3 || !isXtreamCatalogRetryable(t, attempt)) {+ throw t+ }+ val delayMs = adaptiveSyncPolicy.retryDelayFor(providerId, attempt)+ val jitterMs = Random.nextLong(0L, (delayMs / 3L).coerceAtLeast(1L) + 1L)+ delay(delayMs + jitterMs)+ }+ }++ throw lastError ?: IllegalStateException("Unknown Xtream catalog retry failure")+ }++ fun logXtreamCatalogFallback(+ provider: Provider,+ section: String,+ stage: String,+ elapsedMs: Long,+ itemCount: Int?,+ error: Throwable?,+ nextStep: String+ ) {+ val reason = when {+ error != null -> "${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}"+ itemCount == 0 -> "empty result"+ else -> "no usable data"+ }+ Log.w(+ XTREAM_SUPPORT_TAG,+ "Xtream $section $stage failed for provider ${provider.id} after ${elapsedMs}ms ($reason). Switching to $nextStep."+ )+ }++ suspend fun <T> continueFailedPageOutcomes(+ provider: Provider,+ timedOutcomes: List<TimedPageOutcome<T>>,+ fetchSequentially: suspend (Int) -> TimedPageOutcome<T>+ ): List<TimedPageOutcome<T>> {+ val failedPages = timedOutcomes+ .filter { it.outcome is PageFetchOutcome.Failure }+ .map { it.page }+ if (failedPages.isEmpty()) {+ return timedOutcomes+ }+ val replacements = LinkedHashMap<Int, TimedPageOutcome<T>>()+ failedPages.forEach { page ->+ replacements[page] = fetchSequentially(page)+ }+ return timedOutcomes.map { existing ->+ replacements[existing.page] ?: existing+ }.also {+ Log.i(+ XTREAM_SUPPORT_TAG,+ "Xtream continuation fallback kept ${timedOutcomes.size - failedPages.size} successful page results for provider ${provider.id} and retried only ${failedPages.size} failed pages."+ )+ }+ }++ suspend fun <T> continueFailedCategoryOutcomes(+ provider: Provider,+ timedOutcomes: List<TimedCategoryOutcome<T>>,+ fetchSequentially: suspend (XtreamCategory) -> TimedCategoryOutcome<T>+ ): List<TimedCategoryOutcome<T>> {+ val failedCategories = timedOutcomes+ .filter { it.outcome is CategoryFetchOutcome.Failure }+ .map { it.category }+ if (failedCategories.isEmpty()) {+ return timedOutcomes+ }+ val replacements = LinkedHashMap<String, TimedCategoryOutcome<T>>()+ failedCategories.forEach { category ->+ replacements[category.categoryId] = fetchSequentially(category)+ }+ return timedOutcomes.map { existing ->+ replacements[existing.category.categoryId] ?: existing+ }.also {+ Log.i(+ XTREAM_SUPPORT_TAG,+ "Xtream continuation fallback kept ${timedOutcomes.size - failedCategories.size} successful category results for provider ${provider.id} and retried only ${failedCategories.size} failed categories."+ )+ }+ }++ private fun <T> shouldRecoverRemainingCategoryRequests(+ totalCategories: Int,+ processedCategories: Int,+ outcomes: List<CategoryFetchOutcome<T>>+ ): Boolean {+ if (processedCategories >= totalCategories || processedCategories <= 1) {+ return false+ }+ val processedOutcomes = outcomes.take(processedCategories)+ val failures = processedOutcomes.count { it is CategoryFetchOutcome.Failure }+ val stressFailures = processedOutcomes.count { outcome ->+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)+ }+ val recentWindow = processedOutcomes.takeLast(minOf(4, processedOutcomes.size))+ val recentStressFailures = recentWindow.count { outcome ->+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)+ }+ val failureRatio = failures.toFloat() / processedCategories.toFloat()+ return recentStressFailures >= minOf(2, recentWindow.size) ||+ stressFailures >= minOf(3, processedCategories) ||+ (processedCategories >= 6 && failureRatio >= 0.34f)+ }++ private fun isRetryable(error: Throwable): Boolean {+ if (error is XtreamAuthenticationException) return false+ if (error is XtreamParsingException) return false+ if (error is XtreamRequestException) return false+ if (error is XtreamNetworkException) return true+ if (error is IOException) return true++ val message = error.message.orEmpty().lowercase()+ return message.contains("timeout") ||+ message.contains("timed out") ||+ message.contains("unable to resolve host") ||+ message.contains("connection reset") ||+ message.contains("connect") ||+ message.contains("network")+ }++ private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {+ return when (error) {+ is XtreamAuthenticationException -> false+ is XtreamResponseTooLargeException -> false+ is XtreamParsingException -> attempt == 1+ is XtreamRequestException ->+ error.statusCode in setOf(403, 408, 409, 429) || error.statusCode in 500..599+ is XtreamNetworkException -> true+ is IOException -> true+ else -> isRetryable(error)+ }+ }++ private suspend fun <T> withRequestTimeout(+ timeoutMillis: Long,+ requestLabel: String,+ block: suspend () -> T+ ): T {+ return try {+ withTimeout(timeoutMillis) {+ block()+ }+ } catch (e: kotlinx.coroutines.TimeoutCancellationException) {+ throw IOException("Timed out after 60 seconds while loading $requestLabel", e)+ }+ }+}++internal fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {+ return when (this) {+ is com.streamvault.domain.model.Result.Success -> data+ is com.streamvault.domain.model.Result.Error ->+ throw exception ?: IllegalStateException("Failed to fetch $resourceName: $message")+ is com.streamvault.domain.model.Result.Loading ->+ throw Exception("Unexpected loading state for $resourceName")+ }+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex f96e03f1..054bd99a 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -12,6 +12,10 @@ All notable product changes are recorded in this document.- Fixed in-app update downloads that could remain stuck on `Downloading...` by improving download tracking and completion handling.- Fixed M3U catch-up detection and replay URL expansion so archive-capable playlists using `catchup-source`, `timeshift`, and common replay placeholders are wired correctly.- Fixed catch-up and replay handling across M3U and Xtream providers with added regression coverage for archive metadata parsing and replay URL building.+- Fixed player startup stability so normal playback no longer eagerly creates split-screen state that could crash channel and episode opens before playback begins.+- Fixed shared player initialization to defer several constructor-time playback state subscriptions, reducing intermittent crashes when opening Live TV and series episodes.+- Fixed Xtream playback startup handling so provider-auth failures such as `401` and `403` are surfaced as player errors/notices instead of continuing into a broken playback open path.+- Fixed provider setup so Xtream-backed playlist URLs such as `get.php?...type=m3u` and `get.php?...type=m3u_plus` are recognized automatically and imported through the Xtream parser instead of the plain M3U path.## 1.0.3 - 09/04/2026diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.ktindex 1f726af1..a8ac692d 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt@@ -5,6 +5,9 @@ import com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.ProviderRepository+import java.net.URI+import java.net.URLDecoder+import java.nio.charset.StandardCharsetsimport javax.inject.Injectdata class XtreamProviderSetupCommand(@@ -72,14 +75,31 @@ class ValidateAndAddProvider @Inject constructor(name = command.name)) {- is Result.Success -> providerRepository.validateM3u(- url = validated.data.url,- name = validated.data.name,- epgSyncMode = command.epgSyncMode,- m3uVodClassificationEnabled = command.m3uVodClassificationEnabled,- onProgress = onProgress,- id = command.existingProviderId- ).toUseCaseResult()+ is Result.Success -> {+ val validatedInput = validated.data+ val parsedXtream = parseXtreamPlaylistUrl(validatedInput.url)+ if (parsedXtream != null) {+ providerRepository.loginXtream(+ serverUrl = parsedXtream.serverUrl,+ username = parsedXtream.username,+ password = parsedXtream.password,+ name = validatedInput.name,+ xtreamFastSyncEnabled = true,+ epgSyncMode = command.epgSyncMode,+ onProgress = onProgress,+ id = command.existingProviderId+ ).toUseCaseResult()+ } else {+ providerRepository.validateM3u(+ url = validatedInput.url,+ name = validatedInput.name,+ epgSyncMode = command.epgSyncMode,+ m3uVodClassificationEnabled = command.m3uVodClassificationEnabled,+ onProgress = onProgress,+ id = command.existingProviderId+ ).toUseCaseResult()+ }+ }is Result.Error -> ValidateAndAddProviderResult.ValidationError(validated.message)is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")@@ -91,4 +111,48 @@ class ValidateAndAddProvider @Inject constructor(is Result.Error -> ValidateAndAddProviderResult.Error(message, exception)is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")}++ private data class ParsedXtreamPlaylistUrl(+ val serverUrl: String,+ val username: String,+ val password: String+ )++ private fun parseXtreamPlaylistUrl(url: String): ParsedXtreamPlaylistUrl? {+ val uri = runCatching { URI(url) }.getOrNull() ?: return null+ val scheme = uri.scheme?.lowercase() ?: return null+ if (scheme != "http" && scheme != "https") return null++ val normalizedPath = uri.path.orEmpty().lowercase()+ if (!normalizedPath.endsWith("/get.php")) return null++ val query = parseQueryParameters(uri.rawQuery)+ val username = query["username"]?.takeIf { it.isNotBlank() } ?: return null+ val password = query["password"]?.takeIf { it.isNotBlank() } ?: return null+ val type = query["type"]?.lowercase()?.takeIf { it.isNotBlank() } ?: return null+ if (type != "m3u" && type != "m3u_plus") return null++ val authority = uri.rawAuthority?.takeIf { it.isNotBlank() } ?: return null+ return ParsedXtreamPlaylistUrl(+ serverUrl = "$scheme://$authority",+ username = username,+ password = password+ )+ }++ private fun parseQueryParameters(rawQuery: String?): Map<String, String> {+ if (rawQuery.isNullOrBlank()) return emptyMap()+ return rawQuery.split('&')+ .mapNotNull { part ->+ val key = part.substringBefore('=', "")+ .takeIf { it.isNotBlank() }+ ?: return@mapNotNull null+ val value = part.substringAfter('=', "")+ decodeQueryComponent(key) to decodeQueryComponent(value)+ }+ .toMap()+ }++ private fun decodeQueryComponent(value: String): String =+ URLDecoder.decode(value, StandardCharsets.UTF_8.name())}diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.ktindex 20c0bf41..4be183f9 100644--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt@@ -119,6 +119,45 @@ class ValidateAndAddProviderTest {))}++ @Test+ fun auto_converts_xtream_playlist_url_to_xtream_login() = runTest {+ val repository = FakeProviderRepository()+ val useCase = ValidateAndAddProvider(+ providerSetupInputValidator = FakeProviderSetupInputValidator(+ m3uResult = Result.success(+ ValidatedM3uProviderInput(+ url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ name = "Imported Playlist"+ )+ )+ ),+ providerRepository = repository+ )++ val result = useCase.addM3u(+ M3uProviderSetupCommand(+ url = "http://[email protected]:8080/get.php?username=Hakan1605&password=wg9daUwzfV&type=m3u_plus",+ name = "Imported Playlist",+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ existingProviderId = 19L+ )+ )++ assertThat(result).isInstanceOf(ValidateAndAddProviderResult.Success::class.java)+ assertThat(repository.lastM3uCall).isNull()+ assertThat(repository.lastXtreamCall).isEqualTo(+ XtreamCall(+ serverUrl = "http://[email protected]:8080",+ username = "Hakan1605",+ password = "wg9daUwzfV",+ name = "Imported Playlist",+ xtreamFastSyncEnabled = true,+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ id = 19L+ )+ )+ }}private class FakeProviderSetupInputValidator(