StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
chore: bump version to 1.0.5 (6)
David Nashash6990c01fdcc7
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 3dc2c79f..0b837d7d 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -48,8 +48,8 @@ android {applicationId = "com.streamvault.app"minSdk = 28targetSdk = 36- versionCode = 5- versionName = "1.0.4"+ versionCode = 6+ versionName = "1.0.5"testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"buildConfigField("String", "OFFICIAL_APPLICATION_ID", "\"com.streamvault.app\"")buildConfigField("String", "OFFICIAL_SIGNING_CERT_SHA256", "\"$officialSigningCertSha256\"")diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 4477eed2..41958128 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -75,7 +75,8 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_33_34,StreamVaultDatabase.MIGRATION_34_35,StreamVaultDatabase.MIGRATION_35_36,- StreamVaultDatabase.MIGRATION_36_37+ StreamVaultDatabase.MIGRATION_36_37,+ StreamVaultDatabase.MIGRATION_37_38)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.ktindex 222e2d51..1c66b104 100644--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt@@ -193,7 +193,9 @@ fun ChannelCard(onLongClick: (() -> Unit)? = null,isLocked: Boolean = false,isReorderMode: Boolean = false,- isDragging: Boolean = false+ isDragging: Boolean = false,+ isRecording: Boolean = false,+ isScheduledRecording: Boolean = false) {val nowMs by ChannelProgressTicker.nowMs.collectAsStateWithLifecycle()val channelCardShape = LocalAppShapes.current.small@@ -316,6 +318,11 @@ fun ChannelCard(if (channel.catchUpSupported) {StatusPill(label = stringResource(R.string.badge_catch_up), containerColor = Primary, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)}+ if (isRecording) {+ StatusPill(label = stringResource(R.string.badge_recording), containerColor = AccentRed, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)+ } else if (isScheduledRecording) {+ StatusPill(label = stringResource(R.string.badge_scheduled), containerColor = AccentAmber, cornerRadius = 4.dp, horizontalPadding = 6.dp, verticalPadding = 2.dp)+ }StatusPill(label = stringResource(R.string.card_live_badge),containerColor = AccentRed,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.ktindex 49fd4d21..f4d06c94 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt@@ -97,6 +97,8 @@ fun DashboardScreen(viewModel: DashboardViewModel = hiltViewModel()) {val uiState by viewModel.uiState.collectAsStateWithLifecycle()+ val recordingChannelIds by viewModel.recordingChannelIds.collectAsStateWithLifecycle()+ val scheduledChannelIds by viewModel.scheduledChannelIds.collectAsStateWithLifecycle()val provider = uiState.providerval snackbarHostState = remember { SnackbarHostState() }@@ -189,6 +191,8 @@ fun DashboardScreen() { channel ->ChannelCard(channel = channel,+ isRecording = channel.id in recordingChannelIds,+ isScheduledRecording = channel.id in scheduledChannelIds,onClick = { onRecentChannelClick(channel, uiState.currentCombinedProfileId) })}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.ktindex ca77fdb8..b6ae5455 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt@@ -29,6 +29,8 @@ import com.streamvault.domain.repository.SeriesRepositoryimport com.streamvault.domain.usecase.ContinueWatchingScopeimport com.streamvault.domain.usecase.GetContinueWatchingimport com.streamvault.domain.usecase.GetCustomCategories+import com.streamvault.domain.manager.RecordingManager+import com.streamvault.domain.model.RecordingStatusimport android.content.Contextimport com.streamvault.app.Rimport dagger.hilt.android.lifecycle.HiltViewModel@@ -47,6 +49,7 @@ import kotlinx.coroutines.flow.distinctUntilChangedimport kotlinx.coroutines.flow.emitAllimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flow+import com.streamvault.domain.util.AdultContentVisibilityPolicyimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.onStart@@ -67,7 +70,8 @@ class DashboardViewModel @Inject constructor(private val getContinueWatching: GetContinueWatching,private val getCustomCategories: GetCustomCategories,private val syncManager: SyncManager,- private val appUpdateInstaller: AppUpdateInstaller+ private val appUpdateInstaller: AppUpdateInstaller,+ private val recordingManager: RecordingManager) : ViewModel() {private companion object {const val FAVORITE_CHANNEL_LIMIT = 12@@ -81,7 +85,23 @@ class DashboardViewModel @Inject constructor(private val _uiState = MutableStateFlow(DashboardUiState())val uiState: StateFlow<DashboardUiState> = _uiState.asStateFlow()+ private val _recordingChannelIds = MutableStateFlow<Set<Long>>(emptySet())+ val recordingChannelIds: StateFlow<Set<Long>> = _recordingChannelIds.asStateFlow()++ private val _scheduledChannelIds = MutableStateFlow<Set<Long>>(emptySet())+ val scheduledChannelIds: StateFlow<Set<Long>> = _scheduledChannelIds.asStateFlow()+init {+ viewModelScope.launch {+ recordingManager.observeRecordingItems().collect { items ->+ _recordingChannelIds.value = items+ .filter { it.status == RecordingStatus.RECORDING }+ .map { it.channelId }.toSet()+ _scheduledChannelIds.value = items+ .filter { it.status == RecordingStatus.SCHEDULED }+ .map { it.channelId }.toSet()+ }+ }viewModelScope.launch {combine(combinedM3uRepository.getActiveLiveSource(),@@ -141,22 +161,30 @@ class DashboardViewModel @Inject constructor(liveProviderIds: List<Long>,combinedProfileId: Long?): Flow<DashboardUiState> {+ val movieShelf = combine(+ movieRepository.getMovies(provider.id),+ preferencesRepository.parentalControlLevel+ ) { movies, level ->+ movies+ .filter { !shouldHideVodFromHome(it, level) }+ .sortedByDescending(::movieFreshnessScore)+ .take(MOVIE_SHELF_LIMIT)+ }+ val seriesShelf = combine(+ seriesRepository.getSeries(provider.id),+ preferencesRepository.parentalControlLevel+ ) { series, level ->+ series+ .filter { !shouldHideVodFromHome(it, level) }+ .sortedByDescending(::seriesFreshnessScore)+ .take(SERIES_SHELF_LIMIT)+ }val contentShelves = combine(observeFavoriteChannels(liveProviderIds).onStart { emit(emptyList()) },observeRecentChannels(liveProviderIds).onStart { emit(emptyList()) },observeContinueWatching(provider.id).onStart { emit(emptyList()) },- movieRepository.getMovies(provider.id).map { movies ->- movies- .filterNot(::shouldHideVodFromHome)- .sortedByDescending(::movieFreshnessScore)- .take(MOVIE_SHELF_LIMIT)- }.onStart { emit(emptyList()) },- seriesRepository.getSeries(provider.id).map { series ->- series- .filterNot(::shouldHideVodFromHome)- .sortedByDescending(::seriesFreshnessScore)- .take(SERIES_SHELF_LIMIT)- }.onStart { emit(emptyList()) }+ movieShelf.onStart { emit(emptyList()) },+ seriesShelf.onStart { emit(emptyList()) }) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->DashboardContentShelves(favoriteChannels = favoriteChannels,@@ -245,13 +273,17 @@ class DashboardViewModel @Inject constructor(.flatMapLatest(::loadChannelsByOrderedIds)private fun observeRecentChannels(providerIds: List<Long>): Flow<List<Channel>> =- preferencesRepository.showRecentChannelsCategory.flatMapLatest { show ->- if (!show) {- flowOf(emptyList())- } else {- observeRecentLiveIds(providerIds, RECENT_CHANNEL_LIMIT)+ combine(+ preferencesRepository.showRecentChannelsCategory.flatMapLatest { show ->+ if (!show) flowOf(emptyList())+ else observeRecentLiveIds(providerIds, RECENT_CHANNEL_LIMIT).flatMapLatest(::loadChannelsByOrderedIds)- }+ },+ preferencesRepository.parentalControlLevel+ ) { channels, level ->+ AdultContentVisibilityPolicy.filterForAggregatedSurface(+ channels, level+ ) { isAdult || isUserProtected }}private fun observeContinueWatching(providerId: Long): Flow<List<PlaybackHistory>> =@@ -484,12 +516,14 @@ class DashboardViewModel @Inject constructor(?: series.id}- private fun shouldHideVodFromHome(movie: Movie): Boolean {+ private fun shouldHideVodFromHome(movie: Movie, level: Int): Boolean {+ if (AdultContentVisibilityPolicy.showInAggregatedSurfaces(level)) return falseif (movie.isAdult || movie.isUserProtected) return truereturn titleLooksExplicit(movie.name)}- private fun shouldHideVodFromHome(series: Series): Boolean {+ private fun shouldHideVodFromHome(series: Series, level: Int): Boolean {+ if (AdultContentVisibilityPolicy.showInAggregatedSurfaces(level)) return falseif (series.isAdult || series.isUserProtected) return truereturn titleLooksExplicit(series.name)}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.ktindex 42edec74..27ddd5ac 100644--- 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.kt@@ -59,8 +59,10 @@ import com.streamvault.app.ui.theme.TextPrimaryimport com.streamvault.app.ui.theme.TextSecondaryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Program-import java.text.SimpleDateFormat-import java.util.Date+import java.time.Instant+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import java.time.format.FormatStyleimport java.util.Localeimport kotlin.math.max@@ -205,12 +207,13 @@ private fun GuideTimelineHeader(scrollState: androidx.compose.foundation.ScrollState) {val now = currentGuideNow()- val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ val hourFormat = remember { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) }+ val zone = remember { ZoneId.systemDefault() }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)))+ stringResource(R.string.epg_now_marker, hourFormat.format(Instant.ofEpochMilli(now).atZone(zone)))} else {stringResource(R.string.epg_outside_window)}@@ -278,7 +281,7 @@ private fun GuideTimelineHeader(verticalArrangement = Arrangement.spacedBy(2.dp)) {Text(- text = hourFormat.format(Date(marker)),+ text = hourFormat.format(Instant.ofEpochMilli(marker).atZone(zone)),style = MaterialTheme.typography.labelSmall,color = OnSurfaceDim)@@ -507,9 +510,10 @@ fun ProgramItem(val now = currentGuideNow()val isCurrent = now in program.startTime until program.endTime- val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }- val startStr = format.format(Date(program.startTime))- val endStr = format.format(Date(program.endTime))+ val format = remember { DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) }+ val zone = remember { ZoneId.systemDefault() }+ val startStr = format.format(Instant.ofEpochMilli(program.startTime).atZone(zone))+ val endStr = format.format(Instant.ofEpochMilli(program.endTime).atZone(zone))val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)val visibleStart = max(program.startTime, windowStart)val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))@@ -570,7 +574,6 @@ fun ProgramItem(.padding(start = itemStart, top = outerVerticalPadding, bottom = outerVerticalPadding).width(itemWidth).fillMaxHeight()- .clip(RoundedCornerShape(8.dp)).onFocusChanged {if (it.isFocused && !isFocused) {onFocused()@@ -583,6 +586,10 @@ fun ProgramItem(),shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, Color.White.copy(alpha = 0.12f)),+ shape = RoundedCornerShape(8.dp)+ ),focusedBorder = Border(border = BorderStroke(2.dp, FocusBorder),shape = RoundedCornerShape(8.dp)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 978466f0..35d6b575 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@@ -214,6 +214,53 @@ fun FullEpgScreen()}+ uiState.recordingMessage?.let { message ->+ LaunchedEffect(message) {+ android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_SHORT).show()+ viewModel.clearRecordingMessage()+ }+ }++ uiState.pendingRecordingConflict?.let { conflict ->+ androidx.compose.material3.AlertDialog(+ onDismissRequest = { viewModel.dismissRecordingConflict() },+ title = {+ androidx.compose.material3.Text(+ text = stringResource(R.string.epg_recording_conflict_title),+ color = com.streamvault.app.ui.theme.OnSurface+ )+ },+ text = {+ val conflictNames = conflict.conflictingItems.joinToString(", ") {+ it.programTitle ?: it.channelName+ }+ androidx.compose.material3.Text(+ text = stringResource(R.string.epg_recording_conflict_body, conflict.programTitle, conflictNames),+ color = com.streamvault.app.ui.theme.TextSecondary+ )+ },+ confirmButton = {+ androidx.compose.material3.TextButton(onClick = { viewModel.forceScheduleRecording() }) {+ androidx.compose.material3.Text(+ text = stringResource(R.string.epg_recording_conflict_replace),+ color = com.streamvault.app.ui.theme.Primary+ )+ }+ },+ dismissButton = {+ androidx.compose.material3.TextButton(onClick = { viewModel.dismissRecordingConflict() }) {+ androidx.compose.material3.Text(+ text = stringResource(R.string.epg_recording_conflict_cancel),+ color = com.streamvault.app.ui.theme.OnSurface+ )+ }+ },+ containerColor = com.streamvault.app.ui.theme.SurfaceElevated,+ titleContentColor = com.streamvault.app.ui.theme.OnSurface,+ textContentColor = com.streamvault.app.ui.theme.TextSecondary+ )+ }+LaunchedEffect(uiState.channels, uiState.programsByChannel) {if (uiState.channels.isEmpty()) {focusedChannel = null@@ -463,7 +510,13 @@ fun FullEpgScreen(onDensitySelected = viewModel::selectDensity,onToggleScheduledOnly = viewModel::toggleScheduledOnly,onToggleFavoritesOnly = viewModel::toggleFavoritesOnly,- onRefresh = viewModel::refresh+ onRefresh = viewModel::refresh,+ onManageEpgMatch = focusedChannel?.takeIf { it.providerId > 0L }?.let { ch ->+ {+ showGuideOptions = false+ viewModel.openEpgOverride(ch)+ }+ })}@@ -567,17 +620,24 @@ fun FullEpgScreen(} else {null},- onManageEpgMatch = if (channel.providerId > 0L) {- {- selectedProgram = null- viewModel.openEpgOverride(channel)- }- } else {- null- },reminderButtonLabel = reminderButtonLabel,onToggleReminder = reminderButtonLabel?.let {{ viewModel.toggleProgramReminder(channel, program) }+ },+ onScheduleRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {+ { viewModel.scheduleRecording(channel, program) }+ } else {+ null+ },+ onScheduleDailyRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {+ { viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.DAILY) }+ } else {+ null+ },+ onScheduleWeeklyRecording = if (channel.streamUrl.isNotBlank() && program.endTime > currentGuideNow()) {+ { viewModel.scheduleRecording(channel, program, com.streamvault.domain.model.RecordingRecurrence.WEEKLY) }+ } else {+ null})}@@ -714,14 +774,14 @@ private fun GuideProviderTroubleshootingCard(}internal fun isGuideCategoryLocked(category: Category, parentalControlLevel: Int): Boolean =- parentalControlLevel == 1 && (category.isAdult || category.isUserProtected)+ parentalControlLevel in 1..2 && (category.isAdult || category.isUserProtected)private fun isGuideChannelLocked(channel: Channel,categoriesById: Map<Long, Category>,parentalControlLevel: Int): Boolean {- if (parentalControlLevel != 1) {+ if (parentalControlLevel !in 1..2) {return false}val categoryLocked = channel.categoryId?.let(categoriesById::get)?.let { category ->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.ktindex 5d3d168e..473d5651 100644--- 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.kt@@ -199,7 +199,8 @@ internal fun GuideOptionsOverlay(onDensitySelected: (GuideDensity) -> Unit,onToggleScheduledOnly: () -> Unit,onToggleFavoritesOnly: () -> Unit,- onRefresh: () -> Unit+ onRefresh: () -> Unit,+ onManageEpgMatch: (() -> Unit)? = null) {val optionsFocusRequester = remember { FocusRequester() }LaunchedEffect(Unit) {@@ -282,8 +283,14 @@ internal fun GuideOptionsOverlay(modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp),- horizontalArrangement = Arrangement.End+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {+ if (onManageEpgMatch != null) {+ GuideShortcutChip(+ label = stringResource(R.string.epg_override_manage),+ onClick = onManageEpgMatch+ )+ }GuideShortcutChip(label = stringResource(R.string.epg_refresh_guide),onClick = onRefresh@@ -303,12 +310,16 @@ internal fun CompactGuideProgramDialog(onDismiss: () -> Unit,onWatchLive: () -> Unit,onWatchArchive: (() -> Unit)?,- onManageEpgMatch: (() -> Unit)?,reminderButtonLabel: String?,- onToggleReminder: (() -> Unit)?+ onToggleReminder: (() -> Unit)?,+ onScheduleRecording: (() -> Unit)?,+ onScheduleDailyRecording: (() -> Unit)?,+ onScheduleWeeklyRecording: (() -> Unit)?) {var showDetails by rememberSaveable(program.startTime, program.endTime, program.title) { mutableStateOf(false) }val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }+ val firstButtonFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) { firstButtonFocusRequester.requestFocus() }GuideModalDialog(onDismiss = onDismiss) {Surface(modifier = Modifier.widthIn(min = 420.dp, max = 640.dp),@@ -318,7 +329,8 @@ internal fun CompactGuideProgramDialog(Column(modifier = Modifier.fillMaxWidth()- .padding(20.dp),+ .padding(20.dp)+ .verticalScroll(rememberScrollState()),verticalArrangement = Arrangement.spacedBy(14.dp)) {Text(@@ -371,7 +383,8 @@ internal fun CompactGuideProgramDialog(Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {TvButton(onClick = onWatchLive,- modifier = Modifier.fillMaxWidth()+ modifier = Modifier.fillMaxWidth().focusRequester(firstButtonFocusRequester),+ scale = ButtonDefaults.scale(focusedScale = 1f)) {Text(stringResource(R.string.epg_watch_live))}@@ -379,6 +392,7 @@ internal fun CompactGuideProgramDialog(TvButton(onClick = onWatchArchive,modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),colors = ButtonDefaults.colors(containerColor = Primary,contentColor = Color.White@@ -387,33 +401,62 @@ internal fun CompactGuideProgramDialog(Text(stringResource(R.string.epg_watch_archive))}}- if (onManageEpgMatch != null) {+ if (reminderButtonLabel != null && onToggleReminder != null) {TvButton(- onClick = onManageEpgMatch,+ onClick = onToggleReminder,modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),colors = ButtonDefaults.colors(containerColor = SurfaceHighlight,contentColor = OnSurface)) {- Text(stringResource(R.string.epg_override_manage))+ Text(reminderButtonLabel)}}- if (reminderButtonLabel != null && onToggleReminder != null) {+ if (onScheduleRecording != null) {TvButton(- onClick = onToggleReminder,+ onClick = { onScheduleRecording(); onDismiss() },+ modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),+ colors = ButtonDefaults.colors(+ containerColor = com.streamvault.app.ui.theme.AccentRed,+ contentColor = Color.White+ )+ ) {+ Text(stringResource(R.string.epg_schedule_recording))+ }+ }+ if (onScheduleDailyRecording != null) {+ TvButton(+ onClick = { onScheduleDailyRecording(); onDismiss() },modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),colors = ButtonDefaults.colors(containerColor = SurfaceHighlight,contentColor = OnSurface)) {- Text(reminderButtonLabel)+ Text(stringResource(R.string.epg_schedule_daily_recording))+ }+ }+ if (onScheduleWeeklyRecording != null) {+ TvButton(+ onClick = { onScheduleWeeklyRecording(); onDismiss() },+ modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),+ colors = ButtonDefaults.colors(+ containerColor = SurfaceHighlight,+ contentColor = OnSurface+ )+ ) {+ Text(stringResource(R.string.epg_schedule_weekly_recording))}}TvButton(onClick = { showDetails = !showDetails },modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),colors = ButtonDefaults.colors(containerColor = SurfaceHighlight,contentColor = OnSurface@@ -424,7 +467,15 @@ internal fun CompactGuideProgramDialog(else stringResource(R.string.epg_program_details_show))}- TextButton(onClick = onDismiss) {+ TvButton(+ onClick = onDismiss,+ modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),+ colors = ButtonDefaults.colors(+ containerColor = Color.Transparent,+ contentColor = OnSurface+ )+ ) {Text(stringResource(R.string.settings_cancel))}}@@ -463,6 +514,9 @@ internal fun EpgOverrideDialog(stringResource(R.string.epg_override_current_external, currentDescriptor)}+ val searchFocusRequester = remember { FocusRequester() }+ LaunchedEffect(Unit) { searchFocusRequester.requestFocus() }+GuideModalDialog(onDismiss = onDismiss) {Surface(modifier = Modifier.widthIn(min = 560.dp, max = 760.dp),@@ -472,7 +526,8 @@ internal fun EpgOverrideDialog(Column(modifier = Modifier.fillMaxWidth()- .padding(20.dp),+ .padding(20.dp)+ .focusGroup(),verticalArrangement = Arrangement.spacedBy(14.dp)) {Text(@@ -518,6 +573,7 @@ internal fun EpgOverrideDialog(onValueChange = onQueryChange,placeholder = stringResource(R.string.epg_override_search_placeholder),modifier = Modifier.fillMaxWidth(),+ focusRequester = searchFocusRequester,onSearch = { onQueryChange(it) })if (state.candidates.isEmpty()) {@@ -534,7 +590,8 @@ internal fun EpgOverrideDialog(LazyColumn(modifier = Modifier.fillMaxWidth()- .heightIn(max = 320.dp),+ .heightIn(max = 320.dp)+ .focusGroup(),verticalArrangement = Arrangement.spacedBy(10.dp)) {items(@@ -550,6 +607,7 @@ internal fun EpgOverrideDialog(}},modifier = Modifier.fillMaxWidth(),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),colors = ClickableSurfaceDefaults.colors(containerColor = if (isCurrent) SurfaceHighlight else SurfaceElevated,focusedContainerColor = SurfaceHighlight,@@ -608,6 +666,7 @@ internal fun EpgOverrideDialog(onClick = onClearOverride,enabled = !state.isSaving,modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),colors = ButtonDefaults.colors(containerColor = SurfaceHighlight,contentColor = OnSurface@@ -616,7 +675,15 @@ internal fun EpgOverrideDialog(Text(stringResource(R.string.epg_override_clear))}}- TextButton(onClick = onDismiss) {+ TvButton(+ onClick = onDismiss,+ modifier = Modifier.fillMaxWidth(),+ scale = ButtonDefaults.scale(focusedScale = 1f),+ colors = ButtonDefaults.colors(+ containerColor = Color.Transparent,+ contentColor = OnSurface+ )+ ) {Text(stringResource(R.string.settings_cancel))}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.ktindex 51a712c7..3966a68b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt@@ -23,10 +23,20 @@ import com.streamvault.domain.repository.EpgSourceRepositoryimport com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.LiveStreamProgramRequestimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.Result+import com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.usecase.GetCustomCategories+import com.streamvault.domain.usecase.ScheduleRecording+import com.streamvault.domain.usecase.ScheduleRecordingCommand+import com.streamvault.domain.util.AdultContentVisibilityPolicyimport com.streamvault.data.preferences.PreferencesRepositoryimport dagger.hilt.android.lifecycle.HiltViewModelimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.FlowPreviewimport kotlinx.coroutines.Jobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAll@@ -36,6 +46,7 @@ import kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.debounceimport kotlinx.coroutines.flow.distinctUntilChangedimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.first@@ -43,8 +54,16 @@ import kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext+import java.time.Instant+import java.time.ZoneIdimport javax.inject.Inject+data class RecordingConflictInfo(+ val conflictingItems: List<RecordingItem>,+ val pendingRequest: RecordingRequest,+ val programTitle: String+)+data class EpgUiState(val currentProviderName: String? = null,val providerSourceLabel: String = "",@@ -69,10 +88,16 @@ data class EpgUiState(val failedScheduleCount: Int = 0,val lastUpdatedAt: Long? = null,val isGuideStale: Boolean = false,- val guideAnchorTime: Long = System.currentTimeMillis(),- val guideWindowStart: Long = System.currentTimeMillis() - EpgViewModel.LOOKBACK_MS,- val guideWindowEnd: Long = System.currentTimeMillis() + EpgViewModel.LOOKAHEAD_MS-)+ val guideAnchorTime: Long = DEFAULT_NOW,+ val guideWindowStart: Long = DEFAULT_NOW - EpgViewModel.LOOKBACK_MS,+ val guideWindowEnd: Long = DEFAULT_NOW + EpgViewModel.LOOKAHEAD_MS,+ val recordingMessage: String? = null,+ val pendingRecordingConflict: RecordingConflictInfo? = null+) {+ companion object {+ private val DEFAULT_NOW = System.currentTimeMillis()+ }+}data class EpgOverrideUiState(val channel: Channel? = null,@@ -191,6 +216,7 @@ private data class CombinedGuideRequest()@HiltViewModel+@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)class EpgViewModel @Inject constructor(private val providerRepository: ProviderRepository,private val combinedM3uRepository: CombinedM3uRepository,@@ -201,7 +227,9 @@ class EpgViewModel @Inject constructor(private val preferencesRepository: PreferencesRepository,private val parentalControlManager: ParentalControlManager,private val programReminderManager: ProgramReminderManager,- private val getCustomCategories: GetCustomCategories+ private val getCustomCategories: GetCustomCategories,+ private val scheduleRecording: ScheduleRecording,+ private val recordingManager: RecordingManager) : ViewModel() {companion object {@@ -359,6 +387,79 @@ class EpgViewModel @Inject constructor(}}+ fun scheduleRecording(channel: Channel, program: Program, recurrence: RecordingRecurrence = RecordingRecurrence.NONE) {+ viewModelScope.launch {+ val command = ScheduleRecordingCommand(+ contentType = ContentType.LIVE,+ providerId = channel.providerId,+ channel = channel,+ streamUrl = channel.streamUrl,+ currentProgram = program,+ nextProgram = null,+ recurrence = recurrence+ )+ val result = scheduleRecording(command)+ when (result) {+ is Result.Success -> {+ _uiState.update { it.copy(recordingMessage = "Recording scheduled: ${program.title}") }+ }+ is Result.Error -> {+ val msg = result.message.orEmpty()+ if (msg.contains("conflicts", ignoreCase = true)) {+ val scheduledStartMs = maxOf(System.currentTimeMillis(), program.startTime)+ val conflicts = recordingManager.getConflictingRecordings(+ scheduledStartMs, program.endTime, channel.providerId+ )+ if (conflicts.isNotEmpty()) {+ _uiState.update {+ it.copy(+ pendingRecordingConflict = RecordingConflictInfo(+ conflictingItems = conflicts,+ pendingRequest = RecordingRequest(+ providerId = channel.providerId,+ channelId = channel.id,+ channelName = channel.name,+ streamUrl = channel.streamUrl,+ scheduledStartMs = scheduledStartMs,+ scheduledEndMs = program.endTime,+ programTitle = program.title,+ recurrence = recurrence+ ),+ programTitle = program.title ?: channel.name+ )+ )+ }+ return@launch+ }+ }+ _uiState.update { it.copy(recordingMessage = msg.ifBlank { "Failed to schedule recording" }) }+ }+ else -> {}+ }+ }+ }++ fun forceScheduleRecording() {+ val conflict = _uiState.value.pendingRecordingConflict ?: return+ viewModelScope.launch {+ val result = recordingManager.forceScheduleRecording(conflict.pendingRequest)+ val message = when (result) {+ is Result.Success -> "Recording scheduled: ${conflict.programTitle}"+ is Result.Error -> result.message ?: "Failed to schedule recording"+ else -> return@launch+ }+ _uiState.update { it.copy(recordingMessage = message, pendingRecordingConflict = null) }+ }+ }++ fun dismissRecordingConflict() {+ _uiState.update { it.copy(pendingRecordingConflict = null) }+ }++ fun clearRecordingMessage() {+ _uiState.update { it.copy(recordingMessage = null) }+ }+fun updateEpgOverrideSearch(query: String) {val channel = _overrideUiState.value.channel ?: return_overrideUiState.update {@@ -894,7 +995,7 @@ class EpgViewModel @Inject constructor(viewModelScope.launch {combine(baseGuideSnapshot,- programSearchQuery,+ programSearchQuery.debounce(150L),showScheduledOnly,selectedChannelMode,selectedDensity@@ -1358,10 +1459,12 @@ class EpgViewModel @Inject constructor(parentalControlLevel: Int,unlockedCategoryIds: Set<Long>): Boolean {- if (parentalControlLevel != 1) {- return true- }- return (!category.isAdult && !category.isUserProtected) || unlockedCategoryIds.contains(category.id)+ // Non-adult/protected categories are always accessible+ if (!category.isAdult && !category.isUserProtected) return true+ // Adult/protected: accessible if level permits aggregated surfaces (OFF or LOCKED),+ // OR if the user has explicitly unlocked this category+ return AdultContentVisibilityPolicy.showInAggregatedSurfaces(parentalControlLevel) ||+ unlockedCategoryIds.contains(category.id)}}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 de5c74f0..2b20a896 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@@ -343,7 +343,7 @@ fun HomeScreen(val isCategoryLocked: (Category) -> Boolean = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds) {{ category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}@@ -372,7 +372,7 @@ fun HomeScreen((sourceCategory?.isAdult == true) ||(sourceCategory?.isUserProtected == true)) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&!unlocked}}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.ktindex b049dff9..5dc2850c 100644--- 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.kt@@ -123,7 +123,7 @@ internal fun HomeDialogsHost(val category = uiState.selectedCategoryForOptionsval isCategoryLocked =(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIdsCategoryOptionsDialog(category = category,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktindex 634ccab5..84a3cf33 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt@@ -38,6 +38,7 @@ import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.LiveStreamProgramRequestimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.util.AdultContentVisibilityPolicyimport com.streamvault.domain.usecase.GetCustomCategoriesimport com.streamvault.domain.usecase.UnlockParentalCategoryimport com.streamvault.domain.usecase.UnlockParentalCategoryCommand@@ -762,18 +763,26 @@ class HomeViewModel @Inject constructor(combine(channelsFlow,preferencesRepository.liveChannelNumberingMode,- _uiState.map { it.selectedCombinedSourceProviderId }.distinctUntilChanged()- ) { channels, numberingMode, selectedCombinedSourceProviderId ->- val visibleChannels = selectedCombinedSourceProviderId?.let { selectedProviderId ->+ _uiState.map { it.selectedCombinedSourceProviderId }.distinctUntilChanged(),+ _uiState.map { it.parentalControlLevel }.distinctUntilChanged()+ ) { channels, numberingMode, selectedCombinedSourceProviderId, level ->+ val byProvider = selectedCombinedSourceProviderId?.let { selectedProviderId ->channels.filter { it.providerId == selectedProviderId }} ?: channels- when (numberingMode) {- ChannelNumberingMode.GROUP -> visibleChannels.mapIndexed { index, channel ->+ val numbered = when (numberingMode) {+ ChannelNumberingMode.GROUP -> byProvider.mapIndexed { index, channel ->channel.copy(number = index + 1)}- ChannelNumberingMode.PROVIDER -> visibleChannels- ChannelNumberingMode.HIDDEN -> visibleChannels.map { it.copy(number = 0) }+ ChannelNumberingMode.PROVIDER -> byProvider+ ChannelNumberingMode.HIDDEN -> byProvider.map { it.copy(number = 0) }}+ val isAggregatedSurface = category.id == ChannelRepository.ALL_CHANNELS_ID ||+ category.id == VirtualCategoryIds.RECENT+ if (isAggregatedSurface) {+ AdultContentVisibilityPolicy.filterForAggregatedSurface(+ numbered, level+ ) { isAdult || isUserProtected }+ } else numbered}.collect { displayedChannels ->val currentQuery = _uiState.value.channelSearchQuery.trim()val currentLimit = if (currentQuery.length < MIN_CHANNEL_SEARCH_QUERY_LENGTH) {@@ -1155,13 +1164,19 @@ class HomeViewModel @Inject constructor(private fun observeRecentChannels(providerId: Long) {recentChannelsJob?.cancel()recentChannelsJob = viewModelScope.launch {- playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 12)- .map { it.toRecentLiveContentIds() }- .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }- .collect { channels ->- _uiState.update { it.copy(recentChannels = channels) }- updateRecentCategoryCount(channels.size)- }+ combine(+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 12)+ .map { it.toRecentLiveContentIds() }+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) },+ preferencesRepository.parentalControlLevel+ ) { channels, level ->+ AdultContentVisibilityPolicy.filterForAggregatedSurface(+ channels, level+ ) { isAdult || isUserProtected }+ }.collect { visible ->+ _uiState.update { it.copy(recentChannels = visible) }+ updateRecentCategoryCount(visible.size)+ }}}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 1463ad18..b136092d 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@@ -379,14 +379,14 @@ private fun MoviesVodContent(val isCategoryLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}val isCategoryHidden = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel >= 2 &&+ uiState.parentalControlLevel >= 3 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}@@ -394,7 +394,7 @@ private fun MoviesVodContent({ movie: Movie ->val categoryId = movie.categoryId(movie.isAdult || movie.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&(categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)}}@@ -909,14 +909,14 @@ private fun MoviesVodClassicContent(val isCategoryLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}val isCategoryHidden = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel >= 2 &&+ uiState.parentalControlLevel >= 3 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}@@ -924,7 +924,7 @@ private fun MoviesVodClassicContent({ movie: Movie ->val categoryId = movie.categoryId(movie.isAdult || movie.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&(categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.ktindex 9bf8610a..b5c37ef7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt@@ -630,7 +630,7 @@ private fun ReplaceSlotDialog(var pendingLockedCategory by remember { mutableStateOf<com.streamvault.domain.model.Category?>(null) }fun isCategoryLocked(cat: com.streamvault.domain.model.Category): Boolean =- parentalControlLevel == 1 && (cat.isAdult || cat.isUserProtected)+ parentalControlLevel in 1..2 && (cat.isAdult || cat.isUserProtected)PremiumDialog(title = if (selectedCategory == null) stringResource(R.string.multiview_replace_title) else selectedCategory.name,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.ktindex a0115bb2..3377c405 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt@@ -326,5 +326,5 @@ data class ProviderSetupState(val pendingCombinedAttachProfileName: String? = null,val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,val xtreamFastSyncEnabled: Boolean = true,- val m3uVodClassificationEnabled: Boolean = true+ val m3uVodClassificationEnabled: Boolean = false)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.ktindex d2f9e7de..fa4aa679 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt@@ -66,6 +66,9 @@ import com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.usecase.SearchContentimport com.streamvault.domain.usecase.SearchContentScope+import com.streamvault.domain.manager.RecordingManager+import com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.util.AdultContentVisibilityPolicyimport dagger.hilt.android.lifecycle.HiltViewModelimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.FlowPreview@@ -82,7 +85,8 @@ class SearchViewModel @Inject constructor(private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,private val parentalControlManager: ParentalControlManager,private val favoriteRepository: FavoriteRepository,- private val categoryRepository: CategoryRepository+ private val categoryRepository: CategoryRepository,+ private val recordingManager: RecordingManager) : ViewModel() {private companion object {const val MAX_RESULTS_PER_SECTION = 120@@ -97,6 +101,13 @@ class SearchViewModel @Inject constructor(private val _parentalControlLevel = MutableStateFlow(0)private val _activeProviderId = MutableStateFlow<Long?>(null)++ private val _recordingChannelIds = MutableStateFlow<Set<Long>>(emptySet())+ val recordingChannelIds: StateFlow<Set<Long>> = _recordingChannelIds.asStateFlow()++ private val _scheduledChannelIds = MutableStateFlow<Set<Long>>(emptySet())+ val scheduledChannelIds: StateFlow<Set<Long>> = _scheduledChannelIds.asStateFlow()+private val unlockedCategoryIds = providerRepository.getActiveProvider().onEach { provider -> _activeProviderId.value = provider?.id }.flatMapLatest { provider ->@@ -109,6 +120,16 @@ class SearchViewModel @Inject constructor(_parentalControlLevel.value = level}}+ viewModelScope.launch {+ recordingManager.observeRecordingItems().collect { items ->+ _recordingChannelIds.value = items+ .filter { it.status == RecordingStatus.RECORDING }+ .map { it.channelId }.toSet()+ _scheduledChannelIds.value = items+ .filter { it.status == RecordingStatus.SCHEDULED }+ .map { it.channelId }.toSet()+ }+ }}val recentQueries: StateFlow<List<String>> = combine(@@ -156,10 +177,17 @@ class SearchViewModel @Inject constructor(scope = tab.toSearchScope(),maxResultsPerSection = MAX_RESULTS_PER_SECTION).map { results ->+ val filterAdult = !AdultContentVisibilityPolicy.showInAggregatedSurfaces(level)SearchUiState(- channels = results.channels,- movies = results.movies,- series = results.series,+ channels = if (filterAdult)+ results.channels.filterNot { it.isAdult || it.isUserProtected }+ else results.channels,+ movies = if (filterAdult)+ results.movies.filterNot { it.isAdult || it.isUserProtected }+ else results.movies,+ series = if (filterAdult)+ results.series.filterNot { it.isAdult || it.isUserProtected }+ else results.series,isLoading = false,hasSearched = true,parentalControlLevel = level,@@ -322,6 +350,8 @@ fun SearchScreen(val selectedTab by viewModel.selectedTab.collectAsStateWithLifecycle()val recentQueries by viewModel.recentQueries.collectAsStateWithLifecycle()val uiState by viewModel.uiState.collectAsStateWithLifecycle()+ val recordingChannelIds by viewModel.recordingChannelIds.collectAsStateWithLifecycle()+ val scheduledChannelIds by viewModel.scheduledChannelIds.collectAsStateWithLifecycle()val focusManager = LocalFocusManager.currentval searchFocusRequester = remember { FocusRequester() }val context = androidx.compose.ui.platform.LocalContext.current@@ -566,6 +596,8 @@ fun SearchScreen(ChannelCard(channel = channel,isLocked = channelLocked,+ isRecording = channel.id in recordingChannelIds,+ isScheduledRecording = channel.id in scheduledChannelIds,onClick = {if (channelLocked) {pendingChannel = channel@@ -656,6 +688,8 @@ fun SearchScreen(}) { row ->SearchChannelGridRow(channels = row,+ recordingChannelIds = recordingChannelIds,+ scheduledChannelIds = scheduledChannelIds,isLocked = { channel ->isLocked(categoryId = channel.categoryId,@@ -962,6 +996,8 @@ private fun <T : Any> SearchResultRail(@Composableprivate fun SearchChannelGridRow(channels: List<Channel>,+ recordingChannelIds: Set<Long> = emptySet(),+ scheduledChannelIds: Set<Long> = emptySet(),isLocked: (Channel) -> Boolean,onChannelClick: (Channel, Boolean) -> Unit,onChannelLongClick: (Channel) -> Unit@@ -975,6 +1011,8 @@ private fun SearchChannelGridRow(ChannelCard(channel = channel,isLocked = locked,+ isRecording = channel.id in recordingChannelIds,+ isScheduledRecording = channel.id in scheduledChannelIds,onClick = { onChannelClick(channel, locked) },onLongClick = { onChannelLongClick(channel) })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 bf62d248..e142a26d 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@@ -378,14 +378,14 @@ private fun SeriesVodContent(val isCategoryLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}val isCategoryHidden = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel >= 2 &&+ uiState.parentalControlLevel >= 3 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}@@ -393,7 +393,7 @@ private fun SeriesVodContent({ series: Series ->val categoryId = series.categoryId(series.isAdult || series.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&(categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)}}@@ -895,14 +895,14 @@ private fun SeriesVodClassicContent(val isCategoryLocked = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}val isCategoryHidden = remember(uiState.parentalControlLevel, uiState.unlockedCategoryIds, categoryByName) {{ category: Category ->(category.isAdult || category.isUserProtected) &&- uiState.parentalControlLevel >= 2 &&+ uiState.parentalControlLevel >= 3 &&kotlin.math.abs(category.id) !in uiState.unlockedCategoryIds}}@@ -910,7 +910,7 @@ private fun SeriesVodClassicContent({ series: Series ->val categoryId = series.categoryId(series.isAdult || series.isUserProtected) &&- uiState.parentalControlLevel == 1 &&+ uiState.parentalControlLevel in 1..2 &&(categoryId == null || kotlin.math.abs(categoryId) !in uiState.unlockedCategoryIds)}}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.ktindex 5628b9c3..2cbd48f3 100644--- 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.kt@@ -7,7 +7,9 @@ import androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScrollimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardActionsimport androidx.compose.foundation.text.KeyboardOptions@@ -100,7 +102,10 @@ internal fun PremiumSelectionDialog(HorizontalDivider(color = Color.White.copy(alpha = 0.1f))Column(verticalArrangement = Arrangement.spacedBy(6.dp),- modifier = Modifier.padding(top = 6.dp)+ modifier = Modifier+ .padding(top = 6.dp)+ .weight(1f, fill = false)+ .verticalScroll(rememberScrollState())) {content()}@@ -206,7 +211,13 @@ internal fun TimeoutValueDialog(}@Composable-internal fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect: () -> Unit) {+internal fun LevelOption(+ level: Int,+ text: String,+ currentLevel: Int,+ subtitle: String? = null,+ onSelect: () -> Unit+) {Row(modifier = Modifier.fillMaxWidth()@@ -219,7 +230,14 @@ internal fun LevelOption(level: Int, text: String, currentLevel: Int, onSelect:onClick = onSelect)Spacer(modifier = Modifier.width(8.dp))- Text(text, style = MaterialTheme.typography.bodyMedium, color = OnBackground)+ if (subtitle != null) {+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(text, style = MaterialTheme.typography.titleSmall, color = OnBackground)+ Text(subtitle, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ }+ } else {+ Text(text, style = MaterialTheme.typography.bodyMedium, color = OnBackground)+ }}}@@ -428,7 +446,8 @@ internal fun ParentalControlCard(text = when(level) {0 -> stringResource(R.string.settings_level_off)1 -> stringResource(R.string.settings_level_locked)- 2 -> stringResource(R.string.settings_level_hidden)+ 2 -> stringResource(R.string.settings_level_private)+ 3 -> stringResource(R.string.settings_level_hidden)else -> stringResource(R.string.settings_level_unknown)},style = MaterialTheme.typography.bodyMedium,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.ktindex 829cb42d..93c81179 100644--- 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.kt@@ -45,6 +45,21 @@ internal class SettingsRecordingActions(}}+ fun skipOccurrence(scope: CoroutineScope, recordingId: String) {+ scope.launch {+ val result = recordingManager.skipOccurrence(recordingId)+ uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_skip_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_skipped)+ }+ )+ }+ }+ }+fun deleteRecording(scope: CoroutineScope, recordingId: String) {scope.launch {val result = recordingManager.deleteRecording(recordingId)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.ktindex 8eaa556c..d39698e0 100644--- 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.kt@@ -2,12 +2,17 @@ package com.streamvault.app.ui.screens.settingsimport androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.background+import androidx.compose.foundation.borderimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Switch+import androidx.compose.material3.SwitchDefaultsimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOf@@ -20,7 +25,10 @@ import androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.focus.focusRequesterimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.platform.LocalSoftwareKeyboardControllerimport androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport androidx.compose.ui.res.stringResource@@ -319,7 +327,7 @@ private fun BackupToggleRow(@OptIn(ExperimentalLayoutApi::class)@Composable-internal fun RecordingOverviewCard(+internal fun RecordingInfoCard(treeLabel: String?,outputDirectory: String?,availableBytes: Long?,@@ -329,18 +337,24 @@ internal fun RecordingOverviewCard(fileNamePattern: String,retentionDays: Int?,maxSimultaneousRecordings: Int,- onChooseFolder: () -> Unit,- onUseAppStorage: () -> Unit,- onChangePattern: () -> Unit,- onChangeRetention: () -> Unit,- onChangeConcurrency: () -> Unit,- onOpenBrowser: () -> Unit,- onRepairSchedule: () -> Unit+ paddingBeforeMinutes: Int,+ paddingAfterMinutes: Int) {- Surface(+ TvClickableSurface(+ onClick = { },modifier = Modifier.fillMaxWidth(),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),- shape = RoundedCornerShape(16.dp)+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = SurfaceElevated+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(16.dp)+ )+ )) {Column(modifier = Modifier.padding(20.dp),@@ -424,111 +438,152 @@ internal fun RecordingOverviewCard(label = stringResource(R.string.settings_recording_concurrency_title),value = maxSimultaneousRecordings.toString())- }- Column(- modifier = Modifier.fillMaxWidth(),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp)- ) {- RecordingActionButton(- label = stringResource(R.string.settings_recording_choose_folder),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onChooseFolder- )- RecordingActionButton(- label = stringResource(R.string.settings_recording_use_app_storage),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onUseAppStorage- )- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp)- ) {- RecordingActionButton(- label = stringResource(R.string.settings_recording_pattern_title),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onChangePattern- )- RecordingActionButton(- label = stringResource(R.string.settings_recording_retention_title),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onChangeRetention- )- RecordingActionButton(- label = stringResource(R.string.settings_recording_concurrency_title),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onChangeConcurrency- )- }- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(10.dp)- ) {- RecordingActionButton(- label = stringResource(R.string.settings_recording_open_browser),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onOpenBrowser- )- RecordingActionButton(- label = stringResource(R.string.settings_recording_reconcile),- accent = OnBackground,- modifier = Modifier.weight(1f),- onClick = onRepairSchedule- )- }+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_padding_before),+ value = if (paddingBeforeMinutes > 0) {+ stringResource(R.string.settings_recording_padding_minutes, paddingBeforeMinutes)+ } else {+ stringResource(R.string.settings_recording_padding_none)+ }+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_padding_after),+ value = if (paddingAfterMinutes > 0) {+ stringResource(R.string.settings_recording_padding_minutes, paddingAfterMinutes)+ } else {+ stringResource(R.string.settings_recording_padding_none)+ }+ )}}}}-@OptIn(ExperimentalLayoutApi::class)@Composable-internal fun RecordingDashboardSection(- treeLabel: String?,- outputDirectory: String?,- availableBytes: Long?,- isWritable: Boolean,- activeCount: Int,- scheduledCount: Int,- fileNamePattern: String,- retentionDays: Int?,- maxSimultaneousRecordings: Int,+internal fun RecordingActionsCard(+ wifiOnlyRecording: Boolean,+ onWifiOnlyRecordingChange: (Boolean) -> Unit,onChooseFolder: () -> Unit,onUseAppStorage: () -> Unit,onChangePattern: () -> Unit,onChangeRetention: () -> Unit,onChangeConcurrency: () -> Unit,- onRepairSchedule: () -> Unit,- onOpenBrowser: () -> Unit+ onChangePadding: () -> Unit,+ onOpenBrowser: () -> Unit,+ onRepairSchedule: () -> Unit) {- RecordingOverviewCard(- treeLabel = treeLabel,- outputDirectory = outputDirectory,- availableBytes = availableBytes,- isWritable = isWritable,- activeCount = activeCount,- scheduledCount = scheduledCount,- fileNamePattern = fileNamePattern,- retentionDays = retentionDays,- maxSimultaneousRecordings = maxSimultaneousRecordings,- onChooseFolder = onChooseFolder,- onUseAppStorage = onUseAppStorage,- onChangePattern = onChangePattern,- onChangeRetention = onChangeRetention,- onChangeConcurrency = onChangeConcurrency,- onOpenBrowser = onOpenBrowser,- onRepairSchedule = onRepairSchedule- )+ Surface(+ modifier = Modifier.fillMaxWidth(),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier.padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_choose_folder),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChooseFolder+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_use_app_storage),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onUseAppStorage+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_pattern_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangePattern+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_retention_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangeRetention+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_concurrency_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangeConcurrency+ )+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_open_browser),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onOpenBrowser+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_reconcile),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onRepairSchedule+ )+ RecordingActionButton(+ label = stringResource(R.string.settings_recording_padding_title),+ accent = OnBackground,+ modifier = Modifier.weight(1f),+ onClick = onChangePadding+ )+ }+ TvClickableSurface(+ onClick = { onWifiOnlyRecordingChange(!wifiOnlyRecording) },+ modifier = Modifier.fillMaxWidth(),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.Transparent,+ focusedContainerColor = Primary.copy(alpha = 0.12f)+ ),+ border = ClickableSurfaceDefaults.border(+ focusedBorder = Border(+ border = BorderStroke(2.dp, Color.White),+ shape = RoundedCornerShape(10.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = stringResource(R.string.settings_recording_wifi_only),+ style = MaterialTheme.typography.bodyMedium,+ color = OnSurface+ )+ Switch(+ checked = wifiOnlyRecording,+ onCheckedChange = null,+ colors = SwitchDefaults.colors(+ checkedThumbColor = Primary,+ checkedTrackColor = Primary.copy(alpha = 0.3f),+ uncheckedThumbColor = OnSurfaceDim,+ uncheckedTrackColor = OnSurfaceDim.copy(alpha = 0.2f)+ )+ )+ }+ }+ }+ }}@OptIn(ExperimentalLayoutApi::class)@@ -541,6 +596,7 @@ internal fun RecordingBrowserDialog(onPlay: (RecordingItem) -> Unit,onStop: (RecordingItem) -> Unit,onCancel: (RecordingItem) -> Unit,+ onSkipOccurrence: (RecordingItem) -> Unit,onDelete: (RecordingItem) -> Unit,onRetry: (RecordingItem) -> Unit,onToggleSchedule: (RecordingItem, Boolean) -> Unit@@ -616,6 +672,7 @@ internal fun RecordingBrowserDialog(onPlay = onPlay,onStop = onStop,onCancel = onCancel,+ onSkipOccurrence = onSkipOccurrence,onDelete = onDelete,onRetry = onRetry,onToggleSchedule = onToggleSchedule@@ -636,11 +693,23 @@ private fun RecordingBrowserPanel(onPlay: (RecordingItem) -> Unit,onStop: (RecordingItem) -> Unit,onCancel: (RecordingItem) -> Unit,+ onSkipOccurrence: (RecordingItem) -> Unit,onDelete: (RecordingItem) -> Unit,onRetry: (RecordingItem) -> Unit,onToggleSchedule: (RecordingItem, Boolean) -> Unit) {val selectedItem = recordingItems.firstOrNull { it.id == selectedRecordingId } ?: recordingItems.first()+ var searchQuery by remember { mutableStateOf("") }+ var statusFilter by remember { mutableStateOf<RecordingStatus?>(null) }+ val filteredItems = remember(recordingItems, searchQuery, statusFilter) {+ recordingItems.filter { item ->+ val matchesSearch = searchQuery.isBlank() ||+ item.channelName.contains(searchQuery, ignoreCase = true) ||+ item.programTitle?.contains(searchQuery, ignoreCase = true) == true+ val matchesStatus = statusFilter == null || item.status == statusFilter+ matchesSearch && matchesStatus+ }+ }Row(modifier = Modifier.fillMaxSize(),@@ -656,7 +725,7 @@ private fun RecordingBrowserPanel() {Column(modifier = Modifier.fillMaxSize().padding(14.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)+ verticalArrangement = Arrangement.spacedBy(8.dp)) {Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {Text(@@ -665,17 +734,103 @@ private fun RecordingBrowserPanel(color = Primary)Text(- text = "${recordingItems.size} items",+ text = "${filteredItems.size} of ${recordingItems.size} items",style = MaterialTheme.typography.bodySmall,color = OnSurfaceDim)}+ androidx.compose.foundation.layout.FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ CompactRecordingActionChip(+ label = "All",+ accent = if (statusFilter == null) Primary else OnSurfaceDim,+ onClick = { statusFilter = null }+ )+ RecordingStatus.entries.forEach { status ->+ CompactRecordingActionChip(+ label = recordingStatusLabel(status),+ accent = if (statusFilter == status) recordingStatusAccent(status) else OnSurfaceDim,+ onClick = { statusFilter = if (statusFilter == status) null else status }+ )+ }+ }+ val isTelevisionDevice = com.streamvault.app.device.rememberIsTelevisionDevice()+ val searchFocusRequester = remember { FocusRequester() }+ val inputFocusRequester = remember { FocusRequester() }+ val keyboardController = LocalSoftwareKeyboardController.current+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ TvClickableSurface(+ onClick = {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ },+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(searchFocusRequester),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated,+ focusedContainerColor = SurfaceHighlight+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ border = BorderStroke(1.dp, OnSurfaceDim.copy(alpha = 0.3f)),+ shape = RoundedCornerShape(8.dp)+ ),+ focusedBorder = Border(+ border = BorderStroke(2.dp, FocusBorder),+ shape = RoundedCornerShape(8.dp)+ )+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 10.dp, vertical = 6.dp)+ ) {+ if (searchQuery.isEmpty()) {+ Text(+ text = "Search recordings…",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ BasicTextField(+ value = searchQuery,+ onValueChange = { searchQuery = it },+ textStyle = MaterialTheme.typography.bodySmall.copy(color = OnBackground),+ singleLine = true,+ cursorBrush = SolidColor(Primary),+ readOnly = isTelevisionDevice && !acceptsInput,+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ keyboardActions = KeyboardActions(onSearch = {+ acceptsInput = false+ keyboardController?.hide()+ searchFocusRequester.requestFocus()+ }),+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(inputFocusRequester)+ .onFocusChanged {+ if (!it.isFocused && isTelevisionDevice) {+ acceptsInput = false+ keyboardController?.hide()+ }+ }+ )+ }+ }LazyColumn(modifier = Modifier.fillMaxSize(),verticalArrangement = Arrangement.spacedBy(8.dp),contentPadding = PaddingValues(bottom = 4.dp)) {- items(recordingItems, key = { item -> item.id }) { item ->+ items(filteredItems, key = { item -> item.id }) { item ->RecordingPickerRow(item = item,selected = item.id == selectedItem.id,@@ -694,6 +849,7 @@ private fun RecordingBrowserPanel(onPlay = { onPlay(selectedItem) },onStop = { onStop(selectedItem) },onCancel = { onCancel(selectedItem) },+ onSkipOccurrence = { onSkipOccurrence(selectedItem) },onDelete = { onDelete(selectedItem) },onRetry = { onRetry(selectedItem) },onToggleSchedule = { enabled -> onToggleSchedule(selectedItem, enabled) }@@ -784,6 +940,7 @@ private fun RecordingDetailPanel(onPlay: () -> Unit,onStop: () -> Unit,onCancel: () -> Unit,+ onSkipOccurrence: () -> Unit,onDelete: () -> Unit,onRetry: () -> Unit,onToggleSchedule: (Boolean) -> Unit@@ -935,6 +1092,13 @@ private fun RecordingDetailPanel(accent = Secondary,onClick = { onToggleSchedule(!item.scheduleEnabled) })+ if (item.recurringRuleId != null) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_skip),+ accent = OnBackground,+ onClick = onSkipOccurrence+ )+ }CompactRecordingActionChip(label = stringResource(R.string.settings_recording_cancel),accent = OnBackground,@@ -1048,6 +1212,7 @@ internal fun RecordingItemCard(onPlay: () -> Unit,onStop: () -> Unit,onCancel: () -> Unit,+ onSkipOccurrence: () -> Unit,onDelete: () -> Unit,onRetry: () -> Unit,onToggleSchedule: (Boolean) -> Unit@@ -1210,6 +1375,13 @@ internal fun RecordingItemCard(accent = Secondary,onClick = { onToggleSchedule(!item.scheduleEnabled) })+ if (item.recurringRuleId != null) {+ CompactRecordingActionChip(+ label = stringResource(R.string.settings_recording_skip),+ accent = OnBackground,+ onClick = onSkipOccurrence+ )+ }CompactRecordingActionChip(label = stringResource(R.string.settings_recording_cancel),accent = OnBackground,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 ed905c64..cb6c43f9 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@@ -183,7 +183,8 @@ fun SettingsScreen(when (uiState.parentalControlLevel) {0 -> context.getString(R.string.settings_level_off)1 -> context.getString(R.string.settings_level_locked)- 2 -> context.getString(R.string.settings_level_hidden)+ 2 -> context.getString(R.string.settings_level_private)+ 3 -> context.getString(R.string.settings_level_hidden)else -> context.getString(R.string.settings_level_unknown)}}@@ -241,6 +242,7 @@ fun SettingsScreen(var showRecordingPatternDialog by rememberSaveable { mutableStateOf(false) }var showRecordingRetentionDialog by rememberSaveable { mutableStateOf(false) }var showRecordingConcurrencyDialog by rememberSaveable { mutableStateOf(false) }+ var showRecordingPaddingDialog by rememberSaveable { mutableStateOf(false) }var showRecordingBrowserDialog by rememberSaveable { mutableStateOf(false) }var selectedRecordingId by rememberSaveable { mutableStateOf<String?>(null) }var categorySortDialogType by rememberSaveable { mutableStateOf<String?>(null) }@@ -873,15 +875,15 @@ 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 ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€else if (selectedCategory == 4) {item {- RecordingDashboardSection(+ RecordingInfoCard(treeLabel = uiState.recordingStorageState.displayName,outputDirectory = uiState.recordingStorageState.outputDirectory,availableBytes = uiState.recordingStorageState.availableBytes,@@ -891,11 +893,20 @@ fun SettingsScreen(fileNamePattern = uiState.recordingStorageState.fileNamePattern,retentionDays = uiState.recordingStorageState.retentionDays,maxSimultaneousRecordings = uiState.recordingStorageState.maxSimultaneousRecordings,+ paddingBeforeMinutes = uiState.recordingPaddingBeforeMinutes,+ paddingAfterMinutes = uiState.recordingPaddingAfterMinutes+ )+ }+ item {+ RecordingActionsCard(+ wifiOnlyRecording = uiState.wifiOnlyRecording,+ onWifiOnlyRecordingChange = { viewModel.setRecordingWifiOnly(it) },onChooseFolder = { recordingFolderLauncher.launch(null) },onUseAppStorage = { viewModel.updateRecordingFolder(null, null) },onChangePattern = { showRecordingPatternDialog = true },onChangeRetention = { showRecordingRetentionDialog = true },onChangeConcurrency = { showRecordingConcurrencyDialog = true },+ onChangePadding = { showRecordingPaddingDialog = true },onRepairSchedule = { viewModel.reconcileRecordings() },onOpenBrowser = { showRecordingBrowserDialog = true })@@ -1087,8 +1098,8 @@ fun SettingsScreen(Routes.player(streamUrl = playbackUrl,title = item.programTitle ?: item.channelName,- internalId = -1L,- providerId = null,+ internalId = item.id.hashCode().toLong().and(0x7FFFFFFFL),+ providerId = item.providerId,contentType = "MOVIE",returnRoute = currentRoute)@@ -1097,6 +1108,7 @@ fun SettingsScreen(},onStop = { item -> viewModel.stopRecording(item.id) },onCancel = { item -> viewModel.cancelRecording(item.id) },+ onSkipOccurrence = { item -> viewModel.skipOccurrence(item.id) },onDelete = { item -> viewModel.deleteRecording(item.id) },onRetry = { item -> viewModel.retryRecording(item.id) },onToggleSchedule = { item, enabled ->@@ -1168,6 +1180,8 @@ fun SettingsScreen(onShowRecordingRetentionDialogChange = { showRecordingRetentionDialog = it },showRecordingConcurrencyDialog = showRecordingConcurrencyDialog,onShowRecordingConcurrencyDialogChange = { showRecordingConcurrencyDialog = it },+ showRecordingPaddingDialog = showRecordingPaddingDialog,+ onShowRecordingPaddingDialogChange = { showRecordingPaddingDialog = it },showClearHistoryDialog = showClearHistoryDialog,onShowClearHistoryDialogChange = { showClearHistoryDialog = it },showCreateCombinedDialog = showCreateCombinedDialog,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.ktindex 9ff92af6..fa17376f 100644--- 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.kt@@ -8,7 +8,10 @@ import androidx.compose.foundation.focusableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.paddingimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.remember@@ -102,6 +105,8 @@ internal fun SettingsScreenDialogs(onShowRecordingRetentionDialogChange: (Boolean) -> Unit,showRecordingConcurrencyDialog: Boolean,onShowRecordingConcurrencyDialogChange: (Boolean) -> Unit,+ showRecordingPaddingDialog: Boolean,+ onShowRecordingPaddingDialogChange: (Boolean) -> Unit,showClearHistoryDialog: Boolean,onShowClearHistoryDialogChange: (Boolean) -> Unit,showCreateCombinedDialog: Boolean,@@ -488,11 +493,21 @@ internal fun SettingsScreenDialogs(title = stringResource(R.string.settings_select_level),onDismiss = { onShowLevelDialogChange(false) }) {- LevelOption(0, stringResource(R.string.settings_level_off_desc), uiState.parentalControlLevel) {+ LevelOption(+ level = 0,+ text = stringResource(R.string.settings_level_off_desc),+ subtitle = stringResource(R.string.settings_level_off_subtitle),+ currentLevel = uiState.parentalControlLevel+ ) {viewModel.setParentalControlLevel(0)onShowLevelDialogChange(false)}- LevelOption(1, stringResource(R.string.settings_level_locked_desc), uiState.parentalControlLevel) {+ LevelOption(+ level = 1,+ text = stringResource(R.string.settings_level_locked_desc),+ subtitle = stringResource(R.string.settings_level_locked_subtitle),+ currentLevel = uiState.parentalControlLevel+ ) {if (uiState.hasParentalPin) {viewModel.setParentalControlLevel(1)} else {@@ -502,7 +517,12 @@ internal fun SettingsScreenDialogs(}onShowLevelDialogChange(false)}- LevelOption(2, stringResource(R.string.settings_level_hidden_desc), uiState.parentalControlLevel) {+ LevelOption(+ level = 2,+ text = stringResource(R.string.settings_level_private_desc),+ subtitle = stringResource(R.string.settings_level_private_subtitle),+ currentLevel = uiState.parentalControlLevel+ ) {if (uiState.hasParentalPin) {viewModel.setParentalControlLevel(2)} else {@@ -512,6 +532,21 @@ internal fun SettingsScreenDialogs(}onShowLevelDialogChange(false)}+ LevelOption(+ level = 3,+ text = stringResource(R.string.settings_level_hidden_desc),+ subtitle = stringResource(R.string.settings_level_hidden_subtitle),+ currentLevel = uiState.parentalControlLevel+ ) {+ if (uiState.hasParentalPin) {+ viewModel.setParentalControlLevel(3)+ } else {+ onPendingProtectionLevelChange(3)+ onPendingActionChange(ParentalAction.SetNewPin)+ onShowPinDialogChange(true)+ }+ onShowLevelDialogChange(false)+ }}}@@ -609,6 +644,56 @@ internal fun SettingsScreenDialogs(}}+ if (showRecordingPaddingDialog) {+ val paddingOptions = listOf(0, 1, 2, 3, 5, 10, 15, 30)+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_recording_padding_title),+ onDismiss = { onShowRecordingPaddingDialogChange(false) }+ ) {+ Text(+ text = stringResource(R.string.settings_recording_padding_before),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim,+ modifier = Modifier.padding(bottom = 4.dp)+ )+ paddingOptions.forEach { minutes ->+ LevelOption(+ level = minutes,+ text = if (minutes == 0) {+ stringResource(R.string.settings_recording_padding_none)+ } else {+ stringResource(R.string.settings_recording_padding_minutes, minutes)+ },+ currentLevel = uiState.recordingPaddingBeforeMinutes,+ onSelect = {+ viewModel.setRecordingPaddingBeforeMinutes(minutes)+ }+ )+ }+ Spacer(modifier = Modifier.height(12.dp))+ Text(+ text = stringResource(R.string.settings_recording_padding_after),+ style = MaterialTheme.typography.labelMedium,+ color = OnSurfaceDim,+ modifier = Modifier.padding(bottom = 4.dp)+ )+ paddingOptions.forEach { minutes ->+ LevelOption(+ level = minutes,+ text = if (minutes == 0) {+ stringResource(R.string.settings_recording_padding_none)+ } else {+ stringResource(R.string.settings_recording_padding_minutes, minutes)+ },+ currentLevel = uiState.recordingPaddingAfterMinutes,+ onSelect = {+ viewModel.setRecordingPaddingAfterMinutes(minutes)+ }+ )+ }+ }+ }+if (showClearHistoryDialog) {AlertDialog(onDismissRequest = { onShowClearHistoryDialogChange(false) },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 ebab238b..57afc6c3 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@@ -240,6 +240,24 @@ class SettingsViewModel @Inject constructor(}}+ viewModelScope.launch {+ preferencesRepository.recordingWifiOnly.collect { wifiOnly ->+ _uiState.update { it.copy(wifiOnlyRecording = wifiOnly) }+ }+ }++ viewModelScope.launch {+ preferencesRepository.recordingPaddingBeforeMinutes.collect { minutes ->+ _uiState.update { it.copy(recordingPaddingBeforeMinutes = minutes) }+ }+ }++ viewModelScope.launch {+ preferencesRepository.recordingPaddingAfterMinutes.collect { minutes ->+ _uiState.update { it.copy(recordingPaddingAfterMinutes = minutes) }+ }+ }+viewModelScope.launch {epgSourceRepository.getAllSources().collect { sources ->_uiState.update { it.copy(epgSources = sources) }@@ -476,6 +494,24 @@ class SettingsViewModel @Inject constructor(}}+ fun setRecordingWifiOnly(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setRecordingWifiOnly(enabled)+ }+ }++ fun setRecordingPaddingBeforeMinutes(minutes: Int) {+ viewModelScope.launch {+ preferencesRepository.setRecordingPaddingBeforeMinutes(minutes)+ }+ }++ fun setRecordingPaddingAfterMinutes(minutes: Int) {+ viewModelScope.launch {+ preferencesRepository.setRecordingPaddingAfterMinutes(minutes)+ }+ }+fun setPlayerDecoderMode(mode: DecoderMode) {viewModelScope.launch {preferencesRepository.setPlayerDecoderMode(mode)@@ -751,6 +787,10 @@ class SettingsViewModel @Inject constructor(recordingActions.cancelRecording(viewModelScope, recordingId)}+ fun skipOccurrence(recordingId: String) {+ recordingActions.skipOccurrence(viewModelScope, recordingId)+ }+fun deleteRecording(recordingId: String) {recordingActions.deleteRecording(viewModelScope, recordingId)}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.ktindex 4148da19..c996cb3b 100644--- 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.kt@@ -222,6 +222,9 @@ data class SettingsUiState(val backupImportPlan: BackupImportPlan = BackupImportPlan(),val recordingItems: List<RecordingItem> = emptyList(),val recordingStorageState: RecordingStorageState = RecordingStorageState(),+ val wifiOnlyRecording: Boolean = false,+ val recordingPaddingBeforeMinutes: Int = 0,+ val recordingPaddingAfterMinutes: Int = 0,val isIncognitoMode: Boolean = false,val useXtreamTextClassification: Boolean = true,val xtreamBase64TextCompatibility: Boolean = false,diff --git a/app/src/main/res/drawable-hdpi/app_banner.png b/app/src/main/res/drawable-hdpi/app_banner.pngnew file mode 100644index 00000000..72975ce7Binary files /dev/null and b/app/src/main/res/drawable-hdpi/app_banner.png differdiff --git a/app/src/main/res/drawable-mdpi/app_banner.png b/app/src/main/res/drawable-mdpi/app_banner.pngnew file mode 100644index 00000000..69d776ffBinary files /dev/null and b/app/src/main/res/drawable-mdpi/app_banner.png differdiff --git a/app/src/main/res/drawable-xhdpi/app_banner.png b/app/src/main/res/drawable-xhdpi/app_banner.pngnew file mode 100644index 00000000..37528d6dBinary files /dev/null and b/app/src/main/res/drawable-xhdpi/app_banner.png differdiff --git a/app/src/main/res/drawable-xxhdpi/app_banner.png b/app/src/main/res/drawable-xxhdpi/app_banner.pngnew file mode 100644index 00000000..61aafa6bBinary files /dev/null and b/app/src/main/res/drawable-xxhdpi/app_banner.png differdiff --git a/app/src/main/res/drawable-xxxhdpi/app_banner.png b/app/src/main/res/drawable-xxxhdpi/app_banner.pngnew file mode 100644index 00000000..78f8a8abBinary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/app_banner.png differdiff --git a/app/src/main/res/drawable/app_banner.png b/app/src/main/res/drawable/app_banner.pngindex 5e3fce46..37528d6d 100644Binary files a/app/src/main/res/drawable/app_banner.png and b/app/src/main/res/drawable/app_banner.png differdiff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex dc75ef5d..b8979389 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -506,12 +506,18 @@<string name="settings_enter_pin">Enter PIN</string><string name="settings_select_level">Select Protection Level</string><string name="settings_level_off_desc">OFF - No restrictions</string>+ <string name="settings_level_off_subtitle">Adult content appears everywhere.</string><string name="settings_level_locked_desc">LOCKED - Content visible, PIN required</string>+ <string name="settings_level_locked_subtitle">Categories visible with PIN. Adult content shown in all views.</string>+ <string name="settings_level_private_desc">PRIVATE - Categories locked, hidden from feeds</string>+ <string name="settings_level_private_subtitle">Categories visible with PIN. Hidden from Search, EPG, All Channels and Recent.</string><string name="settings_level_hidden_desc">HIDDEN - Content hidden from all lists</string>+ <string name="settings_level_hidden_subtitle">Adult categories not shown anywhere.</string><string name="settings_cancel">Cancel</string><string name="settings_protection_level">Protection Level</string><string name="settings_level_off">OFF</string><string name="settings_level_locked">LOCKED</string>+ <string name="settings_level_private">PRIVATE</string><string name="settings_level_hidden">HIDDEN</string><string name="settings_level_unknown">UNKNOWN</string><string name="settings_change">Change</string>@@ -627,6 +633,9 @@<string name="settings_recording_deleted">Recording deleted</string><string name="settings_recording_stop_failed">Stop failed: %1$s</string><string name="settings_recording_cancel_failed">Cancel failed: %1$s</string>+ <string name="settings_recording_skip">Skip This Occurrence</string>+ <string name="settings_recording_skipped">Occurrence skipped</string>+ <string name="settings_recording_skip_failed">Skip failed: %1$s</string><string name="settings_recording_delete_failed">Delete failed: %1$s</string><string name="settings_recording_retry">Retry</string><string name="settings_recording_enable">Enable</string>@@ -637,6 +646,12 @@<string name="settings_recording_schedule_disabled">Recording schedule disabled</string><string name="settings_recording_schedule_toggle_failed">Schedule update failed: %1$s</string><string name="settings_recording_reconcile">Repair Schedule</string>+ <string name="settings_recording_wifi_only">Record on Wi-Fi only</string>+ <string name="settings_recording_padding_title">Recording Padding</string>+ <string name="settings_recording_padding_before">Start Early</string>+ <string name="settings_recording_padding_after">End Late</string>+ <string name="settings_recording_padding_none">None</string>+ <string name="settings_recording_padding_minutes">%1$d min</string><string name="settings_recording_reconcile_complete">Recording schedule repaired</string><string name="settings_recording_reconcile_failed">Repair failed: %1$s</string><string name="settings_recording_choose_folder">Choose Folder</string>@@ -986,6 +1001,13 @@<string name="epg_program_details_show">Program Details</string><string name="epg_program_details_hide">Hide Details</string><string name="epg_program_reminder_set">Remind Me</string>+ <string name="epg_schedule_recording">Record</string>+ <string name="epg_schedule_daily_recording">Record Daily</string>+ <string name="epg_schedule_weekly_recording">Record Weekly</string>+ <string name="epg_recording_conflict_title">Recording Conflict</string>+ <string name="epg_recording_conflict_body">\"%1$s\" conflicts with: %2$s. Replace the conflicting recording(s)?</string>+ <string name="epg_recording_conflict_replace">Replace</string>+ <string name="epg_recording_conflict_cancel">Cancel</string><string name="epg_program_reminder_cancel">Cancel Reminder</string><string name="epg_program_reminder_loading">Updating Reminder...</string><string name="epg_hero_no_schedule_hint">This channel has no guide entries in the current window.</string>@@ -1242,6 +1264,8 @@<string name="label_tv">TV</string><string name="badge_saved">SAVED</string><string name="badge_catch_up">CATCH UP</string>+ <string name="badge_recording">REC</string>+ <string name="badge_scheduled">SCHED</string><string name="badge_moving">MOVING</string><string name="badge_fav">FAV</string><string name="badge_error">ERR</string>diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/38.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/38.jsonnew file mode 100644index 00000000..d7892846--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/38.json@@ -0,0 +1,4052 @@+{+ "formatVersion": 1,+ "database": {+ "version": 38,+ "identityHash": "169d96c0c53479ea0410496874769635",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "series_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '169d96c0c53479ea0410496874769635')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.ktindex 70d7bc7a..0559c935 100644--- a/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt+++ b/data/src/main/java/com/streamvault/data/epg/EpgResolutionEngine.kt@@ -77,13 +77,13 @@ class EpgResolutionEngine @Inject constructor(}// Build lookup indexes for fast matching- // sourceId -> (xmltvChannelId -> EpgChannelEntity)- val exactIdIndex = mutableMapOf<Long, Map<String, String>>()+ // sourceId -> set of trimmed xmltvChannelIds for existence checks+ val exactIdIndex = mutableMapOf<Long, Set<String>>()// sourceId -> (normalizedName -> xmltvChannelId)val nameIndex = mutableMapOf<Long, Map<String, String>>()for ((sourceId, epgChannels) in epgChannelsBySource) {- exactIdIndex[sourceId] = epgChannels.associate { it.xmltvChannelId to it.xmltvChannelId }+ exactIdIndex[sourceId] = epgChannels.map { it.xmltvChannelId.trim() }.toHashSet()// For name index, first occurrence wins (avoids ambiguity)val nameMap = mutableMapOf<String, String>()for (ch in epgChannels) {@@ -200,6 +200,11 @@ class EpgResolutionEngine @Inject constructor(// 5. No EPGunresolvedCount+++ Log.v(TAG, "Unresolved: channel=${channel.name} (id=${channel.id}), " ++ "epgId=${channelEpgId ?: "null"}, " ++ "normalizedName=$channelNormalizedName, " ++ "idInAnySource=${enabledAssignments.any { channelEpgId != null && channelEpgId in (exactIdIndex[it.epgSourceId] ?: emptySet()) }}, " ++ "nameInAnySource=${enabledAssignments.any { channelNormalizedName in (nameIndex[it.epgSourceId] ?: emptyMap()) }}")ChannelEpgMappingEntity(providerChannelId = channel.id,providerId = providerId,@@ -216,6 +221,7 @@ class EpgResolutionEngine @Inject constructor(}channelEpgMappingDao.replaceForProvider(providerId, mappings)+ channelDao.backfillEpgIcons(providerId)val summary = EpgResolutionSummary(totalChannels = channels.size,diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex ffdf609b..5442c092 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -45,7 +45,7 @@ import com.streamvault.data.local.entity.*ProgramReminderEntity::class,RecordingStorageEntity::class],- version = 37,+ version = 38,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -1810,5 +1810,12 @@ abstract class StreamVaultDatabase : RoomDatabase() {validateForeignKeys(database)}}++ val MIGRATION_37_38 = object : Migration(37, 38) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL("ALTER TABLE epg_sources ADD COLUMN etag TEXT DEFAULT NULL")+ database.execSQL("ALTER TABLE epg_sources ADD COLUMN last_modified_header TEXT DEFAULT NULL")+ }+ }}}diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex 507178d2..771d04e8 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -532,6 +532,7 @@ interface CatalogSyncDao {youtube_trailer,provider_id,watch_progress,+ watch_count,last_watched_at,is_adult,is_user_protected,@@ -561,6 +562,7 @@ interface CatalogSyncDao {stage.provider_id,0,0,+ 0,stage.is_adult,0,stage.sync_fingerprint,diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex e238e0cb..55a714c6 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -255,6 +255,21 @@ abstract class ChannelDao {@Query("UPDATE channels SET error_count = 0 WHERE id = :id")abstract suspend fun resetErrorCount(id: Long)++ @Query("""+ UPDATE channels SET logo_url = (+ SELECT ec.icon_url+ FROM channel_epg_mappings cem+ JOIN epg_channels ec ON ec.epg_source_id = cem.epg_source_id+ AND ec.xmltv_channel_id = cem.xmltv_channel_id+ WHERE cem.provider_channel_id = channels.id+ AND cem.provider_id = :providerId+ AND ec.icon_url IS NOT NULL AND ec.icon_url != ''+ LIMIT 1+ )+ WHERE provider_id = :providerId AND (logo_url IS NULL OR logo_url = '')+ """)+ abstract suspend fun backfillEpgIcons(providerId: Long)}@Dao@@ -2012,8 +2027,8 @@ interface ProgramDao {AND programs.end_time > :startTimeAND programs.start_time < :endTimeAND (- programs.title LIKE :queryPattern- OR programs.description LIKE :queryPattern+ programs.title LIKE :queryPattern ESCAPE '\'+ OR programs.description LIKE :queryPattern ESCAPE '\')AND (:categoryId IS NULL@@ -2442,8 +2457,14 @@ interface EpgSourceDao {@Query("UPDATE epg_sources SET last_refresh_at = :at, last_error = :error, updated_at = :at WHERE id = :id")suspend fun updateRefreshStatus(id: Long, at: Long, error: String?)+ @Query("UPDATE epg_sources SET last_error = :error, updated_at = :at WHERE id = :id")+ suspend fun updateRefreshError(id: Long, error: String?, at: Long = System.currentTimeMillis())+@Query("UPDATE epg_sources SET last_refresh_at = :at, last_success_at = :at, last_error = NULL, updated_at = :at WHERE id = :id")suspend fun updateRefreshSuccess(id: Long, at: Long)++ @Query("UPDATE epg_sources SET etag = :etag, last_modified_header = :lastModified WHERE id = :id")+ suspend fun updateConditionalHeaders(id: Long, etag: String?, lastModified: String?)}@Dao@@ -2515,6 +2536,17 @@ interface EpgChannelDao {@Query("SELECT * FROM epg_channels WHERE epg_source_id = :sourceId ORDER BY display_name ASC")suspend fun getBySource(sourceId: Long): List<EpgChannelEntity>+ @Query("""+ SELECT * FROM epg_channels+ WHERE epg_source_id = :sourceId+ AND (xmltv_channel_id LIKE :pattern ESCAPE '\'+ OR display_name LIKE :pattern ESCAPE '\'+ OR normalized_name LIKE :pattern ESCAPE '\')+ ORDER BY display_name ASC+ LIMIT :limit+ """)+ suspend fun searchBySource(sourceId: Long, pattern: String, limit: Int): List<EpgChannelEntity>+@Query("SELECT * FROM epg_channels WHERE epg_source_id = :sourceId AND xmltv_channel_id = :channelId LIMIT 1")suspend fun getBySourceAndChannelId(sourceId: Long, channelId: String): EpgChannelEntity?@@ -2526,6 +2558,9 @@ interface EpgChannelDao {@Query("DELETE FROM epg_channels WHERE epg_source_id = :sourceId")suspend fun deleteBySource(sourceId: Long)++ @Query("UPDATE epg_channels SET epg_source_id = :newSourceId WHERE epg_source_id = :oldSourceId")+ suspend fun moveToSource(oldSourceId: Long, newSourceId: Long)}@Dao@@ -2556,6 +2591,9 @@ interface EpgProgrammeDao {@Query("DELETE FROM epg_programmes WHERE epg_source_id = :sourceId")suspend fun deleteBySource(sourceId: Long)+ @Query("UPDATE epg_programmes SET epg_source_id = :newSourceId WHERE epg_source_id = :oldSourceId")+ suspend fun moveToSource(oldSourceId: Long, newSourceId: Long)+@Query("DELETE FROM epg_programmes WHERE end_time < :beforeTime")suspend fun deleteOld(beforeTime: Long): Intdiff --git a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.ktindex 208f7317..e50debde 100644--- a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt@@ -100,6 +100,46 @@ interface RecordingRunDao {@Query("SELECT * FROM recording_runs WHERE status = 'RECORDING'")suspend fun getRecordingRuns(): List<RecordingRunEntity>++ @Query(+ """+ SELECT * FROM recording_runs+ WHERE status IN ('COMPLETED', 'FAILED', 'CANCELLED')+ AND terminal_at_ms IS NOT NULL+ AND terminal_at_ms < :thresholdMs+ ORDER BY terminal_at_ms ASC+ """+ )+ suspend fun getExpiredRuns(thresholdMs: Long): List<RecordingRunEntity>++ @Query(+ """+ SELECT * FROM recording_runs+ WHERE recurring_rule_id = :recurringRuleId+ AND status = 'SCHEDULED'+ """+ )+ suspend fun getScheduledByRecurringRuleId(recurringRuleId: String): List<RecordingRunEntity>++ @Query(+ """+ UPDATE recording_runs+ SET bytes_written = :bytesWritten,+ average_throughput_bps = :averageThroughputBytesPerSecond,+ retry_count = MAX(retry_count, :retryCount),+ last_progress_at_ms = :lastProgressAtMs,+ updated_at = :updatedAt+ WHERE id = :id+ """+ )+ suspend fun updateProgress(+ id: String,+ bytesWritten: Long,+ averageThroughputBytesPerSecond: Long,+ retryCount: Int,+ lastProgressAtMs: Long,+ updatedAt: Long+ )}@Daodiff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex 100f34ac..79821579 100644--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt@@ -32,7 +32,7 @@ data class ProviderEntity(@ColumnInfo(name = "allowed_output_formats_json") val allowedOutputFormatsJson: String = "[]",@ColumnInfo(name = "epg_sync_mode") val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,@ColumnInfo(name = "xtream_fast_sync_enabled") val xtreamFastSyncEnabled: Boolean = false,- @ColumnInfo(name = "m3u_vod_classification_enabled") val m3uVodClassificationEnabled: Boolean = true,+ @ColumnInfo(name = "m3u_vod_classification_enabled") val m3uVodClassificationEnabled: Boolean = false,val status: ProviderStatus = ProviderStatus.UNKNOWN,@ColumnInfo(name = "last_synced_at") val lastSyncedAt: Long = 0,@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()@@ -788,7 +788,9 @@ data class EpgSourceEntity(@ColumnInfo(name = "last_error") val lastError: String? = null,val priority: Int = 0,@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),- @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis(),+ val etag: String? = null,+ @ColumnInfo(name = "last_modified_header") val lastModifiedHeader: String? = null)// ── Provider ↔ EPG Source Assignment ───────────────────────────────diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex 2c9f45ab..2c6bb70c 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -1,6 +1,8 @@package com.streamvault.data.managerimport android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilitiesimport android.util.Logimport com.google.gson.Gsonimport com.google.gson.reflect.TypeToken@@ -20,6 +22,7 @@ import com.streamvault.data.manager.recording.RecordingSourceResolverimport com.streamvault.data.manager.recording.ResolvedRecordingSourceimport com.streamvault.data.manager.recording.TsPassThroughCaptureEngineimport com.streamvault.data.manager.recording.UnsupportedRecordingException+import com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.manager.recording.asPersistenceValuesimport com.streamvault.data.manager.recording.createOutputTargetimport com.streamvault.data.manager.recording.deleteOutputTarget@@ -55,6 +58,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launchimport kotlinx.coroutines.sync.Mutex@@ -62,6 +66,9 @@ import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextprivate const val TAG = "RecordingManager"+private const val MIN_FREE_SPACE_BYTES = 512L * 1024L * 1024L // 512 MB+private const val FAILURE_NOTIFICATION_CHANNEL_ID = "streamvault_recording_failure"+private const val FAILURE_NOTIFICATION_ID_BASE = 5000@Singletonclass RecordingManagerImpl @Inject constructor(@@ -74,12 +81,14 @@ class RecordingManagerImpl @Inject constructor(private val recordingSourceResolver: RecordingSourceResolver,private val tsPassThroughCaptureEngine: TsPassThroughCaptureEngine,private val hlsLiveCaptureEngine: HlsLiveCaptureEngine,- private val alarmScheduler: RecordingAlarmScheduler+ private val alarmScheduler: RecordingAlarmScheduler,+ private val preferencesRepository: PreferencesRepository) : RecordingManager {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)private val activeJobs = mutableMapOf<String, Job>()private val activeJobsMutex = Mutex()+ private val recordingMutex = Mutex()private val legacyStateFile by lazy { File(File(context.filesDir, "recordings"), "recordings_state.json") }init {@@ -90,6 +99,26 @@ class RecordingManagerImpl @Inject constructor(}}+ private fun isOnWifi(): Boolean {+ val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return false+ val network = cm.activeNetwork ?: return false+ val caps = cm.getNetworkCapabilities(network) ?: return false+ return caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||+ caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)+ }++ private suspend fun resolveMaxVideoHeightForCurrentNetwork(): Int? {+ val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager+ val caps = cm?.activeNetwork?.let { cm.getNetworkCapabilities(it) }+ return when {+ caps?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) == true ->+ preferencesRepository.playerEthernetMaxVideoHeight.first()+ caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true ->+ preferencesRepository.playerWifiMaxVideoHeight.first()+ else -> null+ }+ }+override fun observeRecordingItems(): Flow<List<RecordingItem>> =recordingRunDao.observeAll().map { runs -> runs.map { it.toDomain() } }@@ -104,8 +133,6 @@ class RecordingManagerImpl @Inject constructor(if (!storage.isWritable) {return@withContext Result.error("Recording storage is not writable.")}- validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)- ?.let { return@withContext Result.error(it) }val scheduleId = recordingScheduleDao.insert(RecordingScheduleEntity(@@ -151,7 +178,7 @@ class RecordingManagerImpl @Inject constructor(status = RecordingStatus.RECORDING,sourceType = source.sourceType,resolvedUrl = source.url,- headersJson = headersToJson(gson, source.headers),+ headersJson = headersToJson(source.headers),userAgent = source.userAgent,expirationTime = source.expirationTime,providerLabel = source.providerLabel,@@ -164,11 +191,20 @@ class RecordingManagerImpl @Inject constructor(createdAt = now,updatedAt = now)- recordingRunDao.insert(run)++ recordingMutex.withLock {+ validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ ?.let { return@withContext Result.error(it) }+ recordingRunDao.insert(run)+ }+alarmScheduler.scheduleStop(recordingId, request.scheduledEndMs)when (val startResult = startCapture(run)) {is Result.Success -> Unit- is Result.Error -> throw IllegalStateException(startResult.message, startResult.exception)+ is Result.Error -> {+ markRunFailed(run.id, startResult.message ?: "Capture failed to start.", inferFailureCategory(startResult.exception))+ throw IllegalStateException(startResult.message, startResult.exception)+ }Result.Loading -> Unit}run.toStandaloneDomain()@@ -184,8 +220,6 @@ class RecordingManagerImpl @Inject constructor(if (!storage.isWritable) {return@withContext Result.error("Recording storage is not writable.")}- validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)- ?.let { return@withContext Result.error(it) }val recurringRuleId = request.recurringRuleId?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() }@@ -209,7 +243,13 @@ class RecordingManagerImpl @Inject constructor(scheduleId = scheduleId,request = request.copy(recurringRuleId = recurringRuleId))- recordingRunDao.insert(run)++ recordingMutex.withLock {+ validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ ?.let { return@withContext Result.error(it) }+ recordingRunDao.insert(run)+ }+alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)run.toStandaloneDomain()}.fold(@@ -223,9 +263,14 @@ class RecordingManagerImpl @Inject constructor(cancelActiveJob(recordingId)alarmScheduler.cancel(recordingId)val now = System.currentTimeMillis()+ val newStatus = when {+ run.status == RecordingStatus.RECORDING -> RecordingStatus.COMPLETED+ run.status == RecordingStatus.SCHEDULED -> RecordingStatus.CANCELLED+ else -> RecordingStatus.CANCELLED+ }recordingRunDao.update(run.copy(- status = if (run.bytesWritten > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,+ status = newStatus,endedAtMs = now,terminalAtMs = now,updatedAt = now@@ -251,9 +296,111 @@ class RecordingManagerImpl @Inject constructor(recordingScheduleDao.getById(run.scheduleId)?.let { schedule ->recordingScheduleDao.update(schedule.copy(enabled = false, updatedAt = now))}+ run.recurringRuleId?.let { ruleId ->+ recordingRunDao.getScheduledByRecurringRuleId(ruleId).forEach { pendingRun ->+ if (pendingRun.id != recordingId) {+ alarmScheduler.cancel(pendingRun.id)+ recordingRunDao.update(+ pendingRun.copy(+ status = RecordingStatus.CANCELLED,+ terminalAtMs = now,+ endedAtMs = now,+ scheduleEnabled = false,+ updatedAt = now+ )+ )+ }+ }+ }+ Result.success(Unit)+ }++ override suspend fun skipOccurrence(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ if (run.status != RecordingStatus.SCHEDULED) {+ return@withContext Result.error("Only scheduled recordings can be skipped.")+ }+ cancelActiveJob(recordingId)+ alarmScheduler.cancel(recordingId)+ val now = System.currentTimeMillis()+ recordingRunDao.update(+ run.copy(+ status = RecordingStatus.CANCELLED,+ failureReason = "Skipped by user",+ terminalAtMs = now,+ endedAtMs = now,+ updatedAt = now+ )+ )Result.success(Unit)}+ override suspend fun getConflictingRecordings(startMs: Long, endMs: Long, providerId: Long): List<RecordingItem> = withContext(Dispatchers.IO) {+ recordingRunDao.getOverlapping(startMs, endMs)+ .filter { it.status == RecordingStatus.SCHEDULED || it.status == RecordingStatus.RECORDING }+ .filter { it.scheduleEnabled }+ .map { it.toStandaloneDomain() }+ }++ override suspend fun forceScheduleRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {+ runCatching {+ val storage = ensureStorageStateSync()+ if (!storage.isWritable) {+ return@withContext Result.error("Recording storage is not writable.")+ }++ val recurringRuleId = request.recurringRuleId+ ?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() }+ val scheduleId = recordingScheduleDao.insert(+ RecordingScheduleEntity(+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ requestedStartMs = request.scheduledStartMs,+ requestedEndMs = request.scheduledEndMs,+ recurrence = request.recurrence,+ recurringRuleId = recurringRuleId,+ enabled = true,+ isManual = false,+ priority = request.priority+ )+ )+ val run = createPendingRun(+ scheduleId = scheduleId,+ request = request.copy(recurringRuleId = recurringRuleId)+ )++ recordingMutex.withLock {+ val overlapping = recordingRunDao.getOverlapping(request.scheduledStartMs, request.scheduledEndMs)+ .filter { it.status == RecordingStatus.SCHEDULED || it.status == RecordingStatus.RECORDING }+ .filter { it.scheduleEnabled }+ for (conflict in overlapping) {+ cancelActiveJob(conflict.id)+ alarmScheduler.cancel(conflict.id)+ val now = System.currentTimeMillis()+ recordingRunDao.update(+ conflict.copy(+ status = RecordingStatus.CANCELLED,+ failureReason = "Replaced by ${request.programTitle ?: request.channelName}",+ terminalAtMs = now,+ endedAtMs = now,+ updatedAt = now+ )+ )+ }+ recordingRunDao.insert(run)+ }++ alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ run.toStandaloneDomain()+ }.fold(+ onSuccess = { Result.success(it) },+ onFailure = { error -> Result.error(error.message ?: "Failed to force-schedule recording", error) }+ )+ }+override suspend fun deleteRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")if (run.status == RecordingStatus.SCHEDULED || run.status == RecordingStatus.RECORDING) {@@ -265,26 +412,57 @@ class RecordingManagerImpl @Inject constructor(}override suspend fun retryRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")- val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")- val retriedRun = createPendingRun(- scheduleId = schedule.id,- request = RecordingRequest(- providerId = schedule.providerId,- channelId = schedule.channelId,- channelName = schedule.channelName,- streamUrl = schedule.streamUrl,- scheduledStartMs = maxOf(System.currentTimeMillis() + 2_000L, schedule.requestedStartMs),- scheduledEndMs = schedule.requestedEndMs,- programTitle = schedule.programTitle,- recurrence = schedule.recurrence,- recurringRuleId = schedule.recurringRuleId,- priority = schedule.priority- )+ runCatching {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")+ val now = System.currentTimeMillis()+ val retryStartMs = maxOf(now + 2_000L, schedule.requestedStartMs)+ val retryEndMs = maxOf(schedule.requestedEndMs, retryStartMs + 60_000L)+ val retryRecurrence = if (schedule.enabled) schedule.recurrence else RecordingRecurrence.NONE+ val retryRuleId = if (schedule.enabled) schedule.recurringRuleId else null+ if (schedule.requestedEndMs <= now) {+ val remainingDuration = schedule.requestedEndMs - schedule.requestedStartMs+ val newEndMs = retryStartMs + remainingDuration.coerceAtLeast(60_000L)+ val retriedRun = createPendingRun(+ scheduleId = schedule.id,+ request = RecordingRequest(+ providerId = schedule.providerId,+ channelId = schedule.channelId,+ channelName = schedule.channelName,+ streamUrl = schedule.streamUrl,+ scheduledStartMs = retryStartMs,+ scheduledEndMs = newEndMs,+ programTitle = schedule.programTitle,+ recurrence = retryRecurrence,+ recurringRuleId = retryRuleId,+ priority = schedule.priority+ )+ )+ recordingRunDao.insert(retriedRun)+ alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)+ } else {+ val retriedRun = createPendingRun(+ scheduleId = schedule.id,+ request = RecordingRequest(+ providerId = schedule.providerId,+ channelId = schedule.channelId,+ channelName = schedule.channelName,+ streamUrl = schedule.streamUrl,+ scheduledStartMs = retryStartMs,+ scheduledEndMs = retryEndMs,+ programTitle = schedule.programTitle,+ recurrence = retryRecurrence,+ recurringRuleId = retryRuleId,+ priority = schedule.priority+ )+ )+ recordingRunDao.insert(retriedRun)+ alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)+ }+ }.fold(+ onSuccess = { Result.success(Unit) },+ onFailure = { error -> Result.error(error.message ?: "Failed to retry recording", error) })- recordingRunDao.insert(retriedRun)- alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)- Result.success(Unit)}override suspend fun setScheduleEnabled(recordingId: String, enabled: Boolean): Result<Unit> = withContext(Dispatchers.IO) {@@ -298,6 +476,18 @@ class RecordingManagerImpl @Inject constructor(} else {alarmScheduler.cancel(run.id)}+ if (!enabled) {+ run.recurringRuleId?.let { ruleId ->+ recordingRunDao.getScheduledByRecurringRuleId(ruleId).forEach { pendingRun ->+ if (pendingRun.id != recordingId) {+ alarmScheduler.cancel(pendingRun.id)+ recordingRunDao.update(+ pendingRun.copy(scheduleEnabled = false, updatedAt = now)+ )+ }+ }+ }+ }Result.success(Unit)}@@ -318,6 +508,7 @@ class RecordingManagerImpl @Inject constructor(override suspend fun reconcileRecordingState(): Result<Unit> = withContext(Dispatchers.IO) {runCatching<Unit> {ensureStorageState()+ pruneExpiredRecordings()recordingRunDao.getAlarmManagedScheduledRuns().filter { it.scheduleEnabled && it.status == RecordingStatus.SCHEDULED }.forEach { run ->@@ -341,46 +532,57 @@ class RecordingManagerImpl @Inject constructor(}override suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")- when (run.status) {- RecordingStatus.RECORDING -> startCapture(run)- RecordingStatus.SCHEDULED -> {- val source = resolveRecordableSource(run.providerId, run.channelId, run.streamUrl)- val storage = ensureStorageStateSync()- if (!storage.isWritable) {- return@withContext Result.error("Recording storage is not writable.")- }- val outputTarget = if (!run.outputUri.isNullOrBlank() || !run.outputDisplayPath.isNullOrBlank()) {- existingOutputTarget(run)- } else {- createOutputTarget(- context = context,- storage = storage,- fileName = sanitizeRecordingFileName(run.channelName, run.programTitle, run.scheduledStartMs, storage.fileNamePattern)+ recordingMutex.withLock {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ when (run.status) {+ RecordingStatus.RECORDING -> startCapture(run)+ RecordingStatus.SCHEDULED -> {+ val source = resolveRecordableSource(run.providerId, run.channelId, run.streamUrl)+ val storage = ensureStorageStateSync()+ if (!storage.isWritable) {+ return@withContext Result.error("Recording storage is not writable.")+ }+ val availableBytes = storage.availableBytes+ if (availableBytes != null && availableBytes < MIN_FREE_SPACE_BYTES) {+ markRunFailed(run.id, "Insufficient disk space (${availableBytes / 1_048_576} MB free, ${MIN_FREE_SPACE_BYTES / 1_048_576} MB required).", RecordingFailureCategory.STORAGE)+ return@withContext Result.error("Not enough disk space to start recording.")+ }+ if (preferencesRepository.recordingWifiOnly.first() && !isOnWifi()) {+ markRunFailed(run.id, "Recording requires Wi-Fi but device is not on Wi-Fi.", RecordingFailureCategory.NETWORK)+ return@withContext Result.error("Recording requires Wi-Fi connection.")+ }+ val outputTarget = if (!run.outputUri.isNullOrBlank() || !run.outputDisplayPath.isNullOrBlank()) {+ existingOutputTarget(run)+ } else {+ createOutputTarget(+ context = context,+ storage = storage,+ fileName = sanitizeRecordingFileName(run.channelName, run.programTitle, run.scheduledStartMs, storage.fileNamePattern)+ )+ }+ val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()+ val now = System.currentTimeMillis()+ val updatedRun = run.copy(+ status = RecordingStatus.RECORDING,+ sourceType = source.sourceType,+ resolvedUrl = source.url,+ headersJson = headersToJson(source.headers),+ userAgent = source.userAgent,+ expirationTime = source.expirationTime,+ providerLabel = source.providerLabel,+ outputUri = outputUri ?: run.outputUri,+ outputDisplayPath = outputDisplayPath ?: run.outputDisplayPath,+ startedAtMs = now,+ updatedAt = now,+ alarmStopAtMs = run.scheduledEndMs)+ recordingRunDao.update(updatedRun)+ alarmScheduler.scheduleStop(updatedRun.id, updatedRun.scheduledEndMs)+ recordingMutex.withLock { spawnNextRecurringRunIfNeeded(updatedRun) }+ startCapture(updatedRun)}- val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()- val now = System.currentTimeMillis()- val updatedRun = run.copy(- status = RecordingStatus.RECORDING,- sourceType = source.sourceType,- resolvedUrl = source.url,- headersJson = headersToJson(gson, source.headers),- userAgent = source.userAgent,- expirationTime = source.expirationTime,- providerLabel = source.providerLabel,- outputUri = outputUri ?: run.outputUri,- outputDisplayPath = outputDisplayPath ?: run.outputDisplayPath,- startedAtMs = now,- updatedAt = now,- alarmStopAtMs = run.scheduledEndMs- )- recordingRunDao.update(updatedRun)- alarmScheduler.scheduleStop(updatedRun.id, updatedRun.scheduledEndMs)- spawnNextRecurringRunIfNeeded(updatedRun)- startCapture(updatedRun)+ else -> Result.error("Recording is no longer active.")}- else -> Result.error("Recording is no longer active.")}}@@ -397,7 +599,7 @@ class RecordingManagerImpl @Inject constructor(val source = ResolvedRecordingSource(url = run.resolvedUrl ?: return Result.error("Recording stream URL could not be resolved."),sourceType = run.sourceType,- headers = headersFromJson(gson, run.headersJson),+ headers = headersFromJson(run.headersJson),userAgent = run.userAgent,expirationTime = run.expirationTime,providerLabel = run.providerLabel@@ -408,6 +610,7 @@ class RecordingManagerImpl @Inject constructor(RecordingSourceType.UNKNOWN -> tsPassThroughCaptureEngineRecordingSourceType.DASH -> return Result.error("DASH live recording is not supported yet.")}+ val maxVideoHeight = resolveMaxVideoHeightForCurrentNetwork()val job = scope.launch {try {engine.capture(@@ -415,7 +618,8 @@ class RecordingManagerImpl @Inject constructor(outputTarget = target,contentResolver = context.contentResolver,scheduledEndMs = run.scheduledEndMs,- onProgress = { progress -> updateRunProgress(run.id, progress) }+ onProgress = { progress -> updateRunProgress(run.id, progress) },+ maxVideoHeight = maxVideoHeight)completeRun(run.id)} catch (cancelled: CancellationException) {@@ -423,7 +627,7 @@ class RecordingManagerImpl @Inject constructor(} catch (unsupported: UnsupportedRecordingException) {markRunFailed(run.id, unsupported.message ?: "Recording format is unsupported.", unsupported.category)} catch (error: Throwable) {- markRunFailed(run.id, error.message ?: "Recording failed.", inferFailureCategory(error.message))+ markRunFailed(run.id, error.message ?: "Recording failed.", inferFailureCategory(error))} finally {removeActiveJob(run.id)onCaptureFinished(run.id)@@ -475,7 +679,7 @@ class RecordingManagerImpl @Inject constructor(scheduledEndMs = item.scheduledEndMs,recurrence = item.recurrence,recurringRuleId = item.recurringRuleId,- status = item.status,+ status = if (item.status == RecordingStatus.RECORDING) RecordingStatus.FAILED else item.status,sourceType = item.sourceType,outputUri = item.outputUri,outputDisplayPath = item.outputDisplayPath ?: item.outputPath,@@ -483,11 +687,11 @@ class RecordingManagerImpl @Inject constructor(averageThroughputBytesPerSecond = item.averageThroughputBytesPerSecond,retryCount = item.retryCount,lastProgressAtMs = item.lastProgressAtMs,- failureCategory = item.failureCategory,- failureReason = item.failureReason,- terminalAtMs = item.terminalAtMs,+ failureCategory = if (item.status == RecordingStatus.RECORDING) RecordingFailureCategory.UNKNOWN else item.failureCategory,+ failureReason = if (item.status == RecordingStatus.RECORDING) "Recording was interrupted during migration." else item.failureReason,+ terminalAtMs = if (item.status == RecordingStatus.RECORDING) System.currentTimeMillis() else item.terminalAtMs,startedAtMs = item.scheduledStartMs,- endedAtMs = item.terminalAtMs,+ endedAtMs = if (item.status == RecordingStatus.RECORDING) System.currentTimeMillis() else item.terminalAtMs,scheduleEnabled = item.scheduleEnabled,priority = item.priority)@@ -521,6 +725,21 @@ class RecordingManagerImpl @Inject constructor().also { recordingStorageDao.upsert(it) }}+ private suspend fun pruneExpiredRecordings() {+ val storage = recordingStorageDao.get() ?: return+ val retentionDays = storage.retentionDays ?: return+ if (retentionDays <= 0) return+ val thresholdMs = System.currentTimeMillis() - retentionDays.toLong() * 86_400_000L+ val expired = recordingRunDao.getExpiredRuns(thresholdMs)+ expired.forEach { run ->+ deleteOutputTarget(context, run.outputUri, run.outputDisplayPath)+ recordingRunDao.delete(run.id)+ }+ if (expired.isNotEmpty()) {+ Log.i(TAG, "Pruned ${expired.size} recording(s) older than $retentionDays days")+ }+ }+private suspend fun resolveRecordableSource(providerId: Long, channelId: Long, streamUrl: String): ResolvedRecordingSource {val source = recordingSourceResolver.resolveLiveSource(providerId, channelId, streamUrl)return when (source.sourceType) {@@ -530,15 +749,13 @@ class RecordingManagerImpl @Inject constructor(}private suspend fun updateRunProgress(recordingId: String, progress: CaptureProgress) {- val run = recordingRunDao.getById(recordingId) ?: return- recordingRunDao.update(- run.copy(- bytesWritten = progress.bytesWritten,- averageThroughputBytesPerSecond = progress.averageThroughputBytesPerSecond,- retryCount = maxOf(run.retryCount, progress.retryCount),- lastProgressAtMs = progress.lastProgressAtMs,- updatedAt = System.currentTimeMillis()- )+ recordingRunDao.updateProgress(+ id = recordingId,+ bytesWritten = progress.bytesWritten,+ averageThroughputBytesPerSecond = progress.averageThroughputBytesPerSecond,+ retryCount = progress.retryCount,+ lastProgressAtMs = progress.lastProgressAtMs,+ updatedAt = System.currentTimeMillis())}@@ -558,6 +775,9 @@ class RecordingManagerImpl @Inject constructor(private suspend fun markRunFailed(recordingId: String, reason: String, category: RecordingFailureCategory) {val run = recordingRunDao.getById(recordingId) ?: return+ if (run.bytesWritten == 0L) {+ deleteOutputTarget(context, run.outputUri, run.outputDisplayPath)+ }val now = System.currentTimeMillis()recordingRunDao.update(run.copy(@@ -570,10 +790,45 @@ class RecordingManagerImpl @Inject constructor())alarmScheduler.cancel(recordingId)+ postFailureNotification(run.channelName, run.programTitle, reason)}- private fun createPendingRun(scheduleId: Long, request: RecordingRequest): RecordingRunEntity {+ private fun postFailureNotification(channelName: String, programTitle: String?, reason: String) {+ val notificationManager = context.getSystemService(android.app.NotificationManager::class.java) ?: return+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {+ val channel = android.app.NotificationChannel(+ FAILURE_NOTIFICATION_CHANNEL_ID,+ "Recording Failures",+ android.app.NotificationManager.IMPORTANCE_HIGH+ ).apply { description = "Alerts when a scheduled recording fails" }+ notificationManager.createNotificationChannel(channel)+ }+ val title = programTitle?.let { "Recording failed: $it" } ?: "Recording failed: $channelName"+ val notification = androidx.core.app.NotificationCompat.Builder(context, FAILURE_NOTIFICATION_CHANNEL_ID)+ .setSmallIcon(android.R.drawable.stat_notify_error)+ .setContentTitle(title)+ .setContentText(reason)+ .setStyle(androidx.core.app.NotificationCompat.BigTextStyle().bigText(reason))+ .setAutoCancel(true)+ .setPriority(androidx.core.app.NotificationCompat.PRIORITY_HIGH)+ .build()+ notificationManager.notify(FAILURE_NOTIFICATION_ID_BASE + channelName.hashCode(), notification)+ }++ private suspend fun createPendingRun(scheduleId: Long, request: RecordingRequest): RecordingRunEntity {val now = System.currentTimeMillis()+ val paddingBeforeMs = if (request.paddingBeforeMs > 0) {+ request.paddingBeforeMs+ } else {+ preferencesRepository.recordingPaddingBeforeMinutes.first().toLong() * 60_000L+ }+ val paddingAfterMs = if (request.paddingAfterMs > 0) {+ request.paddingAfterMs+ } else {+ preferencesRepository.recordingPaddingAfterMinutes.first().toLong() * 60_000L+ }+ val effectiveStart = (request.scheduledStartMs - paddingBeforeMs).coerceAtLeast(0L)+ val effectiveEnd = request.scheduledEndMs + paddingAfterMsreturn RecordingRunEntity(id = UUID.randomUUID().toString(),scheduleId = scheduleId,@@ -582,14 +837,14 @@ class RecordingManagerImpl @Inject constructor(channelName = request.channelName,streamUrl = request.streamUrl,programTitle = request.programTitle,- scheduledStartMs = request.scheduledStartMs,- scheduledEndMs = request.scheduledEndMs,+ scheduledStartMs = effectiveStart,+ scheduledEndMs = effectiveEnd,recurrence = request.recurrence,recurringRuleId = request.recurringRuleId,status = RecordingStatus.SCHEDULED,scheduleEnabled = true,priority = request.priority,- alarmStartAtMs = request.scheduledStartMs,+ alarmStartAtMs = effectiveStart,createdAt = now,updatedAt = now)@@ -692,7 +947,9 @@ class RecordingManagerImpl @Inject constructor(val title = overlapping.firstOrNull()?.programTitle ?: overlapping.firstOrNull()?.channelName.orEmpty()return "Recording conflicts with an existing active recording for $title."}- val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE+ val provider = providerDao.getById(providerId)+ ?: return "Recording provider no longer exists."+ val providerMaxConnections = provider.maxConnectionsif (overlapping.count { it.providerId == providerId } >= providerMaxConnections) {return "Recording exceeds the provider connection limit for this account."}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.ktindex 9d970f62..57b6f611 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt@@ -65,7 +65,9 @@ class RecordingAlarmScheduler @Inject constructor(whenMs,pendingIntent)- }.getOrElse {+ }.getOrElse { ex ->+ android.util.Log.w("RecordingAlarmScheduler",+ "Exact alarm denied (SCHEDULE_EXACT_ALARM may be revoked), falling back to inexact alarm for $recordingId", ex)AlarmManagerCompat.setAndAllowWhileIdle(manager,AlarmManager.RTC_WAKEUP,@@ -87,6 +89,13 @@ class RecordingAlarmScheduler @Inject constructor()}- private fun requestCode(action: String, recordingId: String): Int =- 31 * action.hashCode() + recordingId.hashCode()+ private fun requestCode(action: String, recordingId: String): Int {+ val uuid = runCatching { java.util.UUID.fromString(recordingId) }.getOrNull()+ val idHash = if (uuid != null) {+ (uuid.mostSignificantBits xor uuid.leastSignificantBits).toInt()+ } else {+ recordingId.hashCode()+ }+ return 31 * action.hashCode() + idHash+ }}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.ktindex 07e0b401..407af9f8 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt@@ -25,6 +25,19 @@ data class CaptureProgress(val retryCount: Int = 0)+private const val MAX_TRANSIENT_RETRIES = 3+private const val RETRY_BACKOFF_BASE_MS = 15_000L+private const val STALL_TIMEOUT_MS = 60_000L++private fun isTransientFailure(error: Throwable): Boolean {+ val msg = error.message.orEmpty().lowercase(Locale.ROOT)+ return error is java.net.SocketTimeoutException ||+ error is java.net.SocketException ||+ error is java.net.ConnectException ||+ error is java.net.UnknownHostException ||+ (error is IOException && ("timeout" in msg || "reset" in msg || "broken pipe" in msg))+}+interface RecordingCaptureEngine {val sourceType: RecordingSourceType@@ -33,7 +46,8 @@ interface RecordingCaptureEngine {outputTarget: RecordingOutputTarget,contentResolver: ContentResolver,scheduledEndMs: Long,- onProgress: suspend (CaptureProgress) -> Unit+ onProgress: suspend (CaptureProgress) -> Unit,+ maxVideoHeight: Int? = null)}@@ -48,39 +62,57 @@ class TsPassThroughCaptureEngine @Inject constructor(outputTarget: RecordingOutputTarget,contentResolver: ContentResolver,scheduledEndMs: Long,- onProgress: suspend (CaptureProgress) -> Unit+ onProgress: suspend (CaptureProgress) -> Unit,+ maxVideoHeight: Int?) {val startMs = System.currentTimeMillis()var bytesWritten = 0L- val request = Request.Builder().url(source.url).apply {- source.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }- source.headers.forEach { (key, value) -> header(key, value) }- }.build()- okHttpClient.newCall(request).execute().use { response ->- if (!response.isSuccessful) throw IOException("Recording stream failed with HTTP ${response.code}")- val body = response.body ?: throw IOException("Recording stream returned an empty body")- val output = outputTarget.openOutputStream(contentResolver)- ?: throw IOException("Could not open recording output target")- output.use { sink ->- body.byteStream().use { input ->- val buffer = ByteArray(DEFAULT_BUFFER_SIZE)- while (true) {- kotlinx.coroutines.currentCoroutineContext().ensureActive()- if (scheduledEndMs <= System.currentTimeMillis()) break- val read = input.read(buffer)- if (read <= 0) break- sink.write(buffer, 0, read)- bytesWritten += read- val elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)- onProgress(- CaptureProgress(- bytesWritten = bytesWritten,- averageThroughputBytesPerSecond = (bytesWritten * 1000L) / elapsedMs,- lastProgressAtMs = System.currentTimeMillis()- )- )+ var retryCount = 0+ val output = outputTarget.openOutputStream(contentResolver, append = false)+ ?: throw IOException("Could not open recording output target")+ output.use { sink ->+ while (kotlinx.coroutines.currentCoroutineContext().isActive && System.currentTimeMillis() < scheduledEndMs) {+ try {+ val request = Request.Builder().url(source.url).apply {+ source.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }+ source.headers.forEach { (key, value) -> header(key, value) }+ }.build()+ okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Recording stream failed with HTTP ${response.code}")+ val body = response.body ?: throw IOException("Recording stream returned an empty body")+ body.byteStream().use { input ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ var lastDataAt = System.currentTimeMillis()+ while (true) {+ kotlinx.coroutines.currentCoroutineContext().ensureActive()+ if (scheduledEndMs <= System.currentTimeMillis()) break+ if (System.currentTimeMillis() - lastDataAt > STALL_TIMEOUT_MS) {+ throw IOException("Recording stream stalled — no data received for ${STALL_TIMEOUT_MS / 1000}s")+ }+ val read = input.read(buffer)+ if (read <= 0) break+ lastDataAt = System.currentTimeMillis()+ sink.write(buffer, 0, read)+ bytesWritten += read+ val elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)+ onProgress(+ CaptureProgress(+ bytesWritten = bytesWritten,+ averageThroughputBytesPerSecond = (bytesWritten * 1000L) / elapsedMs,+ lastProgressAtMs = System.currentTimeMillis(),+ retryCount = retryCount+ )+ )+ }+ sink.flush()+ }}- sink.flush()+ break // Normal completion+ } catch (e: Throwable) {+ if (!isTransientFailure(e) || retryCount >= MAX_TRANSIENT_RETRIES) throw e+ retryCount+++ val backoff = RETRY_BACKOFF_BASE_MS * (1L shl (retryCount - 1).coerceAtMost(3))+ delay(backoff.coerceAtMost(scheduledEndMs - System.currentTimeMillis()).coerceAtLeast(0))}}}@@ -98,7 +130,8 @@ class HlsLiveCaptureEngine @Inject constructor(outputTarget: RecordingOutputTarget,contentResolver: ContentResolver,scheduledEndMs: Long,- onProgress: suspend (CaptureProgress) -> Unit+ onProgress: suspend (CaptureProgress) -> Unit,+ maxVideoHeight: Int?) {val startMs = System.currentTimeMillis()var bytesWritten = 0L@@ -111,10 +144,29 @@ class HlsLiveCaptureEngine @Inject constructor(?: throw IOException("Could not open recording output target")output.use { sink ->var currentPlaylistUrl = source.url- val seenSegments = linkedSetOf<String>()+ val maxSeenSegments = 10_000+ val seenSegments = object : LinkedHashSet<String>() {+ override fun add(element: String): Boolean {+ val added = super.add(element)+ if (size > maxSeenSegments) remove(first())+ return added+ }+ }+ var lastDataAt = System.currentTimeMillis()+ var consecutiveEmptyPlaylists = 0while (kotlinx.coroutines.currentCoroutineContext().isActive && System.currentTimeMillis() < scheduledEndMs) {- val playlistText = fetchText(currentPlaylistUrl, headers)- val playlist = parsePlaylist(currentPlaylistUrl, playlistText)+ if (System.currentTimeMillis() - lastDataAt > STALL_TIMEOUT_MS) {+ throw IOException("HLS recording stalled — no new segments for ${STALL_TIMEOUT_MS / 1000}s")+ }+ val playlistText = try {+ fetchText(currentPlaylistUrl, headers)+ } catch (e: Throwable) {+ if (!isTransientFailure(e) || retryCount >= MAX_TRANSIENT_RETRIES) throw e+ retryCount+++ delay(RETRY_BACKOFF_BASE_MS * (1L shl (retryCount - 1).coerceAtMost(3)))+ continue+ }+ val playlist = parsePlaylist(currentPlaylistUrl, playlistText, maxVideoHeight)when (playlist) {is ParsedHlsPlaylist.Master -> {currentPlaylistUrl = playlist.bestVariantUrl@@ -135,20 +187,29 @@ class HlsLiveCaptureEngine @Inject constructor(}// Cache key bytes by URI so rotated keys are fetched once eachval keyCache = mutableMapOf<String, ByteArray>()+ var newSegmentsThisRound = falseplaylist.segments.forEach { segment ->kotlinx.coroutines.currentCoroutineContext().ensureActive()if (segment.uri in seenSegments) return@forEachseenSegments += segment.uri- val bytes = fetchBytes(segment.uri, headers)+ val bytes = try {+ fetchBytes(segment.uri, headers)+ } catch (e: Throwable) {+ if (!isTransientFailure(e) || retryCount >= MAX_TRANSIENT_RETRIES) throw e+ retryCount+++ return@forEach // Skip this segment, retry on next playlist refresh+ }val segKey = segment.key?.takeIf { it.method.equals("AES-128", ignoreCase = true) }val payload = if (segKey != null) {val keyBytes = keyCache.getOrPut(segKey.uri) { fetchBytes(segKey.uri, headers) }- decryptAes128(bytes, keyBytes, segKey.iv)+ decryptAes128(bytes, keyBytes, segKey.iv, segment.mediaSequenceNumber)} else {bytes}sink.write(payload)bytesWritten += payload.size+ newSegmentsThisRound = true+ lastDataAt = System.currentTimeMillis()val elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)onProgress(CaptureProgress(@@ -161,7 +222,7 @@ class HlsLiveCaptureEngine @Inject constructor(if (System.currentTimeMillis() >= scheduledEndMs) return@forEach}sink.flush()- retryCount = 0+ if (newSegmentsThisRound) retryCount = 0if (playlist.endList) breakdelay((playlist.targetDurationSeconds.coerceAtLeast(2) * 1000L) / 2L)}@@ -190,36 +251,49 @@ class HlsLiveCaptureEngine @Inject constructor(}}- private fun decryptAes128(payload: ByteArray, keyBytes: ByteArray, ivHex: String?): ByteArray {- val iv = ivHex?.removePrefix("0x")- ?.chunked(2)- ?.mapNotNull { it.toIntOrNull(16)?.toByte() }- ?.toByteArray()- ?.takeIf { it.size == 16 }- ?: ByteArray(16)+ private fun decryptAes128(payload: ByteArray, keyBytes: ByteArray, ivHex: String?, mediaSequenceNumber: Long): ByteArray {+ val iv = if (ivHex != null) {+ ivHex.removePrefix("0x")+ .chunked(2)+ .mapNotNull { it.toIntOrNull(16)?.toByte() }+ .toByteArray()+ .takeIf { it.size == 16 }+ ?: throw IOException("Malformed AES-128 IV in HLS key: $ivHex")+ } else {+ // Per RFC 8216 §5.2: use media sequence number as big-endian 128-bit integer+ java.nio.ByteBuffer.allocate(16).apply {+ position(8)+ putLong(mediaSequenceNumber)+ }.array()+ }val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyBytes, "AES"), IvParameterSpec(iv))return cipher.doFinal(payload)}- private fun parsePlaylist(baseUrl: String, rawText: String): ParsedHlsPlaylist {+ private fun parsePlaylist(baseUrl: String, rawText: String, maxVideoHeight: Int? = null): ParsedHlsPlaylist {val lines = rawText.lineSequence().map(String::trim).filter { it.isNotEmpty() }.toList()if (lines.any { it.startsWith("#EXT-X-STREAM-INF", ignoreCase = true) }) {- val variants = mutableListOf<Pair<Int, String>>()- var pendingBandwidth = 0+ data class HlsVariant(val bandwidth: Int, val height: Int?, val url: String)+ val variants = mutableListOf<HlsVariant>()lines.forEachIndexed { index, line ->if (line.startsWith("#EXT-X-STREAM-INF", ignoreCase = true)) {- pendingBandwidth = Regex("""BANDWIDTH=(\d+)""")+ val bandwidth = Regex("""BANDWIDTH=(\d+)""").find(line)- ?.groupValues- ?.getOrNull(1)- ?.toIntOrNull()- ?: 0+ ?.groupValues?.getOrNull(1)?.toIntOrNull() ?: 0+ val height = Regex("""RESOLUTION=\d+x(\d+)""")+ .find(line)+ ?.groupValues?.getOrNull(1)?.toIntOrNull()val next = lines.getOrNull(index + 1)?.takeIf { !it.startsWith("#") } ?: return@forEachIndexed- variants += pendingBandwidth to resolveRelativeUrl(baseUrl, next)+ variants += HlsVariant(bandwidth, height, resolveRelativeUrl(baseUrl, next))}}- val bestVariantUrl = variants.maxByOrNull { it.first }?.second+ val eligible = if (maxVideoHeight != null) {+ variants.filter { it.height == null || it.height <= maxVideoHeight }.ifEmpty { variants }+ } else {+ variants+ }+ val bestVariantUrl = eligible.maxByOrNull { it.bandwidth }?.url?: throw IOException("No playable HLS variants were available.")return ParsedHlsPlaylist.Master(bestVariantUrl)}@@ -227,12 +301,18 @@ class HlsLiveCaptureEngine @Inject constructor(var targetDuration = 6var endList = falsevar currentKey: HlsKey? = null+ var mediaSequence = 0Lval segments = mutableListOf<HlsSegment>()+ var segmentIndex = 0Llines.forEach { line ->when {line.startsWith("#EXT-X-TARGETDURATION", ignoreCase = true) -> {targetDuration = line.substringAfter(':', "6").toIntOrNull() ?: 6}+ line.startsWith("#EXT-X-MEDIA-SEQUENCE", ignoreCase = true) -> {+ mediaSequence = line.substringAfter(':', "0").toLongOrNull() ?: 0L+ segmentIndex = 0L+ }line.startsWith("#EXT-X-ENDLIST", ignoreCase = true) -> {endList = true}@@ -248,8 +328,10 @@ class HlsLiveCaptureEngine @Inject constructor(else -> {segments += HlsSegment(uri = resolveRelativeUrl(baseUrl, line),- key = currentKey?.copy()+ key = currentKey?.copy(),+ mediaSequenceNumber = mediaSequence + segmentIndex)+ segmentIndex++}}}@@ -289,7 +371,8 @@ private sealed interface ParsedHlsPlaylist {private data class HlsSegment(val uri: String,- val key: HlsKey? = null+ val key: HlsKey? = null,+ val mediaSequenceNumber: Long = 0)private data class HlsKey(diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.ktindex fa651427..4e33446b 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt@@ -4,12 +4,10 @@ import android.content.Contextimport androidx.work.CoroutineWorkerimport androidx.work.ExistingPeriodicWorkPolicyimport androidx.work.ExistingWorkPolicy-import androidx.work.NetworkTypeimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManagerimport androidx.work.WorkerParameters-import androidx.work.Constraintsimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -44,12 +42,7 @@ class RecordingReconcileWorker(private const val ONE_SHOT_WORK_NAME = "RecordingReconcileWorkerOneShot"fun enqueuePeriodic(context: Context) {- val constraints = Constraints.Builder()- .setRequiredNetworkType(NetworkType.CONNECTED)- .setRequiresBatteryNotLow(false)- .build()val request = PeriodicWorkRequestBuilder<RecordingReconcileWorker>(6, TimeUnit.HOURS)- .setConstraints(constraints).build()WorkManager.getInstance(context).enqueueUniquePeriodicWork(PERIODIC_WORK_NAME,diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.ktindex 7026cbbf..0aae2993 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt@@ -3,17 +3,24 @@ package com.streamvault.data.manager.recordingimport android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intent+import android.os.UserManagerclass RecordingRestoreReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {when (intent.action) {Intent.ACTION_BOOT_COMPLETED,- Intent.ACTION_MY_PACKAGE_REPLACED,- Intent.ACTION_LOCKED_BOOT_COMPLETED -> {+ Intent.ACTION_MY_PACKAGE_REPLACED -> {RecordingForegroundService.requestReconcile(context)RecordingReconcileWorker.enqueueOneShot(context)}+ Intent.ACTION_LOCKED_BOOT_COMPLETED -> {+ val userManager = context.getSystemService(Context.USER_SERVICE) as? UserManager+ if (userManager?.isUserUnlocked == true) {+ RecordingForegroundService.requestReconcile(context)+ RecordingReconcileWorker.enqueueOneShot(context)+ }+ }}}}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.ktindex 469bd285..ef7c07e2 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt@@ -40,9 +40,11 @@ class RecordingSourceResolver @Inject constructor(fallbackProviderId = providerId,fallbackStreamId = channelId,fallbackContentType = ContentType.LIVE,- // Recording jobs can run for minutes or hours; prefer the stable- // portal URL over an expiring tokenized direct-source CDN URL.- preferStableUrl = true+ // Use the direct-source CDN URL when available — many Xtream servers+ // only serve streams via their CDN URLs and return 404 on the+ // credential-based portal path. If no direct-source is present the+ // resolver already falls back to the portal URL automatically.+ preferStableUrl = false) ?: throw IOException("Recording stream URL could not be resolved.")val providerLabel = providerDao.getById(providerId)?.let { provider ->@@ -62,26 +64,52 @@ class RecordingSourceResolver @Inject constructor(}private fun sniffSourceType(resolved: ResolvedStreamUrl): RecordingSourceType {+ // Prefer the container extension reported by the URL resolver (e.g. from the+ // Xtream internal token) — this avoids a network probe that many IPTV servers+ // reject with 404/416 when a Range header is present.+ resolved.containerExtension?.lowercase(Locale.ROOT)?.let { ext ->+ return when (ext) {+ "m3u8" -> RecordingSourceType.HLS+ "ts" -> RecordingSourceType.TS+ "mpd" -> RecordingSourceType.DASH+ else -> RecordingSourceType.TS+ }+ }val url = resolved.url.lowercase(Locale.ROOT)return when {url.contains(".mpd") || url.contains("ext=mpd") -> RecordingSourceType.DASH- url.contains(".ts") || url.contains("ext=ts") -> RecordingSourceType.TS- url.contains(".m3u8") || url.contains("ext=m3u8") || url.contains("/hd") || url.contains("/sd") -> {- probeAdaptiveType(resolved.url)- }+ url.endsWith(".ts") || url.contains(".ts?") || url.contains("ext=ts") -> RecordingSourceType.TS+ url.endsWith(".m3u8") || url.contains(".m3u8?") || url.contains("ext=m3u8") -> RecordingSourceType.HLSelse -> probeAdaptiveType(resolved.url)}}private fun probeAdaptiveType(url: String): RecordingSourceType {+ // Try HEAD first — lighter and avoids Range-header rejections.+ val headResult = runCatching {+ val headRequest = Request.Builder().url(url).head().build()+ okHttpClient.newCall(headRequest).execute().use { response ->+ if (!response.isSuccessful) return@use null+ val contentType = response.header("Content-Type").orEmpty().lowercase(Locale.ROOT)+ when {+ "application/vnd.apple.mpegurl" in contentType || "application/x-mpegurl" in contentType -> RecordingSourceType.HLS+ "application/dash+xml" in contentType -> RecordingSourceType.DASH+ "video/mp2t" in contentType || "video/mpeg" in contentType -> RecordingSourceType.TS+ else -> null+ }+ }+ }.getOrNull()+ if (headResult != null) return headResult++ // Fall back to a small GET to inspect the body prefix.val request = Request.Builder().url(url)- .header("Range", "bytes=0-2047").get().build()val bodyPrefix = runCatching {okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) return@use ""val contentType = response.header("Content-Type").orEmpty().lowercase(Locale.ROOT)when {"application/vnd.apple.mpegurl" in contentType || "application/x-mpegurl" in contentType -> return RecordingSourceType.HLS@@ -94,6 +122,7 @@ class RecordingSourceResolver @Inject constructor(return when {bodyPrefix.contains("#EXTM3U", ignoreCase = true) -> RecordingSourceType.HLSbodyPrefix.contains("<MPD", ignoreCase = true) -> RecordingSourceType.DASH+ bodyPrefix.isEmpty() -> RecordingSourceType.UNKNOWNelse -> RecordingSourceType.TS}}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.ktindex 5162c165..e732b203 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt@@ -6,8 +6,6 @@ import android.net.Uriimport android.os.Environmentimport android.os.StatFsimport androidx.documentfile.provider.DocumentFile-import com.google.gson.Gson-import com.google.gson.reflect.TypeTokenimport com.streamvault.data.local.entity.RecordingRunEntityimport com.streamvault.data.local.entity.RecordingRunWithScheduleimport com.streamvault.data.local.entity.RecordingStorageEntity@@ -20,6 +18,7 @@ import java.io.FileOutputStreamimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale+import org.json.JSONObjectprivate const val DEFAULT_RECORDINGS_DIR_NAME = "recordings"@@ -76,17 +75,31 @@ internal fun RecordingStorageConfig.toEntity(existing: RecordingStorageEntity?,updatedAt = System.currentTimeMillis())-internal fun headersToJson(gson: Gson, headers: Map<String, String>): String =- gson.toJson(headers)+internal fun headersToJson(headers: Map<String, String>): String {+ val obj = JSONObject()+ headers.forEach { (k, v) -> obj.put(k, v) }+ return obj.toString()+}-internal fun headersFromJson(gson: Gson, raw: String?): Map<String, String> {+internal fun headersFromJson(raw: String?): Map<String, String> {if (raw.isNullOrBlank()) return emptyMap()- val type = object : TypeToken<Map<String, String>>() {}.type- return runCatching { gson.fromJson<Map<String, String>>(raw, type).orEmpty() }.getOrDefault(emptyMap())+ return runCatching {+ val obj = JSONObject(raw)+ buildMap { obj.keys().forEach { key -> put(key, obj.getString(key)) } }+ }.getOrDefault(emptyMap())}-internal fun inferFailureCategory(message: String?, fallback: RecordingFailureCategory = RecordingFailureCategory.UNKNOWN): RecordingFailureCategory {- val normalized = message.orEmpty().lowercase(Locale.ROOT)+internal fun inferFailureCategory(error: Throwable?, fallback: RecordingFailureCategory = RecordingFailureCategory.UNKNOWN): RecordingFailureCategory {+ if (error is UnsupportedRecordingException) return error.category+ val rootCause = error?.cause ?: error+ when (rootCause) {+ is java.net.SocketTimeoutException,+ is java.net.SocketException,+ is java.net.UnknownHostException,+ is java.net.ConnectException -> return RecordingFailureCategory.NETWORK+ is javax.net.ssl.SSLException -> return RecordingFailureCategory.NETWORK+ }+ val normalized = error?.message.orEmpty().lowercase(Locale.ROOT)return when {normalized.isBlank() -> fallback"drm" in normalized -> RecordingFailureCategory.DRM_UNSUPPORTED@@ -108,9 +121,9 @@ internal fun sanitizeRecordingFileName(): String {val formatter = SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.US)val startLabel = formatter.format(Date(startMs))- val safeChannel = channelName.replace(Regex("[^a-zA-Z0-9._ -]"), "_").trim().ifBlank { "Channel" }+ val safeChannel = channelName.replace(Regex("[^a-zA-Z0-9_ -]"), "_").trim().ifBlank { "Channel" }val safeProgram = programTitle- ?.replace(Regex("[^a-zA-Z0-9._ -]"), "_")+ ?.replace(Regex("[^a-zA-Z0-9_ -]"), "_")?.trim()?.takeIf { it.isNotBlank() }?: "Program"@@ -161,10 +174,16 @@ internal fun createOutputTarget(val uri = Uri.parse(treeUri)val documentTree = DocumentFile.fromTreeUri(context, uri)?: throw IllegalStateException("Recording folder is unavailable.")- val existing = documentTree.findFile(fileName)- val document = existing ?: documentTree.createFile("video/mp2t", fileName.removeSuffix(".ts"))+ val baseName = fileName.removeSuffix(".ts")+ var candidateName = fileName+ var counter = 1+ while (documentTree.findFile(candidateName) != null) {+ candidateName = "${baseName}_$counter.ts"+ counter+++ }+ val document = documentTree.createFile("video/mp2t", candidateName.removeSuffix(".ts"))requireNotNull(document?.uri) { "Failed to create recording file." }- return RecordingOutputTarget.DocumentTarget(document.uri, "${documentTree.name ?: "Recordings"}/$fileName")+ return RecordingOutputTarget.DocumentTarget(document.uri, "${documentTree.name ?: "Recordings"}/$candidateName")}internal fun deleteOutputTarget(context: Context, outputUri: String?, outputPath: String?) {diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.ktindex 55c3cd28..ce22ce54 100644--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt@@ -642,7 +642,9 @@ fun EpgSourceEntity.toDomain() = com.streamvault.domain.model.EpgSource(lastError = lastError,priority = priority,createdAt = createdAt,- updatedAt = updatedAt+ updatedAt = updatedAt,+ etag = etag,+ lastModifiedHeader = lastModifiedHeader)fun com.streamvault.domain.model.EpgSource.toEntity() = EpgSourceEntity(@@ -655,7 +657,9 @@ fun com.streamvault.domain.model.EpgSource.toEntity() = EpgSourceEntity(lastError = lastError,priority = priority,createdAt = createdAt,- updatedAt = updatedAt+ updatedAt = updatedAt,+ etag = etag,+ lastModifiedHeader = lastModifiedHeader)// ── Provider EPG Source Assignment ─────────────────────────────────diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex 40c0cd06..ffae4c06 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -61,6 +61,7 @@ class PreferencesRepository @Inject constructor(val ACTIVE_LIVE_SOURCE_ID = longPreferencesKey("active_live_source_id")val DEFAULT_VIEW_MODE = stringPreferencesKey("default_view_mode")val PARENTAL_CONTROL_LEVEL = intPreferencesKey("parental_control_level")+ val PARENTAL_V2_MIGRATED = booleanPreferencesKey("parental_v2_migrated")val LEGACY_PARENTAL_PIN = stringPreferencesKey("parental_pin")val PARENTAL_PIN_HASH = stringPreferencesKey("parental_pin_hash")val PARENTAL_PIN_SALT = stringPreferencesKey("parental_pin_salt")@@ -115,6 +116,9 @@ class PreferencesRepository @Inject constructor(val PREVENT_STANDBY_DURING_PLAYBACK = booleanPreferencesKey("prevent_standby_during_playback")val AUTO_CHECK_APP_UPDATES = booleanPreferencesKey("auto_check_app_updates")val AUTO_DOWNLOAD_APP_UPDATES = booleanPreferencesKey("auto_download_app_updates")+ val RECORDING_WIFI_ONLY = booleanPreferencesKey("recording_wifi_only")+ val RECORDING_PADDING_BEFORE_MINUTES = intPreferencesKey("recording_padding_before_minutes")+ val RECORDING_PADDING_AFTER_MINUTES = intPreferencesKey("recording_padding_after_minutes")val LAST_APP_UPDATE_CHECK_TIMESTAMP = longPreferencesKey("last_app_update_check_timestamp")val APP_UPDATE_DOWNLOAD_ID = longPreferencesKey("app_update_download_id")val APP_UPDATE_DOWNLOADED_VERSION_NAME = stringPreferencesKey("app_update_downloaded_version_name")@@ -301,7 +305,12 @@ class PreferencesRepository @Inject constructor(val parentalControlLevel: Flow<Int> = context.dataStore.data.map { preferences ->- preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 1 // Default to 1 = LOCKED+ val stored = preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 2 // Default to 2 = PRIVATE+ // Migration: users who had the old HIDDEN level (stored as 2) are promoted to the new+ // HIDDEN level (3). The v2-migrated flag prevents re-mapping after the user explicitly+ // sets level 2 (PRIVATE) in the new scheme.+ val migrated = preferences[PreferencesKeys.PARENTAL_V2_MIGRATED] ?: false+ if (!migrated && stored == 2) 3 else stored}val hasParentalPin: Flow<Boolean> = context.dataStore.data.map(::hasStoredParentalPin)@@ -341,6 +350,7 @@ class PreferencesRepository @Inject constructor(suspend fun setParentalControlLevel(level: Int) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] = level+ preferences[PreferencesKeys.PARENTAL_V2_MIGRATED] = true}}@@ -466,12 +476,42 @@ class PreferencesRepository @Inject constructor(preferences[PreferencesKeys.ZAP_AUTO_REVERT] ?: true}+ val recordingWifiOnly: Flow<Boolean> = context.dataStore.data.map { preferences ->+ preferences[PreferencesKeys.RECORDING_WIFI_ONLY] ?: false+ }++ val recordingPaddingBeforeMinutes: Flow<Int> = context.dataStore.data.map { preferences ->+ (preferences[PreferencesKeys.RECORDING_PADDING_BEFORE_MINUTES] ?: 0).coerceIn(0, 30)+ }++ val recordingPaddingAfterMinutes: Flow<Int> = context.dataStore.data.map { preferences ->+ (preferences[PreferencesKeys.RECORDING_PADDING_AFTER_MINUTES] ?: 0).coerceIn(0, 30)+ }+suspend fun setZapAutoRevert(enabled: Boolean) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.ZAP_AUTO_REVERT] = enabled}}+ suspend fun setRecordingWifiOnly(enabled: Boolean) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.RECORDING_WIFI_ONLY] = enabled+ }+ }++ suspend fun setRecordingPaddingBeforeMinutes(minutes: Int) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.RECORDING_PADDING_BEFORE_MINUTES] = minutes.coerceIn(0, 30)+ }+ }++ suspend fun setRecordingPaddingAfterMinutes(minutes: Int) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.RECORDING_PADDING_AFTER_MINUTES] = minutes.coerceIn(0, 30)+ }+ }+suspend fun setPreventStandbyDuringPlayback(prevent: Boolean) {context.dataStore.edit { preferences ->preferences[PreferencesKeys.PREVENT_STANDBY_DURING_PLAYBACK] = preventdiff --git a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.ktindex 799f64da..db66148d 100644--- a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt+++ b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt@@ -6,6 +6,7 @@ object NetworkTimeoutConfig {const val WRITE_TIMEOUT_SECONDS = 30L// EPG files can be large and served from slow hosts — allow more time per read.const val EPG_READ_TIMEOUT_SECONDS = 120L+ const val EPG_MAX_SIZE_BYTES = 200L * 1_048_576 // 200 MBconst val XTREAM_HEAVY_READ_TIMEOUT_SECONDS = 300Lconst val XTREAM_HEAVY_WRITE_TIMEOUT_SECONDS = 60Lconst val XTREAM_HEAVY_CALL_TIMEOUT_SECONDS = 330Ldiff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.ktindex ba8c928c..1847381f 100644--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt@@ -80,7 +80,7 @@ class ChannelRepositoryImpl @Inject constructor(parentalControlManager.unlockedCategoriesForProvider(providerId),preferencesRepository.liveChannelNumberingMode) { entities, level, unlockedCats, numberingMode ->- val filtered = if (level == 2) {+ val filtered = if (level >= 3) {entities.filter { entity ->val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)(!entity.isAdult && !entity.isUserProtected) || isUnlocked@@ -116,7 +116,7 @@ class ChannelRepositoryImpl @Inject constructor(parentalControlManager.unlockedCategoriesForProvider(providerId),preferencesRepository.liveChannelNumberingMode) { entities, level, unlockedCats, numberingMode ->- val filtered = if (level == 2) {+ val filtered = if (level >= 3) {entities.filter { entity ->val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)(!entity.isAdult && !entity.isUserProtected) || isUnlocked@@ -146,7 +146,7 @@ class ChannelRepositoryImpl @Inject constructor(domain}}- val filteredCategories = if (level == 2) {+ val filteredCategories = if (level >= 3) {mappedCategories.filter { category ->(!category.isAdult && !category.isUserProtected) || unlockedCats.contains(category.id)}@@ -174,7 +174,7 @@ class ChannelRepositoryImpl @Inject constructor(parentalControlManager.unlockedCategoriesForProvider(providerId),preferencesRepository.liveChannelNumberingMode) { entities, level, unlockedCats, numberingMode ->- val filtered = if (level == 2) {+ val filtered = if (level >= 3) {entities.filter { entity ->val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)(!entity.isAdult && !entity.isUserProtected) || isUnlocked@@ -297,7 +297,7 @@ class ChannelRepositoryImpl @Inject constructor(level: Int,unlockedCats: Set<Long>): List<ChannelBrowseEntity> {- return if (level == 2) {+ return if (level >= 3) {entities.filter { entity ->val isUnlocked = entity.categoryId != null && unlockedCats.contains(entity.categoryId)(!entity.isAdult && !entity.isUserProtected) || isUnlockeddiff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex 2137ee9e..42acf46b 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -11,16 +11,20 @@ import com.streamvault.domain.model.Programimport com.streamvault.domain.model.Resultimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.EpgSourceRepository+import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.SharingStartedimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.shareInimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContext@@ -55,10 +59,15 @@ class EpgRepositoryImpl @Inject constructor(}companion object {- private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MB+ private const val MAX_EPG_SIZE_BYTES = NetworkTimeoutConfig.EPG_MAX_SIZE_BYTESprivate const val NOW_AND_NEXT_LOOKBACK_MS = 60L * 60L * 1000Lprivate const val NOW_AND_NEXT_LOOKAHEAD_MS = 2L * 60L * 60L * 1000Lprivate const val NOW_AND_NEXT_REFRESH_INTERVAL_MS = 60L * 1000L++ private fun String.escapeSqlLike(escape: Char = '\\'): String =+ this.replace("$escape", "$escape$escape")+ .replace("%", "$escape%")+ .replace("_", "${escape}_")}override fun getProgramsForChannel(@@ -127,9 +136,10 @@ class EpgRepositoryImpl @Inject constructor(): Flow<List<Program>> {val normalizedQuery = query.trim()if (normalizedQuery.length < 2) return flowOf(emptyList())+ val escaped = normalizedQuery.escapeSqlLike()return programDao.searchPrograms(providerId = providerId,- queryPattern = "%$normalizedQuery%",+ queryPattern = "%$escaped%",startTime = startTime,endTime = endTime,categoryId = categoryId,@@ -141,7 +151,7 @@ class EpgRepositoryImpl @Inject constructor(}override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =- nowTicker().flatMapLatest { now ->+ nowTicker.flatMapLatest { now ->programDao.getNowPlaying(providerId, channelId, now).map { it?.toDomain() }}@@ -185,7 +195,7 @@ class EpgRepositoryImpl @Inject constructor(}override fun getNowAndNext(providerId: Long, channelId: String): Flow<Pair<Program?, Program?>> =- nowTicker().flatMapLatest { now ->+ nowTicker.flatMapLatest { now ->programDao.getForChannel(providerId = providerId,channelId = channelId,@@ -194,7 +204,8 @@ class EpgRepositoryImpl @Inject constructor().map { entities ->val programs = entities.map { it.toDomain() }val current = programs.find { it.startTime <= now && it.endTime > now }- val next = programs.find { it.startTime > now }+ val nextStart = current?.endTime ?: now+ val next = programs.firstOrNull { it.startTime >= nextStart && it != current }current to next}}@@ -335,12 +346,14 @@ class EpgRepositoryImpl @Inject constructor(return emptyList()}- private fun nowTicker(): Flow<Long> = flow {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ private val nowTicker: Flow<Long> = flow {while (true) {emit(System.currentTimeMillis())delay(NOW_AND_NEXT_REFRESH_INTERVAL_MS)}- }+ }.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 1)private fun providerRefreshMutex(providerId: Long): Mutex =providerRefreshMutexes.computeIfAbsent(providerId) { Mutex() }diff --git a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.ktindex ca17fae8..52ca297e 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgSourceRepositoryImpl.kt@@ -5,6 +5,7 @@ import android.net.Uriimport android.util.Logimport com.streamvault.data.epg.EpgNameNormalizerimport com.streamvault.data.epg.EpgResolutionEngine+import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDao@@ -56,14 +57,16 @@ class EpgSourceRepositoryImpl @Inject constructor(private val epgProgrammeDao: EpgProgrammeDao,private val xmltvParser: XmltvParser,private val okHttpClient: OkHttpClient,- private val resolutionEngine: EpgResolutionEngine+ private val resolutionEngine: EpgResolutionEngine,+ private val transactionRunner: DatabaseTransactionRunner) : EpgSourceRepository {companion object {private const val TAG = "EpgSourceRepo"- private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576 // 200 MB+ private const val MAX_EPG_SIZE_BYTES = NetworkTimeoutConfig.EPG_MAX_SIZE_BYTESprivate const val CHANNEL_BATCH_SIZE = 500private const val PROGRAMME_BATCH_SIZE = 500+ private const val MIN_REFRESH_INTERVAL_MS = 5L * 60L * 1000L // 5 minutes}private val sourceRefreshMutexes = ConcurrentHashMap<Long, Mutex>()@@ -207,14 +210,23 @@ class EpgSourceRepositoryImpl @Inject constructor(?: return@withLock Result.error("Source not found")val now = System.currentTimeMillis()++ // Rate-limit: skip if last successful refresh was less than 5 minutes ago+ if (source.lastRefreshAt > 0 && now - source.lastRefreshAt < MIN_REFRESH_INTERVAL_MS) {+ Log.d(TAG, "Skipping refresh for source $sourceId: last refresh was ${(now - source.lastRefreshAt) / 1000}s ago")+ return@withLock Result.success(Unit)+ }+try {- epgSourceDao.updateRefreshStatus(sourceId, now, null)++ var responseEtag: String? = null+ var responseLastModified: String? = nullval rawInputStream: java.io.InputStream = if (source.url.startsWith("content://")) {context.contentResolver.openInputStream(Uri.parse(source.url))?: run {val err = "Cannot open local file"- epgSourceDao.updateRefreshStatus(sourceId, now, err)+ epgSourceDao.updateRefreshError(sourceId, err)return@withLock Result.error(err)}} else {@@ -225,13 +237,24 @@ class EpgSourceRepositoryImpl @Inject constructor(val request = Request.Builder().url(source.url).header("Accept-Encoding", "identity")+ .apply {+ source.etag?.let { header("If-None-Match", it) }+ source.lastModifiedHeader?.let { header("If-Modified-Since", it) }+ }.build()val response = epgHttpClient.newCall(request).execute()+ if (response.code == 304) {+ response.close()+ val now = System.currentTimeMillis()+ epgSourceDao.updateRefreshSuccess(sourceId, now)+ return@withLock Result.success(Unit)+ }+if (!response.isSuccessful) {val err = "HTTP ${response.code}"response.close()- epgSourceDao.updateRefreshStatus(sourceId, now, err)+ epgSourceDao.updateRefreshError(sourceId, err)return@withLock Result.error("Failed to download EPG: $err")}@@ -239,14 +262,16 @@ class EpgSourceRepositoryImpl @Inject constructor(if (contentLength > MAX_EPG_SIZE_BYTES) {response.close()val err = "File too large (${contentLength / 1_048_576}MB)"- epgSourceDao.updateRefreshStatus(sourceId, now, err)+ epgSourceDao.updateRefreshError(sourceId, err)return@withLock Result.error(err)}val bodyStream = response.body?.byteStream() ?: run {- epgSourceDao.updateRefreshStatus(sourceId, now, "Empty response")+ epgSourceDao.updateRefreshError(sourceId, "Empty response")return@withLock Result.error("Empty EPG response")}+ responseEtag = response.header("ETag")+ responseLastModified = response.header("Last-Modified")// Some servers send Content-Encoding: gzip even when identity was requested.// Since OkHttp no longer decompresses (we set Accept-Encoding manually),// we must handle it here.@@ -263,9 +288,11 @@ class EpgSourceRepositoryImpl @Inject constructor(var channelCount = 0var programmeCount = 0- // Delete old data before ingesting- epgChannelDao.deleteBySource(sourceId)- epgProgrammeDao.deleteBySource(sourceId)+ // Stage new data under a negative source ID to avoid clobbering+ // live data during download/parse. Swap atomically on success.+ val stagingId = -sourceId+ epgChannelDao.deleteBySource(stagingId)+ epgProgrammeDao.deleteBySource(stagingId)rawInputStream.use { raw ->val limited = object : FilterInputStream(raw) {@@ -285,7 +312,7 @@ class EpgSourceRepositoryImpl @Inject constructor(onChannel = { xmltvChannel ->channelBatch.add(EpgChannelEntity(- epgSourceId = sourceId,+ epgSourceId = stagingId,xmltvChannelId = xmltvChannel.id,displayName = xmltvChannel.displayName,normalizedName = EpgNameNormalizer.normalize(xmltvChannel.displayName),@@ -301,7 +328,7 @@ class EpgSourceRepositoryImpl @Inject constructor(onProgramme = { programme ->programmeBatch.add(EpgProgrammeEntity(- epgSourceId = sourceId,+ epgSourceId = stagingId,xmltvChannelId = programme.channelId,startTime = programme.startTime,endTime = programme.endTime,@@ -325,7 +352,7 @@ class EpgSourceRepositoryImpl @Inject constructor(}}- // Flush remaining+ // Flush remaining staging batchesif (channelBatch.isNotEmpty()) {epgChannelDao.insertAll(channelBatch.toList())}@@ -333,7 +360,16 @@ class EpgSourceRepositoryImpl @Inject constructor(epgProgrammeDao.insertAll(programmeBatch.toList())}+ // Atomically swap staging data into the real source ID+ transactionRunner.inTransaction {+ epgChannelDao.deleteBySource(sourceId)+ epgProgrammeDao.deleteBySource(sourceId)+ epgChannelDao.moveToSource(stagingId, sourceId)+ epgProgrammeDao.moveToSource(stagingId, sourceId)+ }+epgSourceDao.updateRefreshSuccess(sourceId, System.currentTimeMillis())+ epgSourceDao.updateConditionalHeaders(sourceId, responseEtag, responseLastModified)if (resolveAffectedProviders) {resolveAffectedProviders(providerEpgSourceDao.getProviderIdsForSourceSync(sourceId))}@@ -341,13 +377,19 @@ class EpgSourceRepositoryImpl @Inject constructor(Result.success(Unit)} catch (e: Exception) {Log.e(TAG, "Failed to refresh source $sourceId", e)+ // Clean up any staged rows on failure+ val stagingId = -sourceId+ runCatching {+ epgChannelDao.deleteBySource(stagingId)+ epgProgrammeDao.deleteBySource(stagingId)+ }val isOversizeError = e is IOException && e.message?.contains("too large", ignoreCase = true) == trueval statusMessage = if (isOversizeError) {"EPG response exceeded 200 MB limit"} else {e.message ?: "Unknown error"}- epgSourceDao.updateRefreshStatus(sourceId, now, statusMessage)+ epgSourceDao.updateRefreshError(sourceId, statusMessage)if (isOversizeError) {Result.error("EPG response exceeded 200 MB limit", e)} else {@@ -396,22 +438,22 @@ class EpgSourceRepositoryImpl @Inject constructor(if (assignments.isEmpty()) return emptyList()val sourceNamesById = epgSourceDao.getAllSync().associate { it.id to it.name }- val normalizedQuery = EpgNameNormalizer.normalize(query)val trimmedQuery = query.trim()+ // Build escaped LIKE pattern; blank query fetches all (up to limit per source)+ val pattern = if (trimmedQuery.isBlank()) {+ "%"+ } else {+ val escaped = trimmedQuery+ .replace("\\", "\\\\")+ .replace("%", "\\%")+ .replace("_", "\\_")+ "%$escaped%"+ }+return assignments.flatMap { assignment ->val sourceName = sourceNamesById[assignment.epgSourceId].orEmpty()- epgChannelDao.getBySource(assignment.epgSourceId)- .asSequence()- .filter { candidate ->- if (trimmedQuery.isBlank()) {- true- } else {- candidate.xmltvChannelId.contains(trimmedQuery, ignoreCase = true) ||- candidate.displayName.contains(trimmedQuery, ignoreCase = true) ||- candidate.normalizedName.contains(normalizedQuery, ignoreCase = true)- }- }+ epgChannelDao.searchBySource(assignment.epgSourceId, pattern, limit).map { candidate ->EpgOverrideCandidate(epgSourceId = assignment.epgSourceId,@@ -421,7 +463,6 @@ class EpgSourceRepositoryImpl @Inject constructor(iconUrl = candidate.iconUrl)}- .toList()}.sortedWith(compareBy<EpgOverrideCandidate>({ it.epgSourceName.lowercase() }, { it.displayName.lowercase() }, { it.xmltvChannelId.lowercase() })).take(limit)}diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 77f7b08e..28182f7c 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -113,7 +113,7 @@ class MovieRepositoryImpl @Inject constructor(override fun getMovies(providerId: Long): Flow<List<Movie>> =preferencesRepository.parentalControlLevel.flatMapLatest { level ->- if (level == 2) movieDao.getByProviderUnprotected(providerId)+ if (level >= 3) movieDao.getByProviderUnprotected(providerId)else movieDao.getByProvider(providerId)}.map { list -> list.map { it.toDomain() } }@@ -122,7 +122,7 @@ class MovieRepositoryImpl @Inject constructor(ensureXtreamCategoryLoaded(providerId, categoryId, fetchIfMissing = true, refreshStaleInBackground = true)emitAll(preferencesRepository.parentalControlLevel.flatMapLatest { level ->- if (level == 2) movieDao.getByCategoryUnprotected(providerId, categoryId)+ if (level >= 3) movieDao.getByCategoryUnprotected(providerId, categoryId)else movieDao.getByCategory(providerId, categoryId)}.map { list -> list.map { it.toDomain() } })@@ -140,7 +140,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByCategoryPage(providerId, categoryId, limit, offset),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -157,7 +157,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByCategoryPreview(providerId, categoryId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -172,7 +172,7 @@ class MovieRepositoryImpl @Inject constructor(preferencesRepository.parentalControlLevel) { categories, level ->val requestedIds = categoryIds.toSet()- val filtered = if (level == 2) categories.filter { !it.isAdult && !it.isUserProtected } else categories+ val filtered = if (level >= 3) categories.filter { !it.isAdult && !it.isUserProtected } else categoriesfiltered.filter { it.categoryId in requestedIds } to level}.flatMapLatest { (filteredCategories, level) ->if (filteredCategories.isEmpty()) {@@ -190,7 +190,7 @@ class MovieRepositoryImpl @Inject constructor(val categoryGroupFlows: List<Flow<Pair<Long?, List<Movie>>>> = filteredCategories.map { cat ->movieDao.getByCategoryPreview(providerId, cat.categoryId, limitPerCategory).map { entities ->- val items = if (level == 2) entities.filter { !it.isUserProtected } else entities+ val items = if (level >= 3) entities.filter { !it.isUserProtected } else entities(cat.categoryId as Long?) to items.map { it.toDomain() }}}@@ -205,7 +205,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getTopRatedPreview(providerId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -217,7 +217,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getFreshPreview(providerId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -275,7 +275,7 @@ class MovieRepositoryImpl @Inject constructor(preferencesRepository.parentalControlLevel) { entities: List<CategoryEntity>, level: Int ->val mapped = entities.map { it.toDomain() }- if (level == 2) {+ if (level >= 3) {mapped.filter { !it.isAdult && !it.isUserProtected }} else {mapped@@ -312,7 +312,7 @@ class MovieRepositoryImpl @Inject constructor(safeMovieSearchFlow(movieDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -525,7 +525,7 @@ class MovieRepositoryImpl @Inject constructor(safeMovieSearchFlow(movieDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities ->entities.map { it.toDomain() }.rankSearchResults(normalizedSearch) { it.name }@@ -544,7 +544,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getTopRatedByCategoryPreview(query.providerId, categoryId, fetchLimit),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -559,7 +559,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getFreshByCategoryPreview(query.providerId, categoryId, fetchLimit),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -574,7 +574,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -582,7 +582,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}}@@ -598,7 +598,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getFavoritesByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -606,7 +606,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getFavoritesByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -620,7 +620,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getInProgressByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -628,7 +628,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getInProgressByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -642,7 +642,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getUnwatchedByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -650,7 +650,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getUnwatchedByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -664,7 +664,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByWatchCountCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -672,7 +672,7 @@ class MovieRepositoryImpl @Inject constructor(movieDao.getByWatchCountProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}else -> null@@ -821,7 +821,7 @@ class MovieRepositoryImpl @Inject constructor(if (batch.isEmpty()) {return}- val visibleBatch = if (parentalLevel == 2) {+ val visibleBatch = if (parentalLevel >= 3) {batch.filterNot { it.isUserProtected }} else {batchdiff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 41bea9ba..0d2dfa77 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -94,7 +94,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByProvider(providerId),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -109,7 +109,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByCategory(providerId, categoryId),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -130,7 +130,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -147,7 +147,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByCategoryPreview(providerId, categoryId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -162,7 +162,7 @@ class SeriesRepositoryImpl @Inject constructor(preferencesRepository.parentalControlLevel) { categories, level ->val requestedIds = categoryIds.toSet()- val filtered = if (level == 2) categories.filter { !it.isAdult && !it.isUserProtected } else categories+ val filtered = if (level >= 3) categories.filter { !it.isAdult && !it.isUserProtected } else categoriesfiltered.filter { it.categoryId in requestedIds } to level}.flatMapLatest { (filteredCategories, level) ->if (filteredCategories.isEmpty()) {@@ -180,7 +180,7 @@ class SeriesRepositoryImpl @Inject constructor(val categoryGroupFlows: List<Flow<Pair<Long?, List<Series>>>> = filteredCategories.map { cat ->seriesDao.getByCategoryPreview(providerId, cat.categoryId, limitPerCategory).map { entities ->- val items = if (level == 2) entities.filter { !it.isUserProtected } else entities+ val items = if (level >= 3) entities.filter { !it.isUserProtected } else entities(cat.categoryId as Long?) to items.map { it.toDomain() }}}@@ -195,7 +195,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getTopRatedPreview(providerId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -207,7 +207,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getFreshPreview(providerId, limit),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -223,7 +223,7 @@ class SeriesRepositoryImpl @Inject constructor(preferencesRepository.parentalControlLevel) { entities: List<CategoryEntity>, level: Int ->val mapped = entities.map { it.toDomain() }- if (level == 2) {+ if (level >= 3) {mapped.filter { !it.isAdult && !it.isUserProtected }} else {mapped@@ -253,7 +253,7 @@ class SeriesRepositoryImpl @Inject constructor(safeSeriesSearchFlow(seriesDao.search(providerId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level: Int ->- if (level == 2) {+ if (level >= 3) {entities.filter { !it.isUserProtected }} else {entities@@ -444,7 +444,7 @@ class SeriesRepositoryImpl @Inject constructor(safeSeriesSearchFlow(seriesDao.searchByCategory(query.providerId, categoryId, ftsQuery, SEARCH_RESULT_LIMIT)),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities ->entities.map { it.toDomain() }.rankSearchResults(normalizedSearch) { it.name }@@ -463,7 +463,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getTopRatedByCategoryPreview(query.providerId, categoryId, fetchLimit),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -478,7 +478,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getFreshByCategoryPreview(query.providerId, categoryId, fetchLimit),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -493,7 +493,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -501,7 +501,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}}@@ -517,7 +517,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getFavoritesByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -525,7 +525,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getFavoritesByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -539,7 +539,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getInProgressByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -547,7 +547,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getInProgressByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -561,7 +561,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getUnwatchedByCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -569,7 +569,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getUnwatchedByProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}normalizedSearch.isBlank() &&@@ -583,7 +583,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByWatchCountCategoryPage(query.providerId, categoryId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } })}@@ -591,7 +591,7 @@ class SeriesRepositoryImpl @Inject constructor(seriesDao.getByWatchCountProviderPage(query.providerId, fetchLimit, 0),preferencesRepository.parentalControlLevel) { entities, level ->- if (level == 2) entities.filter { !it.isUserProtected } else entities+ if (level >= 3) entities.filter { !it.isUserProtected } else entities}.map { entities -> entities.map { it.toDomain() } }}else -> null@@ -744,7 +744,7 @@ class SeriesRepositoryImpl @Inject constructor(if (batch.isEmpty()) {return}- val visibleBatch = if (parentalLevel == 2) {+ val visibleBatch = if (parentalLevel >= 3) {batch.filterNot { it.isUserProtected }} else {batchdiff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.ktindex 011e3a64..aa2a2b07 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerM3uImporter.kt@@ -60,11 +60,11 @@ internal class SyncManagerM3uImporter(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."+ val validEpgUrl = parsedHeader.tvgUrl?.takeIf { UrlSecurityPolicy.validateOptionalEpgUrl(it) == null }+ if (parsedHeader.tvgUrl != null && validEpgUrl == null) {+ warnings += "Ignored unsupported EPG URL from playlist header."}- header = parsedHeader.copy(tvgUrl = secureEpgUrl)+ header = parsedHeader.copy(tvgUrl = validEpgUrl)}) { entry ->parsedCount++diff --git a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.ktindex fdad9386..69d0fd5d 100644--- a/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/EpgSourceRepositoryImplTest.kt@@ -5,6 +5,7 @@ import android.content.Contextimport android.net.Uriimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.epg.EpgResolutionEngine+import com.streamvault.data.local.DatabaseTransactionRunnerimport com.streamvault.data.local.dao.ChannelEpgMappingDaoimport com.streamvault.data.local.dao.EpgChannelDaoimport com.streamvault.data.local.dao.EpgProgrammeDao@@ -44,6 +45,9 @@ class EpgSourceRepositoryImplTest {private val xmltvParser: XmltvParser = mock()private val okHttpClient: OkHttpClient = mock()private val resolutionEngine: EpgResolutionEngine = mock()+ private val transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }private lateinit var repository: EpgSourceRepositoryImpl@@ -59,7 +63,8 @@ class EpgSourceRepositoryImplTest {epgProgrammeDao = epgProgrammeDao,xmltvParser = xmltvParser,okHttpClient = okHttpClient,- resolutionEngine = resolutionEngine+ resolutionEngine = resolutionEngine,+ transactionRunner = transactionRunner)}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex d16282ed..f651eb35 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -565,7 +565,9 @@ class SyncManagerTest {}@Test- fun `sync_m3u_ignores_insecure_streams_and_header_epg`() = runTest {+ fun `sync_m3u_accepts_http_header_epg_and_ignores_insecure_streams`() = runTest {+ // HTTP EPG URLs in the playlist header are now accepted (same policy as playlist sources).+ // Only stream entry URLs with unsupported schemes (e.g. ftp://) are silently dropped.val playlist = tempFolder.newFile("mixed-playlist.m3u")playlist.writeText("""@@ -589,7 +591,32 @@ class SyncManagerTest {val insertedChannels = argumentCaptor<List<com.streamvault.data.local.entity.ChannelImportStageEntity>>()verify(catalogSyncDao, atLeastOnce()).insertChannelStages(insertedChannels.capture())assertThat(insertedChannels.allValues.flatten()).hasSize(1)- assertThat((state as SyncState.Partial).warnings).contains("Ignored insecure EPG URL from playlist header.")+ // HTTP EPG header URL should be accepted — no EPG URL warning+ assertThat((state as SyncState.Partial).warnings).doesNotContain("Ignored unsupported EPG URL from playlist header.")+ // ftp:// stream URL should still be rejected+ assertThat(state.warnings).contains("Ignored 1 insecure playlist stream URL(s).")+ }++ @Test+ fun `sync_m3u_ignores_unsupported_scheme_header_epg`() = runTest {+ val playlist = tempFolder.newFile("ftp-epg-playlist.m3u")+ playlist.writeText(+ """+ #EXTM3U x-tvg-url="ftp://epg.example.com/guide.xml"+ #EXTINF:-1 group-title="News",Channel+ https://live.example.com/channel.ts+ """.trimIndent()+ )++ val provider = sampleProvider(ProviderType.M3U).copy(serverUrl = playlist.toURI().toString(), m3uUrl = playlist.toURI().toString())+ val mgr = buildManager(providerType = ProviderType.M3U, providerEntity = provider)++ val result = mgr.sync(1L, force = true)+ advanceUntilIdle()++ assertThat(result.isSuccess).isTrue()+ assertThat((mgr.currentSyncState(1L) as SyncState.Partial).warnings)+ .contains("Ignored unsupported EPG URL from playlist header.")}// ── M3U sync failure ────────────────────────────────────────────diff --git a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.ktindex afc15cdc..5b1307da 100644--- a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt+++ b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt@@ -53,6 +53,16 @@ class UrlSecurityPolicyTest {assertThat(UrlSecurityPolicy.isAllowedStreamEntryUrl("https://example.com/live.ts%09Injected: true")).isFalse()}+ @Test+ fun `validateOptionalEpgUrl allows http https and local files`() {+ assertThat(UrlSecurityPolicy.validateOptionalEpgUrl("")).isNull()+ assertThat(UrlSecurityPolicy.validateOptionalEpgUrl("http://epg.example.com/guide.xml")).isNull()+ assertThat(UrlSecurityPolicy.validateOptionalEpgUrl("https://epg.example.com/guide.xml")).isNull()+ assertThat(UrlSecurityPolicy.validateOptionalEpgUrl("content://downloads/public_downloads/guide.xml")).isNull()+ assertThat(UrlSecurityPolicy.validateOptionalEpgUrl("ftp://epg.example.com/guide.xml"))+ .isEqualTo("EPG URLs must use HTTP, HTTPS, or select a local file.")+ }+@Testfun `sanitizeImportedAssetUrl drops unsupported schemes`() {assertThat(UrlSecurityPolicy.sanitizeImportedAssetUrl("ftp://example.com/logo.png")).isNull()diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex c15d8ddc..acef1771 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -15,6 +15,8 @@ All notable product changes are recorded in this document.- Added incremental channel loading for large providers.- Added incremental search results with automatic loading on scroll.- Added automatic paging when reaching the end of the channel list.+- Added HTTP conditional requests (`ETag` / `If-Modified-Since`) to EPG refresh — unchanged feeds return `304 Not Modified` and skip download and parse entirely.+- Added EPG channel icon fallback — channels without a provider logo now use the icon from their matched EPG source.#### System & Settings- Added timeshift storage manager with automatic cleanup.@@ -22,13 +24,33 @@ All notable product changes are recorded in this document.- Added automatic update download option.- Added options to show/hide “All Channels” and “Recent Channels”.- Added "Hidden" option to Live TV Channel Numbering — hides channel numbers everywhere in the app (channel lists, player overlay, EPG, zap banner).-+#### Recording+- Schedule recordings directly from the EPG guide — Record, Record Daily, and Record Weekly buttons on any future program.+- Configurable pre/post recording padding (start early / end late) — applied automatically to all scheduled recordings.+- WiFi-only recording restriction — optionally prevent recordings from starting on mobile data.+- HLS recording quality cap — respects the per-network video quality preference instead of always picking the highest bandwidth variant.+- Recording conflict resolution dialog — shows which recordings overlap and offers to replace them instead of just showing an error.+- Recording status indicators on channel cards — REC and Scheduled badges on Dashboard and Search screens.+- Skip single occurrence of a recurring recording without cancelling the series.+- Search and filter in the recordings browser by title, channel, or status.+- Stalled-capture watchdog — recordings that stop receiving data for 60 seconds are automatically aborted.+- Automatic retry with exponential backoff on transient network failures during capture.+- Low disk space pre-flight check — scheduled recordings fail early with a clear message instead of writing partial files.+- Push notification on recording failure with channel name and reason.+- Completed recordings open in the player with resume position tracking.#### VOD- "Filter & Sort" button now shows active selections as a subtitle (e.g. "Favorites · Rating") and highlights with brand colour when non-default settings are applied — applies to both Movies and Series, modern and classic views.#### Search- Long-pressing a channel, movie, or series in Search now opens a context menu with Add/Remove Favorites, Hide, and Parental Lock/Unlock actions — consistent with the same actions available in other screens.+#### Parental Controls+- Added **PRIVATE** protection level — adult categories appear in the sidebar with a PIN lock, but are excluded from Search, EPG Guide, All Channels, and Recent so individual channel names (e.g. explicit titles) are never shown in mixed lists.+- PRIVATE is now the default protection level for new installs.+- Existing users with the old HIDDEN level are automatically migrated to the new HIDDEN (level 3); users previously on LOCKED remain on LOCKED.+- Protection level selection dialog upgraded to a title + description card layout matching other mode-selection dialogs.+- LOCKED level now correctly shows adult content in all views (EPG, Search, All Channels, Recent) — it previously blocked adult content from the EPG guide despite that not being the intended behaviour.+#### Database & Sync- Search now indexes title, cast, director, and genre with BM25 relevance ranking — results are ordered by match quality.- Program reminders — tap any guide entry to be notified before a show starts without scheduling a full recording.@@ -97,6 +119,21 @@ All notable product changes are recorded in this document.- Fixed `.gz` EPG feeds being double-decompressed and failing to parse.- Fixed blank URL accepted past the scheme validator when adding an EPG source.- Fixed EPG list always appearing empty after a fresh install (list was never populated into the UI state).+- Fixed EPG sync rejecting plain HTTP URLs — M3U playlist header EPG (`x-tvg-url`), manual EPG sources, and M3U provider EPG fields now accept HTTP and HTTPS, matching the same policy already applied to Xtream providers.+- Fixed EPG search not escaping `%` and `_` wildcards, returning too many results on certain queries.+- Fixed "now & next" picking the wrong next program when programs had gaps.+- Fixed EPG channel-matching trimming whitespace inconsistently between ID index build and lookup.+- Fixed EPG source refresh not recording errors on failure, leaving stale "refreshing" status.+- Fixed EPG source refresh replacing live data non-atomically — writes now go to a staging area and swap in a single transaction.+- Fixed EPG override-candidates query loading all channels into memory instead of filtering in SQL.+- Fixed `MAX_EPG_SIZE_BYTES` duplicated across two repositories — now defined once in shared config.+- Fixed EPG source refresh not being rate-limited, allowing rapid repeated fetches.+- Fixed `jumpToDay` and `jumpToPrimeTime` using UTC epoch modulo instead of local-timezone arithmetic.+- Fixed guide timeline and program times using hardcoded 24-hour format instead of respecting the device locale.+- Fixed program progress bar gated on `isNowPlaying` flag instead of computing from timestamps.+- Fixed `EpgUiState` using `System.currentTimeMillis()` in default field values, causing inconsistent anchor times.+- Fixed guide search query not debounced, firing a database query on every keystroke.+- Fixed `nowTicker` flow restarting a new timer per collector instead of sharing a single upstream.#### VOD- Fixed "New to Old" sort not working for Movies. The `added` timestamp is now correctly used across the full pipeline, matching how series sorting works.diff --git a/docs/EPG_GRID_CODE_REVIEW.md b/docs/EPG_GRID_CODE_REVIEW.mddeleted file mode 100644index 8da22e81..00000000--- a/docs/EPG_GRID_CODE_REVIEW.md+++ /dev/null@@ -1,928 +0,0 @@-# EPG Grid — Production Code Review--**Reviewed:** April 2026-**Files:** `EpgScreen.kt`, `EpgGridComponents.kt`, `EpgHeroComponents.kt`,-`EpgControlComponents.kt`, `EpgScreenDialogs.kt`, `EpgViewModel.kt`-------## Executive Summary--The EPG grid has a solid architectural foundation: a well-separated ViewModel pipeline,-proper `LazyColumn` row virtualization, a `CompositionLocal`-based clock that limits-recomposition, and a layered fallback strategy for missing guide data. The most important-issues that need fixing before a premium release are:--1. **Critical rendering bug** — program cells use `padding(start = itemStart)` inside a- `Box`, so overlapping or back-to-back programs stack at the wrong pixel column instead- of being positioned absolutely.-2. **Desynchronized horizontal scroll** — the timeline header and per-row program strips- share a single `ScrollState` instance but the header scroll and each row scroll are- driven independently; they can diverge on fast D-pad navigation.-3. **Hard channel cap at 60** — `MAX_CHANNELS = 60` silently truncates large provider- catalogues with no pagination, making the guide unusable for providers with hundreds- or thousands of live channels.-4. **30-second "now" clock visible only inside `GuideNowProvider`** — three separate- `GuideNowProvider {}` wrappers exist in `EpgScreen.kt` (hero, grid, dialog), each- producing an **independent** 30-second ticker; they can disagree by up to 30 s,- causing the "now" bar and the hero progress indicator to be out of sync.-5. **`ImmersiveGuideHero` calls `System.currentTimeMillis()` directly** — bypassing- `LocalGuideNow`, so the hero progress bar does not respect the composition clock and- will show a stale value after any data refresh.-------## 1. Correctness--### 1.1 Program Positioning Bug (Critical)--**Location:** `EpgGridComponents.kt` — `ProgramItem` and the inner `Box` in `EpgRow`.--```kotlin-// ProgramItem-modifier = Modifier- .padding(start = itemStart) // ← WRONG: padding, not absolute offset- .width(itemWidth)-```--`padding(start = itemStart)` inside a `Box` layout places the item relative to the-previous sibling's right edge, not relative to the `Box` origin. With a standard-`Row` or `forEach` inside a `Box`, every program cell shifts by the sum of all-preceding `itemStart` values. The result: programs are visually displaced to the-right, back-to-back programs overlap, and the "now" column aligns with nothing real.--**Fix:** Use `Modifier.absoluteOffset(x = itemStart)` or `Modifier.offset(x = itemStart)`-(the latter is layout-relative but equivalent in a `Box`):--```kotlin-modifier = Modifier- .offset(x = itemStart)- .width(itemWidth)- // … rest unchanged-```--The same pattern must be applied to the "now" line indicator inside `GuideTimelineHeader`.--### 1.2 Now-Indicator Offset in the Timeline Header--**Location:** `EpgGridComponents.kt` — `GuideTimelineHeader`, inner `Box`.--```kotlin-Box(- modifier = Modifier- .padding(start = totalTimelineWidth * elapsedRatio) // same padding bug- .width(2.dp)- .fillMaxHeight()- .background(Primary)-)-```--Same issue as 1.1: `padding(start = …)` stacks on top of whatever precedes this `Box`-child instead of anchoring it at the exact ratio position.--**Fix:** `.offset(x = totalTimelineWidth * elapsedRatio)`.--### 1.3 Cross-Midnight Handling--`guideWindowStart = anchorTime - LOOKBACK_MS` and `guideWindowEnd = anchorTime + LOOKAHEAD_MS`-span a fixed relative range from the anchor, which is correct. However:--- `jumpToDay()` computes time-of-day as `anchorTime.mod(DAY_SHIFT_MS)`, using Kotlin's- `Long.mod()`. When `anchorTime` is negative (any time before epoch — unlikely in- practice but possible if a test passes 0L as "uninitialised") the result is negative,- shifting the window to the previous calendar day. Add a floor clamp: if `anchorTime`- is below epoch milliseconds for year 2000, treat it as `System.currentTimeMillis()`.--- The XMLTV parser and EPG providers are cross-midnight aware (they store UTC epoch- milestamps), so stored programs are safe. The UI correctly clamps `visibleStart` and- `visibleEnd` in `ProgramItem`. **No additional issue here.**--### 1.4 Program Width Clamping Without Gap--```kotlin-val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))-```--Adding `+ 1` ms prevents zero-width but results in a 1-ms-wide item that renders at-`minimumItemWidth`. At 40–56dp minimum this is fine for display, but the program will-appear at the position of the *clamped end*, not its true start. A program whose-`endTime ≤ windowStart` should be **filtered out** before reaching `ProgramItem`.-Consider pre-filtering the program list in `buildGuideDisplaySnapshot`.--### 1.5 Overlapping Programs--The code renders every item in `programs.forEach { … }` with no overlap detection.-If the upstream EPG data contains two programs whose time ranges intersect, both items-will be rendered and one will visually overlap the other (especially with the current-padding-offset bug amplifying the displacement). Add a pre-pass that splits or drops-overlapping programs before building the `programsByChannel` map.-------## 2. Scrolling & Navigation--### 2.1 Header and Row Scroll Desynchronization--**Location:** `EpgGrid`, `EpgRow`.--```kotlin-val horizontalScrollState = rememberScrollState()-// passed to: GuideTimelineHeader(scrollState = horizontalScrollState)-// and to each: EpgRow(scrollState = horizontalScrollState)-```--A single `ScrollState` is created at the `EpgGrid` level and shared. This is the-correct intent. However, inside `GuideTimelineHeader` and `EpgRow` the `Box` that-wraps the timeline content uses a `Row` that applies `.horizontalScroll(scrollState)`.-When D-pad focus moves **inside one row's program strip** (via TV focus traversal),-the `BringIntoViewRequester` on the focused item may call `bringIntoView()` which-scrolls **that row's scroll state** but not the header, because `bringIntoView`-triggers the nearest `ScrollableContainer` ancestor, not the shared instance.--**Fix:** Replace per-row `horizontalScroll` with a single `LazyRow` or `HorizontalPager`-for the program strip, or use `nestedScroll` to propagate scroll commands up to the-shared `ScrollState`. A simpler approach: use a single full-width `Canvas` or-`BoxWithConstraints` to draw all program cells at absolute pixel positions, removing-the nested horizontal scroll entirely.--### 2.2 D-Pad Focus Traversal Inside the Program Strip--Each `ProgramItem` is a `TvClickableSurface` rendered inside a `forEach` loop, which-means the Compose TV focus system sees them as ordinary focusables in document order.-For a very wide timeline (multiple hours), D-pad right from the last *visible* program-will try to focus the next item which may be 300dp to the right and offscreen.-**The programme strip does not auto-scroll to bring the focused item into view** because-there is no `BringIntoViewRequester` wired to `ProgramItem`.--**Fix:** Add a `BringIntoViewRequester` to each `ProgramItem` and call-`bringIntoViewRequester.bringIntoView()` inside the `onFocusChanged` when `isFocused`-becomes true:--```kotlin-val bringIntoViewRequester = remember { BringIntoViewRequester() }-val scope = rememberCoroutineScope()-modifier = Modifier- .bringIntoViewRequester(bringIntoViewRequester)- .onFocusChanged {- if (it.isFocused) scope.launch { bringIntoViewRequester.bringIntoView() }- }-```--### 2.3 Channel-Rail Focus Not Restored After Data Refresh--**Location:** `EpgScreen.kt` — `LaunchedEffect(uiState.channels, uiState.programsByChannel)`.--```kotlin-LaunchedEffect(uiState.channels, uiState.programsByChannel) {- // resolves focusedChannel / focusedProgram in-memory …-}-```--This effect correctly resolves the model objects, but there is no call to restore-**Compose focus** to the previously focused item. If the channel list refreshes (e.g.-after a forced refresh or after the first background sync), focus drops to the system-default (typically row 0). On TV this is jarring.--**Fix:** Store the previously focused `itemKey` (from `epgChannelKey`) in a-`rememberSaveable`, then after the `LazyColumn` layout stabilises use a-`LaunchedEffect(channelKeys)` with `listState.scrollToItem(restoredIndex)` and-`focusRequester.requestFocus()` on the matching row.--### 2.4 Fast Channel-Zap Not Supported from Grid--There is no D-pad shortcut from within the grid to immediately play the focused channel-(e.g. pressing `OK` on the channel-rail goes to the channel play action, but a number-key or `KEYCODE_CHANNEL_UP/DOWN` is not handled). The grid does not intercept-`onPreviewKeyEvent` at the screen level.--**Fix:** Add a `Modifier.onPreviewKeyEvent` at the `EpgGrid` or `FullEpgScreen` level-to handle `KEYCODE_CHANNEL_UP` / `KEYCODE_CHANNEL_DOWN` for fast zap and-`KEYCODE_PROG_RED` / `KEYCODE_PROG_GREEN` for jump-to-now / options shortcuts.-------## 3. Performance--### 3.1 Hard Channel Cap Is Not a Virtualization Strategy--```kotlin-const val MAX_CHANNELS = 60-```--The `LazyColumn` in `EpgGrid` already virtualizes vertical rows lazily. The `MAX_CHANNELS`-cap was introduced as a performance guard but it silently discards channels 61+ with no-indication to the user. For a provider with 500 live channels this makes the guide-incomplete. The real bottleneck is the **program loading step**, not the render.--**Recommended fix:** Remove the cap from the UI pass; apply pagination or an infinite-scroll-trigger at the ViewModel layer so the first 60 channels load eagerly and the next page-loads when the user scrolls near the bottom:--```kotlin-// In EpgGrid LazyColumn:-if (index == channels.size - 10) {- LaunchedEffect(Unit) { onLoadMore() }-}-```--### 3.2 `buildList` for Hour Markers Re-Runs on Every Recomposition--**Location:** `GuideTimelineHeader`.--```kotlin-val hourMarkers = buildList { … } // not inside remember {}-```--The hour-marker list is rebuilt on every recomposition of the header. The header-recomposes every 30 seconds (from `rememberGuideNow`) but also whenever `windowStart`,-`windowEnd`, or scroll position changes. Wrap in `remember`:--```kotlin-val hourMarkers = remember(windowStart, windowEnd, markerStepMs) {- buildList { … }-}-```--Note: the per-row `markers` list already does this correctly — the header should match-that pattern.--### 3.3 Grid-Line Markers Drawn Per-Row--**Location:** `EpgRow` — inner `Box`.--```kotlin-markers.forEach { marker ->- Box(modifier = Modifier- .padding(start = totalTimelineWidth * markerRatio)- …- .background(Color.White.copy(alpha = 0.08f)))-}-```--For 60 rows × N markers (e.g. 14 half-hours = 14 markers), that is 840 `Box`-composables per full render, each containing a `background` draw call. Each has the-same x-positions and appearance. This is expensive and visually redundant: drawing the-grid lines on a single `Canvas` overlay placed below the `LazyColumn` (or as a fixed-background `Box`) would replace 840 composable slot allocations with one `Canvas.drawLine`-loop.--### 3.4 Multiple Independent `rememberGuideNow()` Instances--**Location:** `EpgScreen.kt` lines 322, 364, 503.--```kotlin-GuideNowProvider { GuideHeroSection(…) } // ticker A-GuideNowProvider { EpgGrid(…) } // ticker B-GuideNowProvider { CompactGuideProgramDialog(…) } // ticker C-```--Each `GuideNowProvider` wraps an independent `produceState` coroutine ticking every-30 seconds. Three coroutines run instead of one, and they can be up to 30 s out of-phase. The "now" bar in the grid can display a different time from the hero progress-bar.--**Fix:** Hoist a single `GuideNowProvider` above all three call sites, or move-`rememberGuideNow()` into the ViewModel as a `StateFlow<Long>` driven by a single-`tickerFlow`.--### 3.5 `ImmersiveGuideHero` Bypasses the Composition Clock--**Location:** `EpgHeroComponents.kt` — `ImmersiveGuideHero`.--```kotlin-val currentTime = System.currentTimeMillis()-```--This is a direct wall-clock read outside the `LocalGuideNow` composition local, so it-does not update unless recomposition is triggered by something else. The progress bar-and "Updated N min ago" label can show stale values indefinitely after the initial-composition. Replace with `currentGuideNow()` (already provided by the surrounding-`GuideNowProvider`).--### 3.6 Channel Logo Loading Without Placeholders--`ChannelLogoBadge` is called once per visible row. If the logo URL is absent or slow,-nothing prevents a row-height shift when the image loads. Ensure the badge provides a-fixed-size placeholder (it references `channelName` for a letter fallback, but verify-that the fallback occupies the same pixel dimensions as a loaded image).-------## 4. State Handling--### 4.1 Scroll Position Lost on Window Shift--When the user calls `jumpForward()` or `jumpBackward()`, `guideWindowStart/End` changes,-which triggers a full recomposition of `EpgGrid`. Because `horizontalScrollState` is-created with `rememberScrollState()` (no saved state key tied to the window), the scroll-position resets to 0 on every window shift. For a "jump forward 30 min" action the user-expects the visible content to advance proportionally, not snap to the left edge.--**Fix:** After `jumpForwardHalfHour()`, programmatically scroll the `horizontalScrollState`-by the equivalent pixel distance. In the ViewModel expose the scroll target as a-`SharedFlow<Long>` (milliseconds to scroll to); observe it in the grid and call-`scrollState.animateScrollTo(targetPixelOffset)`.--### 4.2 `focusedProgram` State Matching Is Fragile--```kotlin-focusedProgram = focusedProgram?.let { focused ->- resolvedPrograms.firstOrNull {- it.startTime == focused.startTime &&- it.endTime == focused.endTime &&- it.title == focused.title- }-}-```--Matching by `(startTime, endTime, title)` instead of a stable ID means that a metadata-update (e.g., a slightly corrected title from a reparsed XMLTV feed) will lose the focus-target and fall back to the current live program. If `Program` has a stable `id` or-`(channelEpgId, startTime)` composite key, prefer that.--### 4.3 `pendingLockedAction` Reset Race--**Location:** `EpgScreen.kt` — PIN dialog confirm handler.--```kotlin-scope.launch {- if (viewModel.verifyPin(pin)) {- val action = pendingLockedAction- …- pendingLockedAction = null- action?.let(::executeLockedGuideAction)- } else {- pinError = context.getString(R.string.home_incorrect_pin)- }-}-```--`pendingLockedAction` is `remember { mutableStateOf<LockedGuideAction?>(null) }` (not-`rememberSaveable`), so it is lost on configuration change (screen rotation on a phone-form-factor, or activity recreation). The user enters the PIN, rotation happens, the-action is null, and nothing plays. For a TV-only product this is low risk but worth-noting.-------## 5. Time Sync & Guide Updates--### 5.1 No Periodic Auto-Refresh of Guide Data--The guide viewport auto-advances when the user calls `jumpForward()`, but the underlying-EPG data (`programsByChannel`) is only refreshed when:-- The user presses "Refresh" manually, or-- `refreshNonce` is incremented.--If the app runs for 6+ hours without a user interaction (common on always-on TV-devices), live programs will start showing as "expired" and a new day's schedule will-not appear. The ViewModel has no `WorkManager` or `TickerFlow` that calls `refresh()`-when the guide window falls entirely in the past.--**Fix:** In `init` or `observeGuideBase`, start a coroutine that compares-`System.currentTimeMillis()` to `guideWindowEnd` every 15 minutes and calls-`refresh()` when the window is about to expire:--```kotlin-viewModelScope.launch {- while (true) {- delay(15 * 60_000L)- val state = _uiState.value- if (System.currentTimeMillis() > state.guideWindowEnd - HALF_HOUR_SHIFT_MS) {- refresh()- }- }-}-```--### 5.2 Auto-Scroll to "Now" Not Automatic on Screen Entry--The guide opens at the stored `guideAnchorTime`, which may be several hours in the past-if the user left the guide at 18:00 yesterday. The "Jump to Now" button corrects this,-but it requires user action. On first entry (when `startupCategoryId` is non-null and-`isStartupSelection == true`), `guideAnchorTime` should be initialised to-`System.currentTimeMillis()`.--Currently `restoreGuidePreferences()` restores the persisted anchor time unconditionally.-Add a staleness check:--```kotlin-val saved = preferencesRepository.guideAnchorTime.first()-val now = System.currentTimeMillis()-if (saved != null && abs(saved - now) < 6 * 60 * 60_000L) {- guideAnchorTime.value = saved-} // else leave at now (default)-```-------## 6. Edge Cases--### 6.1 Zero-Duration Programs--```kotlin-val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L) // window safe-// but no guard for program duration:-val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration).coerceIn(0f, 1f)-```--If `program.startTime == program.endTime` (a zero-duration entry from a malformed-XMLTV feed), `visibleStart == visibleEnd` (before the `+ 1` guard), and `widthRatio`-is 0. The item renders at `minimumItemWidth` but at the *start* position. This is-acceptable, but the `+ 1` guard in `visibleEnd` should be documented as intentional-and the filter in `loadGuidePrograms` should discard entries where `endTime <= startTime`.--### 6.2 Extremely Long Programs (24-hour slot)--A program spanning the full window (e.g., a 24-hour slot for a channel with no detailed-schedule) produces `widthRatio ≈ 1.0`, so `itemWidth = totalTimelineWidth`. This is-visually correct (a single cell spanning the full strip) but may cause layout issues if-`totalTimelineWidth` is very large (`calculatedTimelineWidth` can exceed the viewport-by 8× for a 24-hour window), producing a cell wider than the screen. The minimum width-clamp doesn't help because the cell is *too large*, not too small. Clamp the maximum-cell width to `totalTimelineWidth` and test that horizontal scrolling still works.--### 6.3 Missing EPG for All Channels (guide stale)--The `isGuideStale` flag is set and shown as a badge in the hero. However the main-grid area still renders normally, just showing "No schedule" text in each row. This is-the right degraded mode. Consider adding a subtle banner above the grid when stale-(similar to the `LinearProgressIndicator` already shown during refresh) so the user-knows EPG is stale even when scrolled past the hero area.--### 6.4 Empty `programs` List Alignment--```kotlin-if (programs.isEmpty()) {- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Text(stringResource(R.string.epg_no_schedule_short), color = OnSurfaceDim)- }-}-```--The "no schedule" box fills the entire `totalTimelineWidth` wide strip, which is-correct. No issue here — just note that this Box should also display at the same-vertical baseline as program cells to avoid a visual height difference.-------## 7. Responsiveness & Input Latency--### 7.1 `loadGuidePrograms` Blocks the Data Fetch on the IO Dispatcher--```kotlin-private suspend fun loadGuidePrograms(…): GuideProgramsResult {- return withContext(Dispatchers.IO) {- // 3 sequential steps: resolved → legacy → Xtream fallback- val resolvedPrograms = runCatching { epgRepository.getResolvedProgramsForChannels(…) }- val legacyPrograms = if (unresolvedChannels.isNotEmpty()) { … }- val fallbackProgramsByChannel = fetchXtreamGuideFallback(…)- }-}-```--Steps 2 and 3 are sequential, but they operate on disjoint channel sets. They can be-parallelised with `coroutineScope { async { … } async { … } awaitAll() }`, removing-the serial delay when both a legacy query and an Xtream fallback query are needed.--### 7.2 `loadCombinedGuidePrograms` Is Fully Sequential--```kotlin-groupedPrograms.forEach { (providerId, providerChannels) ->- val result = loadGuidePrograms(…)- putAll(result.programsByChannel)-}-```--For a combined profile with N providers, guide programs are loaded one provider at a-time. Switch to `coroutineScope { groupedPrograms.map { async { loadGuidePrograms(…) } }.awaitAll() }`.--### 7.3 No Debounce on `jumpForwardHalfHour` / `jumpBackward`--A user holding D-pad on the jump button fires a rapid succession of `jumpForward()` calls,-each triggering `updateGuideAnchorTime()` which persists to `PreferencesRepository` and-emits a new upstream value that invalidates the entire guide data load. Add a debounce:--```kotlin-private val _pendingAnchorTime = MutableStateFlow(guideAnchorTime.value)-// in init:-viewModelScope.launch {- _pendingAnchorTime.debounce(300).collect { anchorTime ->- guideAnchorTime.value = anchorTime- preferencesRepository.setGuideAnchorTime(anchorTime)- }-}-fun updateGuideAnchorTime(ms: Long) { _pendingAnchorTime.value = ms }-```-------## 8. UI Clarity--### 8.1 Current Program Highlight Is Subtle--```kotlin-containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,-```--20% alpha over `SurfaceElevated` is barely visible, especially on OEM TV panels with-boosted brightness or OLED pixel representation. Consider 30–40% alpha or a distinct-left-border accent of 4dp width in `Primary` color for the current program cell.--### 8.2 Favorite Badge vs. Catch-Up Badge Conflict--```kotlin-if (isFavorite || channel.catchUpSupported) {- Box { Text(if (channel.catchUpSupported) "Replay" else "★") }-}-```--Only one badge is shown even when both conditions are true: a catch-up channel that is-also a favorite shows only "Replay", silently dropping the favorite indicator. Show-both badges side by side, or use a combined badge.--### 8.3 Channel Number Formatting--```kotlin-text = if (channel.number > 0) "${channel.number}. ${channel.name}" else channel.name-```--For channels numbered 1–9, this renders as "1. ChannelName" which looks inconsistent-next to "10. OtherChannel" because no zero-padding is applied. On TV UIs with a fixed-channel-rail width, consider right-aligning the number in a fixed-width column rather-than concatenating it into the name string.--### 8.4 Timeline Header Does Not Scroll Visually During D-Pad Navigation--The timeline header is rendered separately above the `LazyColumn`. As the user D-pads-down through channels and a program item scrolls horizontal state, the header should-follow. Because both share the same `scrollState`, the header does visually scroll —-but only when the user is **inside a program strip**. When the user is focused on the-channel-rail column, horizontal scroll is not possible at all. This means the header-time label and the visible programs can be misaligned if the user scrolled the programs-and then moved focus to the channel rail and back.--**Fix:** Lock horizontal scroll to the program strip interaction only; the header-always reflects the current `scrollState.value` which is correct. No code change-needed, but verify on device that the `LazyColumn` scroll does not inadvertently reset-`horizontalScrollState` to 0 on item recomposition.-------## 9. Error Resilience--### 9.1 Silent Failure on `runCatching` in `loadGuidePrograms`--```kotlin-val resolvedPrograms = runCatching {- epgRepository.getResolvedProgramsForChannels(…)-}.getOrElse { emptyMap() }-```--Failures are swallowed silently and degrade to `emptyMap()`. The `failedScheduleCount`-tracks missing channels but does not surface the underlying exception. For debugging-purposes, at least log the exception at `ERROR` level:--```kotlin-}.onFailure { e -> Timber.e(e, "EPG resolve failed for provider $providerId") }- .getOrElse { emptyMap() }-```--Without this, reproducing EPG data regressions in production requires device-side-logcat captures from users.--### 9.2 Xtream Fallback Does Not Honour `MAX_XTREAM_GUIDE_FALLBACK_CHANNELS`--```kotlin-val fallbackChannels = missingChannels.take(MAX_XTREAM_GUIDE_FALLBACK_CHANNELS)-```--`MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 24`, so when a provider serves 60 channels but-none have XMLTV guide data, only the first 24 get the Xtream API fallback. Channels-25–60 display as "No schedule" with no retry path. Consider raising the limit or making-it configurable, or at least noting it in the stale-badge text.--### 9.3 Combined Guide With No Member Providers--```kotlin-private fun combinedProviderIdsFlow(profileId: Long): Flow<List<Long>> = flow {- emit(combinedM3uRepository.getProfile(profileId)?.members.orEmpty())-}.map { members -> members.filter { it.enabled }.map { it.providerId } }-```--This is a **cold, non-repeating flow**. If the profile's members list changes while-the guide is open (e.g., the user enables a provider in Settings), the combined guide-will not update because the flow only emits once. Convert it to a `Flow` that-re-reads from the database reactively (e.g., a Room DAO query flow rather than a-`getProfile()` suspend call).-------## 10. Security & Data Integrity--### 10.1 `program.description.ifBlank` Falls Through to Unfiltered String--**Location:** `ImmersiveGuideHero`.--```kotlin-text = program.description.ifBlank { stringResource(R.string.epg_hero_no_program_description) }-```--Program descriptions from XMLTV are free text. If a provider injects HTML entities-or markup in the description field (common with some European XMLTV feeds), it will-render as raw text. This is acceptable for a `Text` composable (no injection path),-but ensure the XMLTV parser stores `.trim()` descriptions to avoid leading/trailing-whitespace rendering.-------## 11. Additional Bugs & Architectural Gaps--### 11.1 `epgChannelKey` Includes `index` — Unstable LazyColumn Diff (G-21)--**Location:** `EpgGridComponents.kt` — `epgChannelKey`.--```kotlin-internal fun epgChannelKey(channel: Channel, index: Int): String {- return "channel:${channel.id}:…:$index"-}-```--Including `index` in the stable key means that if any channel shifts position in the-list (e.g. a category filter changes, or channels are reordered after a refresh), every-item **at or below** the first changed position gets a new key. Compose treats a new-key as a new item: it removes the old slot, creates a new one, and redraws — even-if the channel data is identical. Remove `index` from the key; `channel.id` + `channel.streamId`-+ `epgId` + `channel.name.trim()` is already sufficiently unique without it.--### 11.2 Horizontal Scroll Not Positioned to "Now" on Guide Entry (G-22)--Even when the anchor time is correct, `rememberScrollState()` starts at offset 0 (the-left edge). For a 7-hour window with 1 hour of lookback, the "now" position is at-1/7 ≈ 14% of the total timeline width — off the left edge of the viewport on any-screen narrower than the full timeline. The user must manually scroll right to see-current programs.--**Fix:** Add a `LaunchedEffect(Unit)` inside `EpgGrid` that, after the first layout-pass, scrolls `horizontalScrollState` to `(totalTimelineWidth * nowRatio - viewportWidth / 2)`-clamped to `[0, maxScrollValue]`, centering "now" on screen:--```kotlin-val nowRatio = ((now - guideWindowStart).toFloat() / totalDuration).coerceIn(0f, 1f)-LaunchedEffect(Unit) {- val targetPx = ((totalTimelineWidth * nowRatio).value * density.density -- (timelineViewportWidth / 2).value * density.density).toInt().coerceAtLeast(0)- horizontalScrollState.scrollTo(targetPx)-}-```--This is distinct from G-20, which fixes anchor-time staleness; G-22 fixes the pixel-offset within an already-correct time window.--### 11.3 No Numeric Digit (0–9) Remote-Key Channel Zap (G-23)--Section 2.4 recommended handling `KEYCODE_CHANNEL_UP/DOWN`, but the larger gap is-**direct numeric input**: standard IR remotes have 0–9 keys. All commercial EPGs-implement a digit-accumulation overlay: the user presses 1, 5, ENTER → channel 15.--**Fix:** At the `FullEpgScreen` level, intercept `KeyEvent.KEYCODE_0` through-`KeyEvent.KEYCODE_9` in `onPreviewKeyEvent`. Accumulate digits in a `rememberSaveable`-string, display an overlay chip showing the current number, and after a 1.2-second-idle timeout resolve the accumulated number to the matching `channel.number` and-scroll the `LazyColumn` to that row (or play the channel directly).--### 11.4 `Program.imageUrl` Never Rendered (G-24)--The data layer populates `Program.imageUrl` from XMLTV `<icon>` elements and Xtream-metadata, but neither `CompactGuideProgramDialog` nor `ImmersiveGuideHero` renders it.-This is a significant visual gap: sport events, movies, and popular series typically-have high-quality banner art in EPG sources.--**Fix:**-- In `ImmersiveGuideHero`: replace the `ChannelLogoBadge` with an `AsyncImage` that- loads `program.imageUrl` when non-null, falling back to the channel logo.-- In `CompactGuideProgramDialog`: add a `16:9` banner above the program title when- `program.imageUrl` is non-null.--### 11.5 "Live Now" Mode (`GuideChannelMode.ANCHORED`) Not Discoverable (G-25)--`GuideChannelMode.ANCHORED` filters the channel list to only those with a program-airing at the anchor time — exactly the "what's on now" view users expect on first-open. However it is accessible only via the **options overlay** (three taps away),-buried among density and schedule filters. Most users will never find it.--**Fix:** Add a `LIVE NOW` toggle chip directly in `GuideToolbarRow` between the-category chip and "Jump to Now". One tap activates ANCHORED mode; tapping again-returns to ALL. The toolbar already has room for a fourth chip.--### 11.6 No Incremental Window Preloading (G-26)--Every `jumpForward()` / `jumpBackwardHalfHour()` triggers a complete re-fetch of-`programsByChannel` for the new window. Until the coroutine completes the user sees-blank program strips. For a provider with 60 channels × 14 half-hour markers this is-typically 200–400 ms of latency on a local network and 1–2 s on a slow connection.--**Fix:** Maintain a two-window sliding cache in the ViewModel:-- `windowCache: Map<LongRange, GuideProgramsResult>` keyed by `(windowStart, windowEnd)`.-- When the user navigates forward, eagerly pre-fetch the *next* 3-hour window in the- background while still displaying the current one.-- When a pre-fetched window becomes active, show it instantly.-- Evict windows that no longer overlap the displayable range.--### 11.7 `Program` Lacks a Stable Composite Room Key (G-27)--G-14 recommends matching focused programs by a stable ID rather than `(startTime,-endTime, title)`, and G-21 recommends removing `index` from the `LazyColumn` key.-Both fixes ultimately depend on programs having a stable, unique identifier.--The `ProgramEntity` Room table currently has no surrogate primary key that survives a-provider re-sync. Add a composite unique index on `(provider_id, channel_epg_id,-start_time)` and expose it as `Program.stableKey: String` in the domain model-(`"$providerId:$channelEpgId:$startTime"`). Use this key wherever programs need to be-compared across data refreshes.-------## 12. Missing Features--### 12.1 Schedule Recording from the Guide (F-01)--The app has a complete `RecordingManager`, `ScheduleRecording` use case, and the-live player overlay already exposes one-time, daily, and weekly scheduling. The EPG-grid is the **primary** place users schedule recordings on every commercial STB, yet-`CompactGuideProgramDialog` has no "Record" or "Schedule" button.--**Fix:** Add a third action button to `CompactGuideProgramDialog` that calls-`viewModel.scheduleRecording(channel, program)`. For past programs the button should-be hidden; for future programs show "Schedule"; for currently-airing shows show-"Record from now". Wire to the existing `ScheduleRecording` use case — no new business-logic required.--### 12.3 Inline Live Preview in the Hero (F-03)--When focus lands on a channel row, the hero updates with metadata — but there is no-live video. The HomeScreen already implements the exact pattern needed: an auxiliary-`PlayerEngine` instance with `bypassAudioFocus = true`, started after a focus-dwell-delay, torn down on `Lifecycle.ON_STOP` and `onDispose`.--**Fix:** Add a `PlayerSurface` inside `ImmersiveGuideHero` that starts after a-configurable dwell threshold (e.g., 1500 ms). Use `@AuxiliaryPlayerEngine` injection-identical to the HomeScreen implementation. Respect the user's "disable guide preview"-preference if one exists, and ensure the surface is released at the same lifecycle-boundaries as the HomeScreen preview.--### 12.4 Genre and Rating Filter in the Toolbar (F-04)--`Program.genre` and `Program.rating` are populated by the data layer and stored in-the database, but the guide toolbar has no genre or rating filter. For a provider-with 300+ channels carrying News, Sport, Movies, Kids, and Documentary, a one-tap-genre filter is the fastest content-discovery path — faster than category browsing.--**Fix:** Add a genre chip to `GuideToolbarRow` that, when tapped, opens a compact-bottom-sheet picker (reuse `GuideCategoryPickerDialog` style) listing distinct genres-from `programsByChannel.values.flatMap { … }.mapNotNull { it.genre }.distinct()`. The-selected genre is then applied in `buildGuideDisplaySnapshot` as an additional filter-layer on `candidateProgramsByChannel`.--### 12.5 EPG Coverage Badge on Category Toolbar Chip (F-05)--`channelsWithSchedule` and `totalChannelCount` are computed in the ViewModel and-displayed in the hero badge (`GuideHeroBadge`). However, once the user scrolls down-past the hero area the coverage information disappears. The category toolbar chip-only shows the category name.--**Fix:** Append the coverage ratio to the category chip label:--```kotlin-label = "$selectedCategoryName ${channelsWithSchedule}/${totalChannelCount}",-```--A low ratio (e.g., "Sport 2/40") immediately tells the user EPG is thin for that-category without requiring a scroll back to the hero.--### 12.6 Phone and Tablet Layout (F-06)--The guide is designed exclusively for TV (1280dp+ landscape). `rememberIsTelevisionDevice()`-is already imported in `EpgScreen.kt` and `EpgControlComponents.kt`, and-`BoxWithConstraints` is already used in `EpgGrid`. Despite this, no compact layout-branch exists.--On a phone the channel rail is 180dp wide and the program strip is several thousand dp-wide — the guide is effectively broken.--**Fix (suggested layout for compact screens):**-- **Channel list** (`maxWidth < 600dp`): a `LazyColumn` of channel-rail items only,- full-width, with no horizontal program strip.-- **Program list**: when the user selects a channel, show a `LazyColumn` of that- channel's programs for the full day as a detail pane (master–detail pattern using- `TwoPaneLayout` or a back-stack push).-- **Hero**: collapse to a `64dp` card showing the focused channel + current program.--`rememberIsTelevisionDevice()` should drive the top-level layout branch so TV behaviour-is fully unchanged.--### 12.7 "Now & Next" Compact Guide Mode (F-07)--The full timeline grid is the only available guide view. Many users — especially on-first open — want a quick "what's on right now and what's coming up next?" list without-navigating the horizontal timeline. `getNowAndNext()` already exists in `EpgRepository`-and is unused in the guide surface.--**Fix:** Add a `GuideChannelMode.NOW_AND_NEXT` branch to `buildGuideDisplaySnapshot`.-In that mode, replace the `EpgGrid` with a `LazyColumn` of compact rows, each showing:-- Channel logo + name (same channel-rail cell)-- Current program title + progress bar (using `Program.progressPercent()`)-- Next program title + start time--No new network calls or data-layer code are required — `getNowAndNext` is already-available for every channel. Add a "Now & Next" chip to `GuideToolbarRow` alongside-the existing `GuideChannelMode.ALL` and `GuideChannelMode.ANCHORED` options.--### 12.8 Multi-Day Visual Calendar Picker (F-08)--Day navigation is available through `jumpToPreviousDay()` / `jumpToNextDay()` and the-arrow-key-accessible jump buttons, but there is no visual date widget. Navigating more-than 2–3 days forward or backward requires many sequential D-pad presses with no visual-feedback about the destination date. Every commercial STB EPG exposes a 7–14 day-calendar as a primary navigation element.--**Fix:** Add a `GuideDayPickerRow` — a horizontally scrollable strip of day chips-above the category selector — showing 7 days centred on today. Each chip displays the-day abbreviation and date number (e.g. "Fri 18"). Selecting a chip calls the existing-`jumpToDay(dayStartMillis)`.--Important: day boundary computation must use local time, not UTC epoch division (see-G-06 above):-```kotlin-val zone = TimeZone.getDefault().toZoneId()-val dayStart = LocalDate.now(zone).plusDays(offset)- .atStartOfDay(zone).toInstant().toEpochMilli()-```--### 12.9 EPG Resolution Quality Visible to the User (F-09)--`EpgResolutionSummary` tracks total channels, exact-ID matches, normalized-name-matches, and unresolved counts after every resolution pass, but none of this reaches-the user. When a channel shows "No schedule" the user cannot tell whether:-- No EPG source is assigned to their provider-- The source has data but the channel ID / name didn't match-- The source was last refreshed weeks ago--`F-05` (coverage badge in the toolbar) covers the narrow case of *how many channels-have any schedule in the current window*. This item is the broader feedback layer.--**Fix:**-- **Settings — EPG Sources screen**: after each refresh show the per-source resolution- breakdown ("matched 312 / 450 channels — 138 unresolved") sourced from- `EpgSourceRepository.getResolutionSummary(providerId)`.-- **`CompactGuideProgramDialog`**: when `programsByChannel` for the channel is empty,- query `EpgSourceRepository.getChannelMapping(providerId, channelId)` and display a- contextual reason chip:- - `EpgSourceType.NONE` → "No EPG source covers this provider"- - `EpgMatchType.NORMALIZED_NAME` with empty programmes → "EPG matched by name — no schedule for today"- - No mapping row → "This channel could not be matched to any EPG source"-- **Debug overlay** (behind a dev flag): show the `ChannelEpgMapping` confidence score- and `matchType` below the channel name in the guide rail.-------## Summary of Actionable Items--| Priority | ID | Issue | Location |-|----------|-------|-------|----------|-| Critical | G-01 | Program cells use `padding(start=…)` instead of `offset(x=…)` — all programs render at wrong pixel positions | `EpgGridComponents` — `ProgramItem`, `GuideTimelineHeader` now-bar |-| Critical | G-02 | Three independent `GuideNowProvider` wrappers; "now" bar and hero can be 30 s out of sync | `EpgScreen.kt` lines 322, 364, 503 |-| High | G-03 | `ImmersiveGuideHero` uses `System.currentTimeMillis()` instead of `currentGuideNow()` | `EpgHeroComponents.kt` |-| High | G-04 | `MAX_CHANNELS = 60` silently truncates provider catalogues with no pagination or user feedback | `EpgViewModel` |-| High | G-05 | No periodic auto-refresh; guide goes stale after window expires on always-on devices | `EpgViewModel.init` |-| High | G-06 | `jumpToPrimeTime` / `jumpToDay` use UTC midnight, not local midnight | `EpgViewModel` |-| High | G-07 | `loadCombinedGuidePrograms` loads per-provider sequentially; should be parallel | `EpgViewModel` |-| Medium | G-08 | `buildList` for hour markers not inside `remember {}` — rebuilds every recomposition | `EpgGridComponents — GuideTimelineHeader` |-| Medium | G-09 | Grid-line markers drawn as 840+ `Box` composables; should be a single `Canvas` overlay | `EpgGridComponents — EpgRow` |-| Medium | G-10 | D-pad focus on program item does not trigger `bringIntoView`; program strip does not auto-scroll | `EpgGridComponents — ProgramItem` |-| Medium | G-11 | Scroll position resets to 0 on every window time-shift | `EpgGrid` / `EpgViewModel` |-| Medium | G-12 | Composite guide `combinedProviderIdsFlow` is a cold one-shot flow; member changes not reflected | `EpgViewModel` |-| Medium | G-13 | No debounce on `jumpForwardHalfHour` / anchor-time updates; rapid D-pad fires many data reloads | `EpgViewModel.updateGuideAnchorTime` |-| Medium | G-14 | `focusedProgram` match uses title+time instead of stable ID; breaks on metadata updates | `EpgScreen.kt` — `LaunchedEffect` |-| Medium | G-15 | Focus not restored to previously focused row after data refresh | `EpgScreen.kt` |-| Low | G-16 | Current program highlight alpha 0.2 is hard to see on OEM TV panels | `EpgGridComponents — ProgramItem` |-| Low | G-17 | Favorite + catch-up badge: only one shows when both are true | `EpgGridComponents — EpgRow` |-| Low | G-18 | `runCatching` in `loadGuidePrograms` silently swallows EPG fetch errors | `EpgViewModel` |-| Low | G-19 | Xtream fallback hard-capped at 24 channels; channels 25–60 never get fallback EPG | `EpgViewModel` |-| Low | G-20 | Auto-scroll to "now" not applied on first guide entry if persisted anchor is stale | `EpgViewModel.restoreGuidePreferences` |-| Medium | G-21 | `epgChannelKey` includes `index`; any channel reorder causes full LazyColumn diff and redraws all visible cells | `EpgGridComponents — epgChannelKey` |-| Medium | G-22 | Horizontal scroll not positioned to "now" pixel offset on guide entry; user sees left edge even with correct anchor time | `EpgGrid` — `LaunchedEffect(Unit)` missing |-| Medium | G-23 | No numeric digit (0–9) remote-key accumulation for direct channel-number zap | `EpgScreen.kt` — `onPreviewKeyEvent` |-| Medium | G-24 | `Program.imageUrl` populated by data layer but never rendered in `CompactGuideProgramDialog` or `ImmersiveGuideHero` | `EpgScreenDialogs`, `EpgHeroComponents` |-| Medium | G-25 | `GuideChannelMode.ANCHORED` ("on right now") buried in options overlay; not reachable with a single toolbar action | `EpgHeroComponents — GuideToolbarRow` |-| High | G-26 | No incremental window preloading; every time-shift triggers a full data reload and blank-grid flash | `EpgViewModel` |-| High | G-27 | `Program` has no stable composite Room key; fixes for G-14 and G-21 both depend on one | `data` — `ProgramEntity` |-| High | F-01 | **Missing feature:** No "Record" or "Schedule recording" action in the program dialog despite `RecordingManager` and `ScheduleRecording` use case existing | `EpgScreenDialogs — CompactGuideProgramDialog` |-| High | F-03 | **Missing feature:** No inline live preview in the hero when focus dwells on a channel row; HomeScreen auxiliary `PlayerEngine` pattern is directly reusable | `EpgHeroComponents — ImmersiveGuideHero` |-| Medium | F-04 | **Missing feature:** No genre or rating filter chip in the toolbar despite `Program.genre` and `Program.rating` being populated | `EpgHeroComponents — GuideToolbarRow` |-| Medium | F-05 | **Missing feature:** No category EPG-coverage badge on the toolbar category chip; `channelsWithSchedule` / `totalChannelCount` exists but only shown in the hero | `EpgHeroComponents — GuideToolbarRow` |-| High | F-06 | **Missing feature:** No phone/tablet layout; guide is designed exclusively for 1280dp+ TV screens and is unusable on handheld form factors | `EpgScreen.kt` / `EpgGrid` |-| High | F-07 | **Missing feature:** No "Now & Next" compact guide mode; `getNowAndNext()` exists in the repository but is unused in the guide surface | `EpgViewModel` / `EpgScreen.kt` |-| Medium | F-08 | **Missing feature:** No multi-day visual calendar picker; day navigation requires many sequential key presses with no date feedback | `EpgScreen.kt` / `EpgViewModel` |-| Medium | F-09 | **Missing feature:** EPG resolution quality (matched/unresolved counts, match type, source staleness) is never surfaced to the user | `SettingsEpgSection`, `EpgScreenDialogs` |-diff --git a/docs/EPG_MULTI_SOURCE_ARCHITECTURE.md b/docs/EPG_MULTI_SOURCE_ARCHITECTURE.mddeleted file mode 100644index 854d1c92..00000000--- a/docs/EPG_MULTI_SOURCE_ARCHITECTURE.md+++ /dev/null@@ -1,209 +0,0 @@-# EPG Multi-Source Architecture--## Overview--StreamVault supports multiple EPG (Electronic Program Guide) sources per provider. External XMLTV sources can be added, assigned to providers, and matched against channels using ID- or name-based matching. The system resolves the best EPG source per channel at sync time and persists the result for fast guide rendering.--## Data Flow--```-User adds EPG source (Settings)- │- ▼-┌─────────────────────────────────────────────────────────────────┐-│ EpgSourceRepository.addSource(name, url) │-│ → Insert into `epg_sources` table │-│ → Assign to provider via `provider_epg_sources` │-└───────────┬─────────────────────────────────────────────────────┘- │- SyncManager (full sync or EPG-only)- │- ▼-┌─────────────────────────────────────────────────────────────────┐-│ 1. Refresh provider-native EPG (existing `programs` table) │-│ 2. Refresh external sources (EpgSourceRepositoryImpl) │-│ → Download XMLTV (.xml or .xml.gz) │-│ → Parse channels → `epg_channels` table │-│ → Parse programmes → `epg_programmes` table │-│ 3. Run resolution engine (EpgResolutionEngine) │-│ → Match each channel to best source │-│ → Persist results in `channel_epg_mappings` table │-└───────────┬─────────────────────────────────────────────────────┘- │- Guide Grid render (EpgViewModel)- │- ▼-┌─────────────────────────────────────────────────────────────────┐-│ EpgRepository.getResolvedProgramsForChannels() │-│ → Read `channel_epg_mappings` for provider │-│ → EXTERNAL mappings → query `epg_programmes` table │-│ → PROVIDER mappings → query `programs` table (legacy) │-│ → Merge into unified Map<lookupKey, List<Program>> │-│ → Fallback: Xtream on-demand API for unmapped channels │-└─────────────────────────────────────────────────────────────────┘-```--## Resolution Algorithm--For each provider channel, the `EpgResolutionEngine` evaluates matches in priority order:--| Priority | Match Type | Confidence | Source | Description |-|----------|-------------------|------------|------------|-------------|-| 1 | MANUAL | 1.0 | External | User-overridden mapping (future feature) |-| 2 | EXACT_ID | 1.0 | External | Channel's `epgChannelId` matches XMLTV `channel@id` |-| 3 | NORMALIZED_NAME | 0.7 | External | Normalized channel name matches XMLTV `<display-name>` |-| 4 | PROVIDER_NATIVE | 0.5 | Provider | Provider has EPG data for this channel |-| 5 | NONE | 0.0 | — | No EPG coverage |--When multiple external sources are assigned, they are evaluated in assignment priority order (lowest number = highest priority). First match wins.--## Database Schema (v25)--### `epg_sources`-Global registry of external XMLTV EPG URLs.--| Column | Type | Notes |-|--------|------|-------|-| id | INTEGER PK | Auto-increment |-| name | TEXT | User-facing label |-| url | TEXT UNIQUE | XMLTV URL (HTTPS) |-| enabled | INTEGER | 1/0 |-| priority | INTEGER | Global ordering |-| last_refresh_at | INTEGER | Epoch millis |-| last_success_at | INTEGER | Epoch millis, null if never |-| last_error | TEXT | Last error message |-| created_at | INTEGER | Epoch millis |-| updated_at | INTEGER | Epoch millis |--### `provider_epg_sources`-Many-to-many: which external sources are assigned to which providers.--| Column | Type | Notes |-|--------|------|-------|-| id | INTEGER PK | Auto-increment |-| provider_id | INTEGER FK | → providers.id (CASCADE) |-| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |-| priority | INTEGER | Per-provider ordering |-| enabled | INTEGER | 1/0 |--### `epg_channels`-Channels from external XMLTV sources. Rebuilt on each source refresh.--| Column | Type | Notes |-|--------|------|-------|-| id | INTEGER PK | Auto-increment |-| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |-| xmltv_channel_id | TEXT | From `<channel id="...">` |-| display_name | TEXT | From `<display-name>` |-| normalized_name | TEXT | Lowercased, accent/symbol-stripped |-| icon_url | TEXT | From `<icon src="...">` |--### `epg_programmes`-Programme data from external XMLTV sources. Rebuilt on each source refresh.--| Column | Type | Notes |-|--------|------|-------|-| id | INTEGER PK | Auto-increment |-| epg_source_id | INTEGER FK | → epg_sources.id (CASCADE) |-| xmltv_channel_id | TEXT | Maps to epg_channels |-| start_time, end_time | INTEGER | Epoch millis |-| title, description | TEXT | Programme info |-| category, lang, rating, image_url | TEXT | Optional metadata |--### `channel_epg_mappings`-Precomputed resolution results. One row per provider channel.--| Column | Type | Notes |-|--------|------|-------|-| id | INTEGER PK | Auto-increment |-| provider_channel_id | INTEGER FK | → channels.id |-| provider_id | INTEGER FK | → providers.id (CASCADE) |-| source_type | TEXT | EXTERNAL / PROVIDER / NONE |-| epg_source_id | INTEGER | Nullable, FK → epg_sources.id |-| xmltv_channel_id | TEXT | Nullable |-| match_type | TEXT | EXACT_ID / NORMALIZED_NAME / MANUAL / PROVIDER_NATIVE |-| confidence | REAL | 0.0–1.0 |-| is_manual_override | INTEGER | 1/0 |-| updated_at | INTEGER | Epoch millis |--## Key Classes--| Class | Module | Purpose |-|-------|--------|---------|-| `EpgSource`, `ProviderEpgSourceAssignment`, etc. | domain | Domain models |-| `EpgSourceRepository` | domain | Interface for source management |-| `EpgSourceRepositoryImpl` | data | CRUD, download, ingestion |-| `EpgResolutionEngine` | data | Resolution algorithm + resolved queries |-| `EpgNameNormalizer` | data | Name normalization for fuzzy matching |-| `XmltvParser.parseStreamingWithChannels()` | data | Streaming channel+programme parser |-| `XmltvParser.maybeDecompressGzip()` | data | Transparent .gz support |-| `EpgViewModel.loadGuidePrograms()` | app | Resolved → legacy → Xtream fallback |--## Backward Compatibility--- The existing `programs` table and all existing queries remain unchanged-- Provider-native EPG continues to work exactly as before-- If no external sources are assigned, the guide falls back to legacy behavior-- Resolution is additive: external sources enhance, never remove, existing EPG coverage-- Migration 24→25 is non-destructive (creates new tables only)--## Matching Strategy--Channel-to-source matching uses a two-tier approach:--1. **Exact ID match** — the channel's `epgChannelId` (from `tvg-id` in M3U, or provider API) is compared directly against `<channel id="...">` in the XMLTV source. This is the strongest signal (confidence 1.0) and is always preferred.--2. **Normalized name match** — if no exact ID match exists, the channel's display name is normalized via `EpgNameNormalizer` (lowercase, trim, strip accents/punctuation/separators, remove common quality suffixes like HD/FHD/4K) and compared against the pre-normalized `normalized_name` column in `epg_channels`. Confidence is 0.7.--When multiple external sources are assigned to a provider, they are evaluated in their assignment priority order. The first source that produces a match wins. This prevents ambiguity and ensures deterministic results.--Fuzzy matching is deliberately conservative to avoid wrong mappings — there is no Levenshtein distance or partial substring matching.--## Refresh Flow--1. **SyncManager** triggers refresh during full provider sync or EPG-only sync-2. For each enabled external source assigned to the provider:- - `EpgSourceRepositoryImpl.refreshSource()` downloads the XMLTV URL- - `.gz` files are auto-detected via URL suffix and decompressed with `GZIPInputStream`- - The response is size-limited (200 MB) and streamed through `XmltvParser.parseStreamingWithChannels()`- - Existing data for that source is **deleted before ingestion** (atomic swap per source)- - Channels and programmes are batch-inserted (500 items per batch)- - Source `last_refresh_at`, `last_success_at`, or `last_error` are updated-3. After all source refreshes complete, `EpgResolutionEngine.resolveForProvider()` runs:- - Recomputes all channel mappings for that provider- - Preserves any existing manual overrides- - Replaces all mappings atomically via `replaceForProvider()`-4. If a refresh **fails**, the error is recorded but previously-ingested data has already been cleared for that source (current design choice favoring consistency over stale data retention)--## Conflict Resolution--The system uses a **source-selection model**, not a programme-merge model:--- Each channel gets exactly **one effective source** (external or provider-native)-- The guide grid shows **one programme timeline per channel** — no visible collisions-- When two external sources both match the same channel, the **higher-priority source** (lower priority number) wins-- External sources always beat provider-native EPG for the same channel-- Resolution is precomputed at sync time and stored in `channel_epg_mappings`, not evaluated at render time--This design avoids the complexity and UX issues of per-programme conflict fusion (overlapping time blocks, duplicate entries, inconsistent data from different sources).--## Known Limitations--1. **Source refresh deletes before inserting** — if a refresh fails mid-parse, the source's data is lost. A staging-table approach could be added for higher reliability but adds complexity.-2. **No incremental XMLTV update** — every refresh re-downloads and re-parses the full XMLTV file. Conditional HTTP (`If-Modified-Since`) is not yet implemented.-3. **Manual override UI not implemented** — the data model supports it (`is_manual_override`, `MANUAL` match type) but there is no settings screen to set per-channel overrides yet.-4. **No per-channel EPG source indicator in the guide** — the guide grid shows resolved data but doesn't visually indicate which source provided it.-5. **Name normalization is conservative** — channels with significantly different naming across sources (e.g., "BBC 1" vs "BBC One") may not auto-match. Manual override or exact ID is needed.-6. **Resolution runs for all channels** — for providers with very large channel counts (10k+), the resolution pass touches every channel. This is fast in practice but could be optimized to only re-resolve when sources change.-7. **No stale programme auto-cleanup for external sources** — `DatabaseMaintenanceManager` handles provider-native programmes via `ProgramDao.deleteOld()`, but external `epg_programmes` stale data cleanup uses the same approach.--## Future Extension Points--1. **Manual override per channel** — add a channel details screen with "Override EPG Source" action that writes a `MANUAL` mapping to `channel_epg_mappings`-2. **Per-channel EPG diagnostics** — show match type, confidence, source name, and alternative candidates on a channel info screen-3. **Conditional refresh** — use `If-Modified-Since` / `ETag` headers to skip re-download when the source hasn't changed-4. **Staging-swap refresh** — ingest into temporary tables and swap atomically, preserving old data on failure-5. **Local XMLTV file import** — add a file picker for `.xml`/`.xml.gz` files on local storage-6. **Match preview** — show exact-ID/name/unresolved counts before committing source assignment-7. **Provider EPG toggle** — allow disabling provider-native EPG entirely when external sources provide better coverage-8. **Background refresh scheduling** — periodic refresh of external sources independent of full provider syncdiff --git a/docs/db-cache-review.md b/docs/db-cache-review.mddeleted file mode 100644index 06aff72b..00000000--- a/docs/db-cache-review.md+++ /dev/null@@ -1,1303 +0,0 @@-# Production Code Review: Database & Cache Layer--**Scope**: `data/local/`, `data/repository/`, `data/sync/`, Room schema v32-**Date**: 2026-04-16-**Reviewer**: Production code audit-------## Executive Summary--The database and cache layer has solid architectural foundations: WAL mode, per-provider sync mutexes, staging-based atomic catalog replacement with fingerprint-diff updates, FTS search, comprehensive index coverage (32 migrations, 37 tables), and a maintenance worker with conditional VACUUM logic. Despite this, there are **four high-severity issues** that represent real production data loss and race-condition risks:--1. **Double GZIP decompression** in EPG refresh produces corrupt XML on misbehaving CDNs (DB-C-01)-2. **Watch-progress denormalization divergence** causes movies to appear "unwatched" even with history (DB-C-02)-3. **Provider cleanup race** in `onProviderDeleted` can leave a sync running over half-deleted data (DB-C-03)-4. **Background EPG job map registration race** can leak a completed-but-unreachable job entry (DB-ASYNC-02)--Beyond those, `CatalogSyncDao`'s N×columns correlated-subquery UPDATE is a scalability time bomb for large catalogs (DB-Q-01), VACUUM is triggered via a side-effecting `TRUNCATE` checkpoint (DB-PERF-01), and the classification cache uses a thundering-herd flush strategy (DB-CACHE-01).-------## 1. Correctness & Data Integrity--### DB-C-01 · FIXED (2026-04-17) · 🔴 HIGH · EPG double GZIP decompression--**File**: `EpgRepositoryImpl.kt`--**Status**: Fixed by adding `EpgRepository.getProgramsForChannelsSnapshot()` and routing the bulk EPG callers in `EpgViewModel` and `TvInputChannelSyncManager` through that snapshot path. `EpgRepositoryImpl.getProgramsForChannels()` also now collapses oversized requests to a single snapshot emission instead of maintaining N chunked Room observers.--**Status**: Fixed in `EpgRepositoryImpl.refreshEpg()`. The repository now skips URL-suffix gzip detection when `Content-Encoding: gzip` has already been handled, and a regression test covers the `.xml.gz` + `Content-Encoding: gzip` combination.--The request sends `Accept-Encoding: identity` to disable OkHttp's transparent decompression, then manually wraps the body stream in `GZIPInputStream` when the response has `Content-Encoding: gzip`. Immediately after, the stream is passed to `xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)`, which wraps in another `GZIPInputStream` if the URL path ends with `.xml.gz` or `.gz`.--If a misbehaving server or CDN forwards `Content-Encoding: gzip` AND the EPG URL ends in `.xml.gz` (common pattern: `epg.xml.gz` hosted behind a CDN gateway), the stream is decompressed twice. The second pass reads already-raw XML as a gzip stream, producing garbage bytes that either fail XML parsing silently or inject junk `<programme>` records into the staging table.--```kotlin-// Current (buggy path):-val httpStream = if (contentEncoding?.contains("gzip", ignoreCase = true) == true) {- GZIPInputStream(rawStream) // ← already decompressed here-} else { rawStream }-// ...-xmltvParser.maybeDecompressGzip(epgUrl, limitedStream).use { xmlInput -> // ← decompresses again if URL ends in .gz-```--**Fix**:--```kotlin-val alreadyDecompressed = contentEncoding?.contains("gzip", ignoreCase = true) == true-val httpStream: InputStream = if (alreadyDecompressed) GZIPInputStream(rawStream) else rawStream-val limitedStream = ByteLimitFilterInputStream(httpStream, MAX_EPG_SIZE_BYTES)--// Skip URL-suffix detection if Content-Encoding already handled it-val xmlInput: InputStream = if (alreadyDecompressed) limitedStream- else xmltvParser.maybeDecompressGzip(epgUrl, limitedStream)-xmlInput.use { ... }-```-------### DB-C-02 · FIXED (2026-04-17) · 🔴 HIGH · Watch-progress denormalization divergence--**Files**: `PlaybackHistoryRepositoryImpl.kt`, `Daos.kt` (MovieDao, EpisodeDao)--**Status**: Fixed in the movie unwatched queries and in `PlaybackHistoryRepositoryImpl.clearAllHistory()`. Unwatched movie filters now read the authoritative `playback_history` table instead of stale denormalized `movies.watch_progress`, and a full history clear now uses direct reset updates for movie and episode progress instead of correlated whole-table resyncs. The same authoritative-source fix was also applied to the category-scoped movie unwatched queries/counts.--`movies.watch_progress` and `episodes.watch_progress` are denormalized copies of `playback_history.resume_position_ms`. Sync is event-driven via `syncDenormalizedProgress()` on every write. The risk is in the query consumers:--**`getUnwatchedByProviderPage`** uses the denormalized field:-```sql-SELECT * FROM movies-WHERE provider_id = :providerId AND COALESCE(movies.watch_progress, 0) <= 0-```--**`getInProgressByProviderPage`** correctly joins the authoritative table:-```sql-EXISTS (SELECT 1 FROM playback_history WHERE ... AND resume_position_ms > 0 ...)-```--This inconsistency means:-- If denormalization sync fails (DB-busy exception inside an outer transaction, partial rollback, or first-install migration), `watch_progress` stays `0` while `playback_history` has real progress. Those movies appear "unwatched" — the user sees no resume indicator and the "unwatched" filter incorrectly includes them.-- After `clearAllHistory()`, `syncAllDenormalizedProgress()` runs `UPDATE movies SET watch_progress = COALESCE((SELECT ... FROM playback_history ...), 0)` — a correlated subquery per movie row for every provider. For 50,000 movies, this executes 50,000 subqueries.--**Fix for `getUnwatchedByProviderPage`** — align to the authoritative source:-```sql-SELECT * FROM movies WHERE provider_id = :providerId-AND NOT EXISTS (- SELECT 1 FROM playback_history- WHERE playback_history.provider_id = movies.provider_id- AND playback_history.content_type = 'MOVIE'- AND playback_history.content_id = movies.id- AND playback_history.resume_position_ms > 0-)-ORDER BY name ASC LIMIT :limit OFFSET :offset-```--**Fix for `clearAllHistory`** — replace the correlated sync with a direct reset:-```kotlin-// MovieDao-@Query("UPDATE movies SET watch_progress = 0, last_watched_at = 0")-suspend fun resetAllWatchProgress()--// EpisodeDao-@Query("UPDATE episodes SET watch_progress = 0, last_watched_at = 0")-suspend fun resetAllEpisodeWatchProgress()-```-------### DB-C-03 · FIXED (2026-04-17) · 🔴 HIGH · Provider cleanup race in `onProviderDeleted`--**File**: `SyncManager.kt`--**Status**: Fixed in `SyncManager.onProviderDeleted()`. The provider mutex is now removed while still inside `withProviderLock`, and provider deletion also notifies `EpgRepository` so provider-scoped EPG sync state is cleaned up in the same critical section.--```kotlin-suspend fun onProviderDeleted(providerId: Long) {- // ...- withProviderLock(providerId) { ... } // acquires mutex, does cleanup, releases- providerSyncMutexes.remove(providerId) // removes AFTER lock released-}-```--Between the lock release and `ConcurrentHashMap.remove()`, a concurrent `sync(providerId)` call invokes `computeIfAbsent(providerId) { Mutex() }` and obtains a fresh `Mutex`. The subsequent `remove(providerId)` then removes this new mutex, not the old one. The deleted provider now has no mutex entry — the next `sync(providerId)` would create yet another mutex and proceed over partially-cleaned-up data concurrently with the deletion.--**Fix** — move the remove inside the lock:-```kotlin-suspend fun onProviderDeleted(providerId: Long) {- val cancelledEpgJob = backgroundEpgJobs.remove(providerId)- cancelledEpgJob?.cancel()- withProviderLock(providerId) {- syncStateTracker.reset(providerId)- xtreamAdaptiveSyncPolicy.forgetProvider(providerId)- syncCatalogStore.clearProviderStaging(providerId)- providerSyncMutexes.remove(providerId) // ← safe: mutex is held here- }- // No remove here — already done inside the lock-}-```-------### DB-C-04 · FIXED (2026-04-17) · 🟡 MEDIUM · Clock-skew stale cache--**File**: `ContentCachePolicy.kt`--**Status**: Fixed in `ContentCachePolicy.shouldRefresh()`. Negative elapsed time now forces a refresh instead of leaving future-dated sync timestamps fresh until wall-clock time catches up.--```kotlin-fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long): Boolean =- lastSyncAt <= 0L || now - lastSyncAt >= ttlMillis-```--If the device clock was set forward during a sync (NTP correction, user adjustment, DST), `lastSyncAt` becomes a future timestamp relative to the corrected `now`. The difference `now - lastSyncAt` is negative — less than any TTL — and the cache never triggers a refresh until real time catches up. With a 24h CATALOG_TTL, a 1-hour forward clock jump suppresses refreshes for 25 hours post-correction.--**Fix**:-```kotlin-fun shouldRefresh(lastSyncAt: Long, ttlMillis: Long, now: Long): Boolean {- if (lastSyncAt <= 0L) return true- val elapsed = now - lastSyncAt- return elapsed < 0L || elapsed >= ttlMillis // negative = clock skew → force refresh-}-```-------### DB-C-05 · FIXED (2026-04-17) · 🟡 MEDIUM · Unbounded `providerRefreshMutexes` in `EpgRepositoryImpl`--**File**: `EpgRepositoryImpl.kt`--**Status**: Fixed by adding `EpgRepository.onProviderDeleted(providerId)` and wiring `SyncManager.onProviderDeleted()` to call it. `EpgRepositoryImpl` now removes dead provider mutex entries when a provider is deleted.--```kotlin-private val providerRefreshMutexes = ConcurrentHashMap<Long, Mutex>()-```--A `Mutex` is added to this map on every `refreshEpg()` call (via `providerRefreshMutex(providerId)`). When a provider is deleted, `SyncManager.onProviderDeleted()` cleans up its own data but never notifies `EpgRepositoryImpl`. Over a long app session with repeated provider additions and deletions, this map accumulates dead `Mutex` objects that are never GC'd because the map holds strong references.--**Fix**: Expose `fun onProviderDeleted(providerId: Long)` on `EpgRepositoryImpl` and call it from `SyncManager.onProviderDeleted()`:-```kotlin-fun onProviderDeleted(providerId: Long) {- providerRefreshMutexes.remove(providerId)-}-```-------### DB-C-06 · FIXED (2026-04-17) · 🟡 MEDIUM · FTS query injection surface--**Files**: `Daos.kt` (ChannelDao, MovieDao, SeriesDao)--**Status**: Fixed in the repository search flows. Channel, movie, and series FTS-backed search entry points now fail soft to empty results when SQLite rejects a malformed MATCH expression at runtime, instead of propagating `SQLiteException` to the UI layer.--All FTS search queries use `channels_fts MATCH :query` with Room parameter binding. Room prevents SQL injection, but malformed FTS expressions (`OR`, `NOT`, `NEAR/n`, unbalanced double-quotes, bare `*`) throw `SQLiteException` at runtime. The project has `FtsQueryUtils` but callers must invoke it explicitly — there is no DAO-level enforcement.--**Fix**: Apply `FtsQueryUtils.buildPrefixQuery(rawInput)` in every repository search method before calling the DAO. Add a defensive catch in each repository search method:--```kotlin-// ChannelRepositoryImpl-override fun search(providerId: Long, query: String, limit: Int): Flow<List<Channel>> {- val ftsQuery = FtsQueryUtils.buildPrefixQuery(query.trim())- ?: return flowOf(emptyList())- return channelDao.search(providerId, ftsQuery, limit)- .catch { e ->- if (e is SQLiteException) emit(emptyList())- else throw e- }- .map { ... }-}-```-------## 2. Query Quality--### DB-Q-01 · FIXED (2026-04-17) · 🔴 HIGH · CatalogSyncDao: N×columns correlated-subquery UPDATE--**File**: `CatalogSyncDao.kt`--**Status**: Fixed in `SyncCatalogStore`. The stage-apply path now reads staged rows once, diffs them against the current provider rows in Kotlin, and applies changed categories, channels, movies, and series through batched `@Update` calls instead of repeated correlated-subquery UPDATE statements.--The `updateChangedChannelsFromStage()` query updates each of the 14 updatable columns with a separate correlated subquery back to `channel_import_stage`:--```sql-UPDATE channels SET- name = (SELECT stage.name FROM channel_import_stage AS stage WHERE stage.session_id = :sessionId AND stage.provider_id = :providerId AND stage.stream_id = channels.stream_id),- logo_url = (SELECT stage.logo_url FROM channel_import_stage AS stage WHERE stage.session_id = :sessionId AND stage.provider_id = :providerId AND stage.stream_id = channels.stream_id),- ... -- 12 more identical subquery blocks-WHERE provider_id = :providerId AND EXISTS (...)-```--For a provider with 10,000 channels and 14 updatable columns, this executes up to **140,000 correlated subquery lookups per sync**. Even with an index on `(provider_id, session_id, stream_id)` in the stage table, SQLite re-evaluates each subquery independently per column per row. The same pattern exists for movies and series.--On a device with 50,000 movies, a full-catalog movie sync can spend seconds on this single UPDATE statement, blocking the Dispatchers.IO thread and stalling subsequent sync phases.--**Fix** — move diff computation to Kotlin and use a targeted entity-batch `@Update`:--```kotlin-// In SyncCatalogStore or CatalogSyncDao:-suspend fun applyChannelChanges(providerId: Long, sessionId: Long) {- val staged = catalogSyncDao.getChannelStageRows(providerId, sessionId) // single SELECT- val existing = channelDao.getByProviderSync(providerId)- val existingByStreamId = existing.associateBy { it.streamId }- val changed = staged.mapNotNull { stage ->- val current = existingByStreamId[stage.streamId] ?: return@mapNotNull null- if (current.syncFingerprint == stage.syncFingerprint) return@mapNotNull null- current.copy(name = stage.name, logoUrl = stage.logoUrl, ...) // apply diff- }- if (changed.isNotEmpty()) channelDao.updateAll(changed) // @Update batch-}-```--This replaces O(14n) subqueries with one SELECT + one batched UPDATE.-------### DB-Q-02 · FIXED (2026-04-17) · 🔴 HIGH · Correlated subquery ORDER BY for watch-count sort--**File**: `Daos.kt` (MovieDao)--**Status**: Fixed by denormalizing `watch_count` into `movies.watch_count`, backfilling it from `playback_history` in migration 32→33, and switching the provider-scoped movie watch-count sort to `ORDER BY COALESCE(movies.watch_count, 0) DESC`.--```sql-ORDER BY COALESCE((- SELECT playback_history.watch_count- FROM playback_history- WHERE playback_history.provider_id = movies.provider_id- AND playback_history.content_type = 'MOVIE'- AND playback_history.content_id = movies.id- LIMIT 1-), 0) DESC, movies.name ASC-LIMIT :limit OFFSET :offset-```--SQLite cannot use indexes to short-circuit a correlated ORDER BY before applying LIMIT. All `movies` rows are evaluated, each with a subquery lookup from `playback_history`, before `LIMIT` is applied. For a provider with 50,000 movies, this materializes 50,000 rows with 50,000 subquery lookups even when only 20 rows are needed by the UI.--**Fix**: Denormalize `watch_count` into `MovieEntity` (matching the existing `watch_progress` denormalization pattern), then query directly:--```sql-ORDER BY COALESCE(movies.watch_count, 0) DESC, movies.name ASC-LIMIT :limit OFFSET :offset-```--Sync `watch_count` the same way as `watch_progress` via `syncWatchProgressFromHistory()`.-------### DB-Q-03 · FIXED (2026-04-17) · 🟡 MEDIUM · Same correlated sort on category-scoped variant--**File**: `Daos.kt` (MovieDao — `getByWatchCountCategoryPage`)--**Status**: Fixed alongside DB-Q-02. The category-scoped movie watch-count sort now reads the denormalized `movies.watch_count` column directly instead of executing a correlated subquery per row.--Identical problem as DB-Q-02, scoped to a category. Applies the same fix: add `watch_count` to `MovieEntity` and use it directly in ORDER BY.-------### DB-Q-04 · FIXED (2026-04-17) · 🟡 MEDIUM · `getNowPlaying` captures stale timestamp on long-lived subscriptions--**File**: `EpgRepositoryImpl.kt`--**Status**: Fixed in `EpgRepositoryImpl.getNowPlaying()`. It now uses the existing `nowTicker()` refresh flow, matching `getNowAndNext()` so long-lived subscriptions reevaluate against current time instead of a one-time timestamp captured at subscription.--```kotlin-override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =- programDao.getNowPlaying(providerId, channelId, System.currentTimeMillis())- .map { it?.toDomain() }-```--`System.currentTimeMillis()` is captured once when the `Flow` is subscribed. A UI component holding this flow for > 30 minutes (e.g., a persistent EPG guide overlay) receives a "now" timestamp that is 30+ minutes stale, and programs that have since ended remain labeled "now playing." Only `getNowAndNext()` wraps in `nowTicker()`.--**Fix**:-```kotlin-override fun getNowPlaying(providerId: Long, channelId: String): Flow<Program?> =- nowTicker().flatMapLatest { now ->- programDao.getNowPlaying(providerId, channelId, now)- .map { it?.toDomain() }- }-```-------### DB-Q-05 · FIXED (2026-04-17) · 🟡 MEDIUM · Favorites `IS NULL` predicate reduces index efficiency--**File**: `Daos.kt` (MovieDao)--**Status**: Fixed with a dedicated partial index, `index_favorites_global_provider_id_content_type_content_id`, on global favorites only (`WHERE group_id IS NULL`). The query shape stays the same, but SQLite now has an index tailored to that predicate.--```sql-EXISTS (- SELECT 1 FROM favorites- WHERE favorites.content_type = 'MOVIE'- AND favorites.provider_id = movies.provider_id- AND favorites.group_id IS NULL- AND favorites.content_id = movies.id-)-```--The unique index on `favorites` is `(provider_id, content_id, content_type, group_id)`. The `group_id IS NULL` predicate on the trailing index column limits SQLite's ability to use the full index range. This subquery runs once per movie row in the outer scan — for large catalogs it degrades to O(movies × partial_index_scan).--**Fix**: Add an explicit `is_global_favorite` boolean column to `FavoriteEntity` (true when `group_id IS NULL`), maintained on insert/delete. The favorites query then becomes a simple equality predicate on an indexed column. Alternatively, use a partial index:-```sql-CREATE INDEX IF NOT EXISTS idx_favorites_global- ON favorites(provider_id, content_type, content_id)- WHERE group_id IS NULL-```-------## 3. Cache Behavior--### DB-CACHE-01 · FIXED (2026-04-17) · 🔴 HIGH · AdultContentClassifier thundering-herd cache flush--**File**: `AdultContentClassifier.kt`--**Status**: Fixed in `AdultContentClassifier`. The cache now uses bounded LRU-style eviction instead of clearing the entire map at capacity, which avoids the full-cache miss storm during large imports and removes the non-atomic `size/check/clear/insert` pattern.--```kotlin-private val classificationCache = ConcurrentHashMap<String, Boolean>()--if (classificationCache.size >= MAX_CLASSIFICATION_CACHE_SIZE) {- classificationCache.clear()-}-classificationCache[normalized] = isAdult-```--When the cache reaches 4,096 entries, the next classification call clears the entire map and repopulates with a single entry. The next ~4,095 classifications all miss the cache and re-classify from scratch (regex/string scanning). During a large catalog sync (100k+ channels), this can fire dozens of times, causing CPU spikes when the classifier re-processes all recently-seen values.--The size-check + clear + insert on `ConcurrentHashMap` is also not atomic: two threads can both observe `size >= MAX`, both call `clear()`, and both insert their entry — result is two entries in the map, both correct but the thundering herd is compounded.--**Fix** — use a synchronized LRU with bounded eviction:-```kotlin-private val classificationCache: MutableMap<String, Boolean> =- Collections.synchronizedMap(- object : LinkedHashMap<String, Boolean>(256, 0.75f, true) {- override fun removeEldestEntry(e: Map.Entry<String, Boolean>) =- size > MAX_CLASSIFICATION_CACHE_SIZE- }- )-```-------### DB-CACHE-02 · FIXED (2026-04-17) · 🟡 MEDIUM · Partial sync updates TTL timestamp; stale data treated as fresh--**File**: `SyncManager.kt` / `ContentCachePolicy.kt`--**Status**: Fixed by separating success freshness from attempt timestamps. `SyncMetadata` now tracks `lastLiveSuccess`, `lastSeriesSuccess`, and `lastEpgSuccess`, `movie` continues to use `lastMovieSuccess`, and the TTL checks in `SyncManager` now key off those success timestamps instead of the broader attempt/partial timestamps.--After a partial sync (`SyncState.Partial`), `syncMetadataRepository.updateMetadata()` stamps `lastSyncAt` with the current time. Subsequent `ContentCachePolicy.shouldRefresh()` calls return `false` for up to 24h, even though the catalog is incomplete (e.g., only categories 1–30 of 60 were fetched).--**Fix** — track successful and attempted sync timestamps separately:--```kotlin-// SyncMetadataEntity-@ColumnInfo(name = "last_successful_live_sync") val lastSuccessfulLiveSync: Long = 0L-// ...--// ContentCachePolicy-fun shouldRefresh(lastSuccessfulSyncAt: Long, ttlMillis: Long, now: Long): Boolean {- val elapsed = now - lastSuccessfulSyncAt- return lastSuccessfulSyncAt <= 0L || elapsed < 0L || elapsed >= ttlMillis-}-```--Only update `lastSuccessfulSyncAt` on `SyncState.Success`. `lastSyncAt` (attempted) continues to update on partial for backoff/retry logic.-------### DB-CACHE-03 · FIXED (2026-04-17) · 🟡 MEDIUM · DataStore incognito check blocks per playback event--**File**: `PlaybackHistoryRepositoryImpl.kt`--**Status**: Fixed in `PlaybackHistoryRepositoryImpl`. Incognito mode is now cached in a hot `StateFlow`, so playback write paths read `isIncognito.value` instead of suspending on `DataStore.data.first()` for every playback update.--```kotlin-override suspend fun recordPlayback(history: PlaybackHistory): Result<Unit> {- return try {- if (preferencesRepository.isIncognitoMode.first()) { // ← DataStore read every call- return Result.success(Unit)- }-```--`DataStore.data.first()` suspends to read preferences from disk on every `recordPlayback()` / `updateResumePosition()` / `markAsWatched()` call. If the player saves progress at 10-second intervals, this performs ~360 DataStore reads per hour of playback, each blocking the calling coroutine.--**Fix** — cache in a hot `StateFlow` initialized eagerly:-```kotlin-private val isIncognito: StateFlow<Boolean> =- preferencesRepository.isIncognitoMode- .stateIn(applicationScope, SharingStarted.Eagerly, initialValue = false)--// In each write method:-if (isIncognito.value) return Result.success(Unit)-```-------### DB-CACHE-04 · FIXED (2026-04-17) · 🟢 LOW · EPG size cap: partial protection on chunked-transfer responses--**File**: `EpgRepositoryImpl.kt`--**Status**: Fixed in both `EpgRepositoryImpl` and `EpgSourceRepositoryImpl`. When the byte-limit guard trips during chunked EPG downloads, the repositories now translate that specific oversize `IOException` into a typed `Result.error("EPG response exceeded 200 MB limit")` instead of surfacing a generic parser/download failure.--```kotlin-val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1L-if (contentLength > MAX_EPG_SIZE_BYTES) {- response.close()- return@withLock Result.error("EPG file too large...")-}-```--When the server uses chunked transfer encoding (common from CDNs), `Content-Length` is absent (`-1L`). The pre-download size check is bypassed, and protection falls entirely to the `FilterInputStream` byte counter. When that counter trips at 200 MB, it throws `IOException` mid-stream. This IOException propagates to the catch block, which deletes the staging rows and re-throws — correct, but the error surface is an opaque `IOException` rather than a typed size limit error.--**Fix**: In the catch block, detect the specific IOException message and return a typed error:-```kotlin-} catch (e: IOException) {- programDao.deleteByProvider(stagingProviderId)- if (e.message?.contains("too large") == true)- return@withLock Result.error("EPG response exceeded 200 MB limit")- return@withLock Result.error("EPG download failed: ${e.message}")-}-```-------## 4. Performance--### DB-PERF-01 · FIXED (2026-04-17) · 🔴 HIGH · VACUUM triggered via side-effecting TRUNCATE checkpoint--**File**: `DatabaseMaintenanceManager.kt`--**Status**: Fixed in `DatabaseMaintenanceManager.runVacuum()`. Maintenance now uses a non-blocking `wal_checkpoint(PASSIVE)` inspection step, only attempts a `FULL` checkpoint when WAL is already clear enough to proceed, and skips `VACUUM` if WAL pages remain instead of using `TRUNCATE` as a side-effecting pre-check.--```kotlin-val busyPages = sqliteDb.query("PRAGMA wal_checkpoint(TRUNCATE)").use { cursor ->- if (cursor.moveToFirst()) cursor.getInt(1) else 0-}-if (busyPages > 0) {- Log.w(TAG, "wal_checkpoint(TRUNCATE) had $busyPages busy pages; VACUUM skipped")- return@withContext false-}-sqliteDb.execSQL("VACUUM")-```--Two problems:--1. **Side-effecting pre-check**: `wal_checkpoint(TRUNCATE)` is not a read-only check. It attempts to checkpoint and then truncate the WAL file. Using it purely to test for busy readers is a harmful side effect — if other connections are active, the truncation attempt adds contention. `PASSIVE` mode should be used for non-blocking inspection.--2. **VACUUM blocks all readers in WAL mode**: Despite WAL's reader-writer concurrency, `VACUUM` requires an `EXCLUSIVE` database lock, blocking all Room query flows on the main thread for its entire duration. On a database ≥ 128 MB, VACUUM can take 2–5 seconds — long enough to produce an ANR warning if UI threads are blocked on Room queries.--**Fix**:-```kotlin-// Step 1: non-blocking WAL state check-val notCheckpointed = sqliteDb.query("PRAGMA wal_checkpoint(PASSIVE)").use { c ->- if (c.moveToFirst()) c.getInt(1) else -1 // column 1 = pages not yet checkpointed-}-if (notCheckpointed > 0) {- Log.d(TAG, "VACUUM deferred: $notCheckpointed WAL pages not checkpointed")- return@withContext false-}-// Step 2: full checkpoint to clear WAL before VACUUM-sqliteDb.execSQL("PRAGMA wal_checkpoint(FULL)")-// Step 3: VACUUM (only safe after full checkpoint, and no active sync per isSyncActive check)-sqliteDb.execSQL("VACUUM")-```--Long-term: move VACUUM into a WorkManager job constrained to `requiresDeviceIdle() + requiresCharging()` to prevent any foreground contention.-------### DB-PERF-02 · FIXED (2026-04-18) · 🟡 MEDIUM · EPG staging inserts in separate implicit transactions--**File**: `EpgRepositoryImpl.kt`--**Status**: Fixed in `EpgRepositoryImpl.refreshEpg()`. The staging delete plus all streamed `programDao.insertAll()` batches now run inside one explicit `transactionRunner.inTransaction` block before the final provider swap transaction, and a regression test verifies inserts happen while a transaction is active.--```kotlin-xmltvParser.parseStreaming(xmlInput) { program ->- batch.add(program.copy(providerId = stagingProviderId).toEntity())- if (batch.size >= 500) {- programDao.insertAll(batch.toList()) // ← each call = one Room auto-transaction- batch.clear()- }-}-```--For a 50,000-program XMLTV feed, this executes 100 separate Room transactions (WAL write + fsync per batch). Wrapping in a single transaction would reduce the total write cost to one fsync.--**Fix**:-```kotlin-transactionRunner.inTransaction {- xmltvParser.parseStreaming(xmlInput) { program ->- batch.add(program.copy(providerId = stagingProviderId).toEntity())- if (batch.size >= 500) {- programDao.insertAll(batch.toList())- batch.clear()- }- }- if (batch.isNotEmpty()) programDao.insertAll(batch.toList())-}-```--Note: This creates a longer-lived transaction, but since the staging table is dedicated to this provider ID and no UI reads from negative provider IDs, there is no read-contention risk. Memory pressure stays bounded by the 500-item batch.-------### DB-PERF-03 · FIXED (2026-04-17) · 🟡 MEDIUM · 24h program retention deletes active catch-up content--**File**: `DatabaseMaintenanceManager.kt`--**Status**: Fixed in `DatabaseMaintenanceManager`. Program retention now uses the maximum `catch_up_days` across stored channels, with a 24h minimum floor, instead of hard-coding every provider to one day of retained guide data.--```kotlin-private const val PROGRAM_RETENTION_MILLIS = 24L * 60 * 60 * 1000L-val deletedPrograms = programDao.deleteOld(oldProgramThreshold)-```--The maintenance job deletes all programs with `end_time < now - 24h`. Live channels with catch-up support declare `catch_up_days` (up to 7 days is common). Deleting their programs at 24h silently destroys the program guide for days 2–7 of catch-up, leaving users with empty EPG grids when browsing back in time.--**Fix**: Compute retention from the longest catch-up window among active channels:--```kotlin-// ChannelDao-@Query("SELECT COALESCE(MAX(catch_up_days), 0) FROM channels WHERE provider_id = :providerId AND catch_up_supported = 1")-suspend fun getMaxCatchUpDays(providerId: Long): Int--// DatabaseMaintenanceManager-val catchUpDays = channelDao.getMaxCatchUpDaysAcrossAllProviders()-val retentionMs = maxOf(PROGRAM_MIN_RETENTION_MILLIS, catchUpDays * 86_400_000L)-```-------### DB-PERF-04 · FIXED (2026-04-17) · 🟢 LOW · `syncAllWatchProgressFromHistory` — full provider table scan after history clear--**File**: `Daos.kt` (MovieDao)--**Status**: Fixed indirectly by the `DB-C-02` history-clear changes. `PlaybackHistoryRepositoryImpl.clearAllHistory()` now calls direct reset updates for movie and episode watch progress instead of invoking the correlated whole-table sync path after history has been cleared.--After `clearAllHistory()`, `syncAllWatchProgressFromHistory()` issues:-```sql-UPDATE movies-SET watch_progress = COALESCE((SELECT resume_position_ms FROM playback_history WHERE ...), 0)-WHERE provider_id = :providerId-```--Since history is just cleared, every COALESCE returns 0 — the subquery always misses. This scans the entire movies table executing 50,000 guaranteed-null subqueries.--**Fix** — use direct reset after a full clear (see DB-C-02 fix above):-```kotlin-@Query("UPDATE movies SET watch_progress = 0, last_watched_at = 0")-suspend fun resetAllWatchProgress()-```-------## 5. Scalability--### DB-SCALE-01 · FIXED (2026-04-18) · 🟡 MEDIUM · Chunked `combine()` thundering-herd on EPG table writes--**File**: `EpgRepositoryImpl.kt`--```kotlin-val chunks = channelIds.chunked(500)-return combine(chunks.map { chunk ->- programDao.getForChannels(providerId, chunk, startTime, endTime)-}) { arrays -> arrays.flatMap { it.toList() }... }-```--For an EPG guide with 5,000 channels, this creates 10 reactive Room query subscriptions. Every write to the `programs` table (EPG refresh, maintenance) invalidates ALL Room observers on that table, causing all 10 chunks to re-emit simultaneously, triggering a `combine` recomposition that maps and flatMaps 5,000+ program entities on each emission.--**Fix**: For bulk EPG grid loading, use a single snapshot query rather than 10 reactive flows:-```kotlin-override suspend fun getProgramsForChannelsSnapshot(providerId: Long, channelIds: List<String>, startTime: Long, endTime: Long): Map<String, List<Program>> {- return channelIds.chunked(500).flatMap { chunk ->- programDao.getForChannelsSync(providerId, chunk, startTime, endTime)- }.map { it.toDomain() }.groupBy { it.channelId }-}-```--Drive a periodic refresh from a ticker flow in the UI layer, rather than a reactive database subscription per channel.-------### DB-SCALE-02 · FIXED (2026-04-18) · 🟢 LOW · Virtual groups position reordering on large favorite sets--**Files**: `FavoriteDao`, `VirtualGroupDao`--**Status**: Fixed in `FavoriteRepositoryImpl.reorderFavorites()` and the live/VOD reorder save paths. Favorites now use sparse gap-based positions (`POSITION_STEP = 1024`) so most reorders only rewrite the affected slice instead of every row, and the UI no longer re-densifies positions to `0..n` before persisting. Existing dense lists still normalize once on their first reorder, after which subsequent moves stay localized.--Favorites are ordered by `position` (integer). Reordering via `reorderFavorites()` issues `UPDATE favorites SET position = :pos WHERE id = :id` for every entry. For a user with 500 favorites in one group, a drag-to-reorder near the top issues 500 individual UPDATE statements (one per shifted row). There is no bulk-update path.--**Fix**: Use fractional / gap-based positioning (e.g., float/double position with midpoints on reorder) to limit updates to the single moved item in most cases.-------### DB-SCALE-03 · FIXED (2026-04-18) · 🟢 LOW · `backgroundEpgScope` EPG jobs are not durable across process death--**File**: `SyncManager.kt`--**Status**: Fixed by replacing the in-process background EPG coroutine path with `BackgroundEpgSyncWorker`. `SyncManager.scheduleBackgroundEpgSync()` now enqueues unique WorkManager work per provider with `NetworkType.CONNECTED`, `batteryNotLow`, and exponential backoff, so queued EPG refresh survives process death and is not duplicated by repeated schedule requests.--```kotlin-private val backgroundEpgScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)-```--EPG refresh jobs launched via `scheduleBackgroundEpgSync()` live entirely in-process. If the app is killed mid-download (OOM, system reclaim on a low-memory TV box), the EPG sync is silently lost with no retry. The `SyncWorker` maintenance job does not cover EPG refresh.--**Fix**: Move scheduled EPG refresh to WorkManager with `KEEP` existing-work policy, `setRequiredNetworkType(NetworkType.CONNECTED)`, and exponential backoff. WorkManager persists the job and retries after process restart.-------## 6. Resilience--### DB-RES-01 · FIXED (2026-04-18) · 🟡 MEDIUM · `SyncWorker` is maintenance-only; no durable catalog or EPG sync--**File**: `SyncWorker.kt`--**Status**: Fixed by persisting a compact maintenance summary to `PreferencesRepository` DataStore after each maintenance run and surfacing it in the existing Settings diagnostics UI as a "Database Health" card with the last run time, cleanup counts, storage sizes, reclaimable bytes, and VACUUM result.--**Status**: Fixed by adding `ProviderSyncWorker`, a separate periodic WorkManager job that runs every 6 hours with network and battery-not-low constraints and calls `SyncManager.sync(force = false)` for saved providers. `SyncWorker` remains maintenance-only, but catalog and EPG freshness are now covered by durable periodic work instead of relying solely on the in-process app lifecycle.--`SyncWorker.doWork()` calls only `DatabaseMaintenanceManager.runDailyMaintenance()`. Provider catalog and EPG refreshes are not handled by WorkManager at all. If the user's device is out of memory and the app is killed during a background EPG download (triggered by `scheduleBackgroundEpgSync()`), data goes stale with no recovery mechanism.--**Fix**: Add a `ProviderSyncWorker` that re-syncs all active providers if their TTL has expired, scheduled via `PeriodicWorkRequest` with network and battery constraints. Wire it to the existing `sync()` entry point in `SyncManager`.-------### DB-RES-02 · FIXED (2026-04-17) · 🟡 MEDIUM · Migrations lack `PRAGMA foreign_key_check`--**File**: `StreamVaultDatabase.kt`--**Status**: Fixed in `StreamVaultDatabase`. Table-restructuring migrations now run a real FK integrity check via `PRAGMA foreign_key_check` queried through `SupportSQLiteDatabase`, and the migration throws if any violation is found instead of silently opening a broken schema.--Several major migrations (MIGRATION_8_9, MIGRATION_10_11, MIGRATION_28_29, MIGRATION_31_32) rebuild tables and add or restructure foreign keys. None execute a post-migration integrity check. A subtle bug in an ID remapping step (e.g., `channel_id_map` misses a record) leaves orphaned favorites or history rows silently — the migration succeeds, Room opens the database, and the orphan is invisible until `DatabaseMaintenanceManager` trims it.--**Fix**: Add after each migration that restructures FK relationships:-```kotlin-database.execSQL("PRAGMA foreign_key_check")-// Will throw if any FK violation is found, preventing corrupt database from opening-```-------### DB-RES-03 · FIXED (2026-04-18) · 🟢 LOW · Session IDs use wall-clock milliseconds — clock adjustment collision risk--**File**: `SyncManager.kt` / staging tables--**Status**: Fixed in `SyncCatalogStore.newSessionId()`. Session IDs no longer derive from wall-clock time; the in-process session counter is now seeded from a random positive `Long` and advances monotonically from there, which removes the clock-rollback collision path for stale staged rows after app restarts.--Staging session IDs are derived from `System.currentTimeMillis()`. If the device clock is adjusted backwards between two syncs for the same provider (NTP correction), the new session could reuse a previous session's ID. While per-`(provider_id, session_id)` scoping prevents cross-provider conflicts, for the same provider, stale rows from the aborted session could be promoted by the new session.--**Fix**: Use `UUID.randomUUID()` (or `System.nanoTime() xor Random.nextLong()`) for session IDs.-------### DB-RES-04 · FIXED (2026-04-18) · 🟢 LOW · `ChannelDao.replaceAll()` in an interface with `@Transaction`--**File**: `Daos.kt`--**Status**: Fixed by converting `ChannelDao` from an interface DAO to an abstract class DAO. `replaceAll()` now remains an `open` transactional method on an abstract Room DAO, which removes reliance on Room's interface-default-method transaction wrapper behavior for this path.--```kotlin-@Dao-interface ChannelDao {- @Transaction- suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) { ... }-}-```--Room supports `@Transaction` on Kotlin interface default methods by generating a delegation wrapper. However, the generated wrapper behavior for `suspend` default interface methods differs subtly from `abstract class` methods in edge cases across Room versions. Additionally, the body calls three separate DAO methods (`getIdMappings`, `deleteByProvider`, `insertAll`) — each individually valid, but the transaction boundary depends on Room's generated wrapper correctly entering a transaction before the first call.--**Fix**: Convert `ChannelDao` to `abstract class` (as `ProviderDao` already is) to guarantee the `@Transaction` contract:-```kotlin-@Dao-abstract class ChannelDao {- @Transaction- open suspend fun replaceAll(providerId: Long, channels: List<ChannelEntity>) { ... }-}-```-------## 7. Schema & Migrations--### DB-SCH-01 · FIXED (2026-04-18) · 🟡 MEDIUM · `is_user_protected` is not in the staging tables — orphan protection persists--**File**: `CatalogSyncDao.kt`, `Entities.kt`--**Status**: Fixed in `SyncCatalogStore.applyCategories()`. When a previously user-protected category is re-mapped in staging (detected by a changed category sync fingerprint), the category now has its user-protection bit cleared and the inherited `is_user_protected` flags on channels, movies, or series for that category are cleared in the same apply transaction. A regression test covers the remapped protected-category case.--`ChannelImportStageEntity`, `MovieImportStageEntity`, and `SeriesImportStageEntity` deliberately omit `is_user_protected` to preserve user-applied parental locks across syncs. However, if a category disappears from the provider (removed by the IPTV service), its channels are deleted from `channels` by the stale-deletion step — correct. But `categories` keep `is_user_protected = 1` for any category that still exists at the database level. If a parent category was removed while a sub-category was re-mapped, the protection state can be orphaned reference protection on a new category that has the same ID but different content.--**Recommendation**: After applying category changes from staging, run a targeted cleanup that verifies protection references still correspond to valid category+provider pairs. Consider flagging re-mapped category IDs as "protection invalidated" and prompting the user to re-apply.-------### DB-SCH-02 · FIXED (2026-04-18) · 🟢 LOW · Sync fingerprint hash collision risk on 100k+ catalogs--**File**: `Entities.kt`--**Status**: Verified not reproducible in the current implementation. `SyncCatalogStore.fingerprint()` already computes a full SHA-256 digest and stores the complete 64-hex-character value, so the review's "short hash / 64-bit fingerprint" collision scenario no longer matches the codebase.--The `sync_fingerprint` determines whether a catalog item needs an update (`current.sync_fingerprint != stage.sync_fingerprint`). If the fingerprint is a short hash (MD5/SHA-1 truncated to a string), a collision causes a changed item to appear unchanged — suppressing a metadata update silently.--For a provider with 100,000 channels, with a 64-bit fingerprint space, the collision probability per sync cycle is ~0.5% (birthday paradox). Over months of daily syncs, silent missed updates accumulate.--**Fix**: Use a content digest with at least 128 bits (SHA-256 first 16 bytes, hex-encoded), or a `hashCode()` of all mutable fields concatenated deterministically.-------### DB-SCH-03 · FIXED (2026-04-17) · 🟢 LOW · No index on `programs.end_time` for lookback queries--**File**: Schema v32--**Status**: Fixed in schema v34 and migration 33→34 by adding `index_programs_provider_id_end_time_channel_id` on `(provider_id, end_time, channel_id)`.--EPG queries for currently-airing programs use time windows like `start_time < :now AND end_time > :now`. The existing index `(provider_id, channel_id, start_time, end_time)` efficiently bounds the `start_time <` predicate but requires SQLite to scan all rows within the start-time range and filter on `end_time >` separately. For channels with dense EPG data (30-minute slots, 24h × 10 days = 480 programs/channel), the scan per channel is acceptable, but across thousands of channels it compounds.--**Fix**: Add a complementary index:-```sql-CREATE INDEX idx_programs_provider_end_time_channel- ON programs(provider_id, end_time, channel_id)-```--Room migration:-```kotlin-database.execSQL("CREATE INDEX IF NOT EXISTS idx_programs_provider_end_time_channel ON programs(provider_id, end_time, channel_id)")-```-------### DB-SCH-04 · FIXED (verified 2026-04-18) · 🟢 LOW · VirtualGroup migration (MIGRATION_31_32) risks zero-active-provider default--**File**: `StreamVaultDatabase.kt`--**Status**: Verified not reproducible in the current migration. `MIGRATION_31_32` already falls back from the active provider to the first provider by ID when no provider is active, and an instrumentation regression test now covers the zero-active-provider case to ensure migrated `virtual_groups.provider_id` is never left as `0` or `NULL`.--Migration 31→32 adds `provider_id` to `virtual_groups` and scopes it to a provider. The migration likely populates existing rows by selecting the currently-active provider via `SELECT id FROM providers WHERE is_active = 1 LIMIT 1`. If the app was force-closed mid-sync — leaving `is_active = 0` for all providers — this subquery returns NULL. Existing virtual groups default to `provider_id = 0` (or NULL), orphaning them from all real providers.--**Recommendation**: After the migration, verify that `SELECT COUNT(*) FROM virtual_groups WHERE provider_id = 0 OR provider_id IS NULL` is 0. If not, attempt to recover by associating orphan groups to the most recently created provider.-------## 8. Threading / Async--### DB-ASYNC-01 · FIXED (2026-04-18) · 🟡 MEDIUM · VACUUM/sync active check is not atomic--**File**: `DatabaseMaintenanceManager.kt`--**Status**: Fixed by coordinating maintenance with `SyncManager` through a shared admission gate. New syncs now acquire their provider mutex while holding `syncAdmissionMutex`, and `DatabaseMaintenanceManager` uses `SyncManager.runWhenNoSyncActive { ... }` to atomically block new sync starts, detect already-active syncs, and run `VACUUM` only when the database is truly idle. A concurrency regression test covers the in-flight sync case.--```kotlin-val vacuumRan = if (shouldVacuum(statsBeforeVacuum) && !isSyncActive()) {- runVacuum()-} else { false }-```--Between the `!isSyncActive()` check and the `VACUUM` call, a new sync can start in another coroutine. The sync then holds a provider mutex and begins writing to the database, while VACUUM attempts to acquire an exclusive lock. SQLite will handle the lock contention, but the sync may receive `SQLITE_BUSY` errors that surface to the user as spurious sync failures.--**Fix**: Consult the same lock inside `runVacuum()` rather than before it. If a sync starts mid-VACUUM, abort VACUUM via connection timeout rather than letting SQLite retry indefinitely.-------### DB-ASYNC-02 · FIXED (verified 2026-04-17) · 🔴 HIGH · Background EPG job map registration race--**File**: `SyncManager.kt`--**Status**: Already fixed in the current `SyncManager.scheduleBackgroundEpgSync()` implementation. The launched job is stored in `backgroundEpgJobs` before `invokeOnCompletion` registration is relied on for cleanup, so the completed-before-registration leak path described below no longer exists in the checked-in code.--```kotlin-fun scheduleBackgroundEpgSync(providerId: Long) {- backgroundEpgJobs.remove(providerId)?.cancel()- val job = backgroundEpgScope.launch { ... } // ← coroutine launched- backgroundEpgJobs[providerId] = job // ← job stored AFTER launch- job.invokeOnCompletion {- backgroundEpgJobs.remove(providerId, job)- }-}-```--If the launched coroutine completes synchronously (e.g., `providerDao.getById(providerId)` returns null immediately), `invokeOnCompletion` fires before `backgroundEpgJobs[providerId] = job` executes. `remove(providerId, job)` finds no entry and does nothing. Then the store `backgroundEpgJobs[providerId] = job` inserts a reference to a completed job that is never cleaned up. Future calls to `scheduleBackgroundEpgSync()` cancel this phantom job (no-op) and store a new one, but the phantom accumulates if it races repeatedly.--The comment acknowledges the intent was to store before completion, but the ordering is inverted.--**Fix**:-```kotlin-fun scheduleBackgroundEpgSync(providerId: Long) {- backgroundEpgJobs.remove(providerId)?.cancel()- val job: Job- synchronized(backgroundEpgJobs) {- job = backgroundEpgScope.launch { ... }- backgroundEpgJobs[providerId] = job- }- job.invokeOnCompletion { backgroundEpgJobs.remove(providerId, job) }-}-```-------### DB-ASYNC-03 · FIXED (2026-04-18) · 🟢 LOW · `collectStorageStats()` touches the writable database on IO--**File**: `DatabaseMaintenanceManager.kt`--**Status**: Fixed by making the IO contract explicit. `collectStorageStats()` and its pragma helpers are now annotated `@WorkerThread`, and the method remains private to `DatabaseMaintenanceManager`, so the writable-database reads are clearly documented as worker-thread-only maintenance code.--`collectStorageStats()` calls `database.openHelper.writableDatabase` and executes three `PRAGMA` queries. This is within `withContext(Dispatchers.IO)` in `runDailyMaintenance()`, which is correct. However, the method is not annotated or documented as requiring `Dispatchers.IO`. A future refactor that calls it outside the IO context would cause a `StrictMode` violation or silent deadlock.--**Fix**: Add `@WorkerThread` annotation and a `check(isOnIoDispatcher)` guard, or make the method private and always-inlined within the `withContext(Dispatchers.IO)` body.-------## 9. Observability--### DB-OBS-01 � FIXED (2026-04-18) � MEDIUM � No slow-query instrumentation--**Files**: All DAO files and repositories--**Status**: Fixed in `DatabaseModule` with a debug-only `SlowQueryLoggingOpenHelperFactory`. Room now uses a wrapped `SupportSQLiteOpenHelper` in debug builds that times actual `query`, `execSQL`, and compiled-statement execution paths and logs only statements taking 100ms or longer.--No query timing was captured anywhere in the data layer. Slow queries (correlated-subquery sorts, large FTS results, 50k-row migrations, VACUUM) were invisible without external APM tooling. In production, users experiencing slow UI could not self-diagnose, and developers could not identify which query was responsible.-**Fix**: Add a Room `QueryCallback` in debug builds to log queries exceeding 100ms:-**Fix**: Install a debug-only open-helper wrapper that times SQL execution and logs slow statements:-```kotlin-Room.databaseBuilder(context, StreamVaultDatabase::class.java, "streamvault.db")- .openHelperFactory(- SlowQueryLoggingOpenHelperFactory(- delegate = FrameworkSQLiteOpenHelperFactory(),- slowQueryThresholdMs = 100L- )- )-```--For production, integrate a lightweight `SQLiteQueryStats` observer that records P95/P99 latency per query pattern and logs a warning on any single query taking > 500ms.-------### DB-OBS-02 · FIXED (2026-04-18) · 🟡 MEDIUM · Maintenance report not persisted or surfaced--**File**: `SyncWorker.kt`--```kotlin-Log.d("SyncWorker", "Maintenance complete: oldPrograms=${report.deletedPrograms}, ...")-```--The maintenance report is logged at `DEBUG` level only — invisible in production logcat filters. The database size, freelist percentage, whether VACUUM was deferred repeatedly, and the count of orphaned records cleaned up are all genuine health signals that should be accessible outside a debug build.--**Fix**: Persist the last `MaintenanceReport` summary (timestamp, DB size, vacuum ran, rows cleaned) to `PreferencesRepository` via DataStore after each run. Expose a "Database Health" card in the Settings diagnostics screen that shows this data and warns when:-- VACUUM has been deferred for > 30 days-- Freelist exceeds 30% of database size-- Sequential failure count for any provider exceeds 10-------### DB-OBS-03 · FIXED (2026-04-18) · 🟢 LOW · Provider health streaks not surfaced for user alerting--**File**: `SyncMetadataEntity`, `SyncManager.kt`--**Status**: Fixed by extending the Settings diagnostics model and panel to show the provider-health signals already tracked in `SyncMetadata`, including remembered live/movie/series failure states, healthy streak counters, stale movie-catalog state, and remembered movie warning counts. Those warnings now remain visible in Settings instead of disappearing with the next transient sync-state update.--`SyncMetadata` tracks provider-health signals such as remembered failure states and healthy streaks. Before this fix, they were only used internally for adaptive sync behavior and were never surfaced to the user as a persistent warning. A provider with repeated failures could therefore look "idle" in Settings once the transient sync banner disappeared.--**Fix**: Add a `SyncMetadataDao` query:-```kotlin-@Query("SELECT * FROM sync_metadata WHERE sequential_failure_count >= :threshold")-fun getUnhealthyProviders(threshold: Int = 5): Flow<List<SyncMetadataEntity>>-```--Display a persistent banner or badge in Settings when any provider exceeds the failure threshold, linking to the provider's sync history.-------## Risk Matrix Summary--| ID | Severity | Area | Issue |-|---|---|---|---|-| DB-C-01 | 🔴 HIGH | Correctness | EPG double GZIP decompression |-| DB-C-02 | 🔴 HIGH | Correctness | Watch-progress denormalization divergence |-| DB-C-03 | 🔴 HIGH | Correctness | Provider cleanup race in `onProviderDeleted` |-| DB-ASYNC-02 | 🔴 HIGH | Threading | Background EPG job map registration race |-| DB-Q-01 | 🔴 HIGH | Query | CatalogSyncDao N×columns correlated-subquery UPDATE |-| DB-Q-02 | 🔴 HIGH | Query | Correlated subquery ORDER BY for watch-count sort |-| DB-CACHE-01 | 🔴 HIGH | Cache | Thundering-herd flush in AdultContentClassifier |-| DB-PERF-01 | 🔴 HIGH | Performance | VACUUM triggered via side-effecting TRUNCATE checkpoint |-| DB-C-04 | 🟡 MEDIUM | Correctness | Clock-skew stale cache (negative elapsed) |-| DB-C-05 | 🟡 MEDIUM | Correctness | Unbounded `providerRefreshMutexes` after provider delete |-| DB-C-06 | 🟡 MEDIUM | Correctness | FTS query injection surface |-| DB-Q-03 | 🟡 MEDIUM | Query | Correlated subquery sort — category-scoped |-| DB-Q-04 | 🟡 MEDIUM | Query | `getNowPlaying` captures stale timestamp |-| DB-Q-05 | 🟡 MEDIUM | Query | Favorites `IS NULL` predicate reduces index efficiency |-| DB-CACHE-02 | FIXED (2026-04-17) | Cache | Partial sync updates TTL; stale catalog treated as fresh |-| DB-CACHE-03 | 🟡 MEDIUM | Cache | DataStore incognito read blocks per playback event |-| DB-PERF-02 | FIXED (2026-04-18) | Performance | EPG staging inserts in 100 separate implicit transactions |-| DB-PERF-03 | 🟡 MEDIUM | Performance | 24h program pruning destroys catch-up TV guide |-| DB-SCALE-01 | FIXED (2026-04-18) | Scalability | Large multi-channel EPG reads now use snapshot queries instead of chunked reactive `combine()` |-| DB-RES-01 | FIXED (2026-04-18) | Resilience | Durable periodic provider sync via WorkManager |-| DB-RES-02 | FIXED (2026-04-17) | Resilience | Migrations lack `PRAGMA foreign_key_check` |-| DB-OBS-01 | FIXED (2026-04-18) | Observability | Debug slow-query logging added via wrapped SQLite open helper |-| DB-OBS-02 | FIXED (2026-04-18) | Observability | Maintenance report persisted to DataStore and surfaced in Settings |-| DB-CACHE-04 | 🟢 LOW | Cache | EPG size cap: partial protection on chunked transfer |-| DB-PERF-04 | 🟢 LOW | Performance | `clearAllHistory` runs correlated sync over emptied history |-| DB-SCALE-02 | FIXED (2026-04-18) | Scalability | Favorites reorder now uses sparse positions and localized updates |-| DB-SCALE-03 | FIXED (2026-04-18) | Scalability | Background EPG now uses unique durable WorkManager jobs |-| DB-SCH-01 | FIXED (2026-04-18) | Schema | Orphan protection on re-mapped category IDs |-| DB-SCH-02 | FIXED (2026-04-18) | Schema | Verified current sync fingerprints already use full SHA-256 hex digests |-| DB-SCH-03 | FIXED (2026-04-17) | Schema | Missing `programs.end_time` composite index |-| DB-SCH-04 | FIXED (verified 2026-04-18) | Schema | Verified migration already falls back when no provider is active |-| DB-RES-03 | FIXED (2026-04-18) | Resilience | Session IDs use wall-clock ms — clock adjustment collision |-| DB-RES-04 | FIXED (2026-04-18) | Resilience | `ChannelDao.replaceAll` interface `@Transaction` reliability |-| DB-ASYNC-03 | FIXED (2026-04-18) | Threading | `collectStorageStats()` dispatcher dependency implicit |-| DB-OBS-03 | FIXED (2026-04-18) | Observability | Provider sync health streaks and warning signals surfaced in Settings |-------## Recommended Prioritization--**Sprint 1 — Data Safety (🔴 HIGH items)**-1. DB-C-01: Fix EPG double-decompression guard in `EpgRepositoryImpl`-2. DB-C-02: Align `getUnwatchedByProviderPage` to authoritative `playback_history`; add `resetAllWatchProgress()` for history clear-3. DB-C-03: Move `providerSyncMutexes.remove()` inside the `withProviderLock` block-4. DB-ASYNC-02: Fix background EPG job registration race with `synchronized`-5. DB-PERF-01: Replace `wal_checkpoint(TRUNCATE)` with `PASSIVE` + separate `FULL` before VACUUM-6. DB-Q-01: Replace multi-subquery catalog UPDATE with Kotlin-side diff + batch `@Update`--**Sprint 2 — Query Performance and Cache Correctness (🟡 MEDIUM)**-7. DB-Q-02/03: Denormalize `watch_count` into `MovieEntity`-8. DB-CACHE-01: Replace `AdultContentClassifier` clear-flush with LRU eviction-9. DB-CACHE-02: Fixed 2026-04-17 by separating success freshness from attempted sync timestamps-10. DB-CACHE-03: Cache incognito state in a `StateFlow` for zero-suspension access-11. DB-PERF-03: Compute program retention from `MAX(catch_up_days)` instead of fixed 24h-12. DB-RES-02: Fixed 2026-04-17 by adding FK integrity checks to table-restructuring migrations-13. DB-PERF-02: Fixed 2026-04-18 by wrapping streamed EPG staging inserts in one explicit transaction--**Sprint 3 — Resilience and Observability (🟡 MEDIUM + 🟢 LOW)**-15. DB-OBS-01: Fixed 2026-04-18 by adding debug slow-query logging through a wrapped SQLite open helper-16. DB-OBS-02: Fixed 2026-04-18 by persisting maintenance reports to DataStore and surfacing them in Settings diagnostics-17. DB-ASYNC-01: Fixed 2026-04-18 by adding an atomic sync-admission gate around VACUUM-18. DB-RES-03: Fixed 2026-04-18 by removing wall-clock-derived staging session IDs-19. DB-SCH-01: Fixed 2026-04-18 by invalidating inherited parental protection on re-mapped categories-20. DB-RES-04: Fixed 2026-04-18 by converting `ChannelDao` to an abstract Room DAO-21. DB-ASYNC-03: Fixed 2026-04-18 by making maintenance DB access explicitly worker-thread-only-22. DB-SCALE-02: Fixed 2026-04-18 by preserving sparse favorite positions through reorder save paths-23. DB-SCALE-03: Fixed 2026-04-18 by moving background EPG refresh onto durable WorkManager jobs-24. DB-SCH-02: Verified fixed 2026-04-18 because sync fingerprints already use full SHA-256 digests-25. DB-SCH-04: Verified fixed 2026-04-18 with migration fallback and regression coverage for zero active providers-26. Remaining LOW items per team velocity-------## 10. Missing Features & Enhancement Opportunities--These are capabilities that are entirely absent — not bugs in what exists, but gaps in the data/cache contract that will constrain future UI or reliability work.-------### DB-ENH-01 · FTS4 → FTS5: richer search ranking and multi-field indexing--**Current state**: All three search virtual tables (`channels_fts`, `movies_fts`, `series_fts`) use FTS4 with only `name` indexed.--**What's missing**:-- **Search relevance ranking**: FTS4 has no built-in relevance score. The layer sorts results by `name ASC` after matching, so "Matrix" ranks "The Matrix Reloaded" ahead of "The Matrix" despite the exact match. FTS5 exposes a `rank` column powered by BM25 that Room can sort by directly.-- **Multi-column search**: `plot`, `cast`, `director`, and `genre` are stored in `MovieEntity` but unindexed for FTS. Users can't search "Spielberg" to find his films or search by genre keyword.-- **Prefix optimization**: FTS4 prefix queries (`term*`) perform full-table scans on the FTS shadow tables. FTS5 uses a B-tree prefix index that scales with catalog size.--**Migration path**:-```kotlin-// Room schema: replace @Fts4 with @Fts5-@Fts5(contentEntity = MovieEntity::class)-@Entity(tableName = "movies_fts")-data class MovieFtsEntity(- val name: String,- val plot: String?,- val cast: String?,- val director: String?,- val genre: String?-)--// Query with ranking:-@Query("""- SELECT m.* FROM movies m- JOIN movies_fts ON m.id = movies_fts.rowid- WHERE m.provider_id = :providerId AND movies_fts MATCH :query- ORDER BY movies_fts.rank -- BM25 score, best match first- LIMIT :limit-""")-fun search(providerId: Long, query: String, limit: Int): Flow<List<MovieBrowseEntity>>-```--FTS4 → FTS5 content tables require a rebuild migration (`INSERT INTO movies_fts(movies_fts) VALUES('rebuild')`), which can run in the background after the migration completes.-------### DB-ENH-02 ? FIXED (2026-04-18) ? Offset pagination ? keyset/cursor pagination for large catalogs--**Current state**: Every paginated DAO query uses `LIMIT :limit OFFSET :offset`.--**What's missing**: Offset pagination is correct for static data but drifts on live datasets. During a catalog sync, new channels are inserted and stale ones deleted. A user paging through 10,000 channels while a sync runs may skip items (if deletions shift rows before the current page) or see duplicates (if insertions push rows into an already-visited page). The drift is silent — no error, just missing content.--Additionally, `OFFSET n` scans and discards the first `n` rows internally. For page 200 of a 50,000-channel catalog (`OFFSET 5000`), SQLite reads 5,000 rows before returning 25.--**Enhancement**: Migrate hot-path paginated queries to keyset pagination using the last-seen sort key:-```sql--- Instead of: ORDER BY number ASC LIMIT 25 OFFSET :offset--- Use:-WHERE provider_id = :providerId AND number > :lastSeenNumber-ORDER BY number ASC LIMIT 25-```--This is O(log n) via the index regardless of page depth and is drift-stable. Integrate with Paging 3's `PagingSource` at the repository boundary.-------### DB-ENH-03 ? FIXED (2026-04-18) ? Cross-provider content identity via shared TMDB namespace--**Current state**: `MovieEntity.tmdbId` and `SeriesEntity.tmdbId` are stored per provider but never joined across providers. Two providers carrying the same movie create two independent `MovieEntity` rows with separate favorites, separate watch progress, and separate history entries.--**What's missing**: If the user watches 40 minutes of a movie on Provider A and switches to Provider B which has better stream quality for the same title, the resume position from Provider A is invisible. Favorites don't cross-reference either.--**Enhancement**: Add a `tmdb_identity` table:-```sql-CREATE TABLE tmdb_identity (- tmdb_id INTEGER NOT NULL,- content_type TEXT NOT NULL, -- 'MOVIE' or 'SERIES'- canonical_provider_id INTEGER NOT NULL,- first_seen_at INTEGER NOT NULL,- PRIMARY KEY (tmdb_id, content_type)-)-```--A `SharedWatchProgressRepository` queries `playback_history JOIN movies ON movies.id = content_id JOIN movies ON movies.tmdb_id = :tmdbId` across providers, returning the most recent progress regardless of which provider delivered the stream. This enables:-- **Cross-provider resume** (continue watching on best-quality provider)-- **Unified favorites** (favorite "the movie" not "movie on provider X")-- **Deduplication in continue-watching** (already done per-provider, but would work globally)-------### DB-ENH-04 � FIXED (2026-04-18) � Playback progress write batching / debounce buffer--**Current state**: Resume-position updates were previously written through to Room on every player checkpoint interval.--**Status**: Fixed in PlaybackHistoryRepositoryImpl. Resume-position updates are now buffered in memory and flushed on a 30-second interval, while explicit stop paths such as recordPlayback() and markAsWatched() consume the pending buffered state and persist a single consolidated write.--**What's missing**: A write buffer for in-flight progress. For a 2-hour movie, this is 720 individual database write transactions. The denormalized sync (`movies.watch_progress`) is updated 720 times even though the UI reads it only when a new screen is displayed.--**Enhancement**: Buffer progress writes in memory and flush to the database on a 30-second interval (or on pause/stop/destruction whichever comes first):--```kotlin-// In PlaybackHistoryRepositoryImpl or a dedicated PlaybackProgressBuffer:-private val pendingUpdates = ConcurrentHashMap<Triple<Long, ContentType, Long>, PlaybackHistory>()-private val flushJob = applicationScope.launch {- while (isActive) {- delay(FLUSH_INTERVAL_MS)- flushPendingUpdates()- }-}--override suspend fun updateResumePosition(history: PlaybackHistory): Result<Unit> {- if (isIncognito.value) return Result.success(Unit)- pendingUpdates[Triple(history.contentId, history.contentType, history.providerId)] = history- return Result.success(Unit) // write to DB happens on next flush-}-```--Force-flush on `recordPlayback()` and `markAsWatched()` to guarantee persistence on explicit stop. This reduces write transactions from ~720 to ~12 for a 2-hour session.-------### DB-ENH-05 � FIXED (2026-04-18) � Provider row budget / catalog size enforcement--**Current state**: Catalog staging previously accepted every distinct live/movie/series row for a provider with no upper bound.--**Status**: Fixed in CatalogSizeLimits and SyncCatalogStore. Live, movie, and series catalog staging now enforce per-provider row budgets before commit, keeping the lowest-numbered live channels and the highest-rated VOD items when the feed exceeds configured limits.--**Enhancement**: Add to `ContentCachePolicy` or a new `CatalogSizeLimits` object:-```kotlin-object CatalogSizeLimits {- const val MAX_CHANNELS_PER_PROVIDER = 100_000- const val MAX_MOVIES_PER_PROVIDER = 200_000- const val MAX_SERIES_PER_PROVIDER = 100_000- const val MAX_PROGRAMS_PER_PROVIDER = 5_000_000 // 500 channels × 10 days × 1000 programs-}-```--In `SyncCatalogStore.applyChannelStage()`, count staged rows before the commit and emit a `SyncState.Partial` warning if the limit is exceeded, truncating to the budget sorted by `number ASC` (live) or `rating DESC` (VOD) to preserve quality.-------### DB-ENH-06 � VERIFIED (2026-04-18) � Incremental series sync using last_modified--**Current state**: The current series path no longer does per-series `series_info` hydration during catalog sync.--**Status**: Verified no longer applicable as originally written. Series catalog sync stages list data, while detailed `get_series_info` hydration happens on demand in SeriesRepositoryImpl when opening series details instead of during the sync pass.--**Enhancement**: In `SyncManagerXtreamSeriesStrategy`, before queuing an episode hydration request, compare the remote `lastModified` against the locally stored field:--```kotlin-val needsHydration = remoteSeries.lastModified > (localSeries?.lastModified ?: 0L)- || localSeries == null- || episodeDao.getCountForSeries(localSeries.id) == 0-```--For a provider with 5,000 series where 95% haven't changed since last sync, this drops from 5,000 API calls to ~250. This would also reduce the window where a partial sync leaves the series catalog in an inconsistent state.-------### DB-ENH-07 � FIXED (2026-04-18) � EPG channel match quality tracking and re-match scheduling--**Current state**: `ChannelEpgMappingEntity` now tracks `matchedAt`, `failedAttempts`, and `source`, `ChannelEpgMappingDao` exposes rematch candidate queries, and `EpgResolutionSummary` surfaces low-confidence/rematch counts.-**Status**: Fixed in `ChannelEpgMappingEntity`/`ChannelEpgMappingDao`, `EpgResolutionEngine`, the 35->36 migration, and the Settings EPG provider card. Low-confidence/provider-native mappings are now counted, unresolved channels accumulate bounded failed-attempt metadata, and the provider Settings summary now shows weak/no-EPG coverage that needs review. Existing assign/refresh flows already trigger a fresh resolution pass when sources are added or refreshed.--**What's missing**:-- A `matchAttemptedAt` timestamp to know when the match was last tried-- A `failedAttempts` counter to gradually reduce retry frequency for unresolvable channels-- A DAO query to surface channels with no mapping or confidence below a threshold--**Enhancement**:-```kotlin-// ChannelEpgMappingEntity additions:-@ColumnInfo(name = "matched_at") val matchedAt: Long = 0L,-@ColumnInfo(name = "failed_attempts") val failedAttempts: Int = 0,-@ColumnInfo(name = "source") val source: String? = null // "name_match", "tvg_id", "override"--// ChannelEpgMappingDao:-@Query("""- SELECT * FROM channel_epg_mapping- WHERE provider_id = :providerId- AND (confidence < :minConfidence OR mapping_id IS NULL)- AND failed_attempts < :maxAttempts- ORDER BY confidence ASC, channel_name ASC- LIMIT :limit-""")-suspend fun getChannelsNeedingRematch(providerId: Long, minConfidence: Float, maxAttempts: Int, limit: Int): List<ChannelEpgMappingEntity>-```--Surface a "N channels have no EPG" count in the provider settings card and trigger a background re-match pass when new EPG sources are added.-------### DB-ENH-08 � FIXED (2026-04-18) � Program reminder table (lightweight alternative to recording schedule)--**Current state**: The app now has a dedicated `program_reminders` table plus alarm-backed reminder delivery for future guide entries.-**Status**: Fixed in `ProgramReminderEntity`/`ProgramReminderDao`, `ProgramReminderManagerImpl`, the new reminder alarm/restore receivers, and the EPG program dialog. Users can now set or cancel a reminder from the guide, reminders survive reboot/app update via restore scheduling, fire a notification shortly before airtime, and are pruned during daily maintenance once they are stale.--**What's missing**: Many users want to be reminded to watch a live event without committing to a recording (e.g., no storage configured, or they prefer live viewing). The data model has no facility for this.--**Enhancement**: Add a `program_reminders` table:-```sql-CREATE TABLE program_reminders (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- provider_id INTEGER NOT NULL,- channel_id TEXT NOT NULL,- program_title TEXT NOT NULL,- program_start_time INTEGER NOT NULL,- remind_at INTEGER NOT NULL, -- start_time minus user's lead time preference- lead_time_minutes INTEGER NOT NULL DEFAULT 5,- is_dismissed INTEGER NOT NULL DEFAULT 0,- created_at INTEGER NOT NULL,- FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE-)-```--`SyncWorker` can check for due reminders on each maintenance run and enqueue a `NotificationWorker` for each undismissed reminder within the next maintenance window. When EPG refresh reloads programs, a reconciliation step can update or cancel reminders for programs whose times shifted.-------### DB-ENH-09 � FIXED (2026-04-18) � Recent search queries: per-content-type, timestamped, in Room not DataStore--**Current state**: Recent search queries previously lived in DataStore as one shared pipe-delimited string with no timestamp metadata.-**Status**: Fixed in SearchHistoryEntity/SearchHistoryDao, PreferencesRepository, SearchViewModel, and DatabaseMaintenanceManager. Recent searches now live in Room with per-tab scoping, timestamped ordering, provider-aware lookup keys, and 90-day pruning during maintenance.--**What's missing**:-- Content-type scoping (searches in the movie section shouldn't pre-fill in the live channel search)-- Timestamp for sorting suggestions "most recently used first" rather than list-insertion order-- Survivable across DataStore corruption (DataStore uses a protobuf file; a corrupt file loses all preferences including search history)-- Ability to query "top 5 searches for this provider" for recommendation seeding--**Enhancement**: Move recent searches to a Room table:-```sql-CREATE TABLE search_history (- id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- query TEXT NOT NULL,- content_type TEXT NOT NULL, -- 'LIVE', 'MOVIE', 'SERIES', 'EPG'- provider_id INTEGER, -- NULL = global- used_at INTEGER NOT NULL,- use_count INTEGER NOT NULL DEFAULT 1,- UNIQUE(query, content_type, provider_id)-)-CREATE INDEX idx_search_history_type_time ON search_history(content_type, used_at DESC)-```--`DatabaseMaintenanceManager` prunes entries older than 90 days. The top-k queries per content type become a cheap indexed lookup.-------### DB-ENH-10 · HTTP-level OkHttp disk cache for EPG and Xtream API responses--**Current state**: The OkHttp client used for EPG downloads and Xtream catalog fetches has no disk cache configured. Every sync re-downloads the full response even if the server offers `Cache-Control` or `ETag` headers.--**Status**: Fixed in `NetworkModule.provideOkHttpClient()`. The shared OkHttp client now uses a 256 MB disk cache rooted in `context.cacheDir/streamvault_http_cache`, so both Xtream API calls and EPG downloads can reuse server-provided cache headers instead of always re-downloading full payloads.--**What's missing**: Many XMLTV EPG sources serve stable files with `Cache-Control: max-age=3600` or `ETag` for conditional GET. Without an HTTP cache, the layer ignores these signals entirely and relies solely on its own TTL logic (ContentCachePolicy), which is not server-aware.--**Enhancement**: Configure an OkHttp `Cache` for EPG fetches:-```kotlin-// In DataModule / NetworkModule:-val epgCache = Cache(- directory = File(context.cacheDir, "epg_http_cache"),- maxSize = 256L * 1024 * 1024 // 256 MB-)-val epgOkHttpClient = baseClient.newBuilder()- .cache(epgCache)- .build()-```--For Xtream API calls (catalog endpoints), a separate smaller cache with a short `max-stale` directive allows serving the last category list if the provider is temporarily unavailable, preventing a sync failure from wiping displayed content.--Note: the EPG URL must not be called with `Accept-Encoding: identity` when using OkHttp's cache, as the cache layer handles transparent decompression. This also resolves DB-C-01 (double GZIP) for cache-served responses.-------### DB-ENH-11 · Table-level row count metrics in maintenance report--**Current state**: `MaintenanceReport` records deleted rows and storage stats (page size, freelist, WAL size) but not the total current row count per table. The only way to know "how many channels does provider X have" is to run a separate `SELECT COUNT(*)`.--**Status**: Fixed in `DatabaseMaintenanceManager`, `SyncWorker`, and the Settings diagnostics UI. Daily maintenance now collects per-table row counts, persists them through the existing maintenance snapshot in DataStore, and surfaces them in the "Database Health" card alongside cleanup counts and storage metrics.--**What's missing**: Row count drift tracking across maintenance cycles. If `channels` grows by 10% between syncs (a misconfigured provider keeps appending duplicates via a bug in the staging logic), there's no signal.--**Enhancement**: Add a `tableStats` field to `MaintenanceReport`:-```kotlin-data class TableRowStats(- val channels: Long,- val movies: Long,- val series: Long,- val episodes: Long,- val programs: Long,- val epgProgrammes: Long,- val playbackHistory: Long,- val favorites: Long-)-```--Collect via `SELECT COUNT(*) FROM table` inside `runDailyMaintenance()`. Persist in DataStore alongside the existing maintenance metadata. Alert (via the Settings diagnostics card from DB-OBS-02) when any single table exceeds its expected row budget (DB-ENH-05).-------### Missing Features Summary--| ID | Category | Feature |-|---|---|---|-| DB-ENH-01 | Search | FTS4 → FTS5: BM25 ranking, multi-field indexing (cast/director/genre) |-| DB-ENH-02 | FIXED (2026-04-18) | Movie/series hot-path library browse now steps through keyset pages in the repository instead of deep OFFSET scans |-| DB-ENH-03 | FIXED (2026-04-18) | Added tmdb_identity plus cross-provider movie/series resume fallback via shared TMDB matches |-| DB-ENH-04 | FIXED (2026-04-18) | Playback progress write buffer / 30-second flush debounce |-| DB-ENH-05 | FIXED (2026-04-18) | Per-provider row budget enforcement at staging layer |-| DB-ENH-06 | VERIFIED (2026-04-18) | Current series sync no longer performs per-series detail hydration during catalog sync |-| DB-ENH-07 | FIXED (2026-04-18) | Channel EPG match quality tracking, rematch metadata, and Settings coverage surface |-| DB-ENH-08 | FIXED (2026-04-18) | Program reminders with alarm-backed notifications from the guide |-| DB-ENH-09 | FIXED (2026-04-18) | Per-content-type, timestamped search history in Room (not DataStore string) |-| DB-ENH-10 | FIXED (2026-04-18) | OkHttp disk cache for EPG and Xtream API (respect server Cache-Control/ETag) |-| DB-ENH-11 | FIXED (2026-04-18) | Per-table row count tracking in maintenance report |---diff --git a/docs/epg-code-review.md b/docs/epg-code-review.mddeleted file mode 100644index 117825c0..00000000--- a/docs/epg-code-review.md+++ /dev/null@@ -1,649 +0,0 @@-# EPG System — Production Code Review--**Scope**: `XmltvParser`, `EpgRepositoryImpl`, `EpgSourceRepositoryImpl`, `EpgResolutionEngine`, `EpgNameNormalizer`, `EpgViewModel`, `EpgGridComponents`, domain models (`Program`, `EpgModels`).--**Date**: April 2026-------## Summary--The EPG system has a well-thought-out multi-source architecture and already incorporates-several good practices (streaming XmlPullParser, per-provider mutexes, staging area in-`EpgRepositoryImpl.refreshEpg`, gzip decompression with size cap). However, several-correctness bugs, a data-loss scenario, and observable performance gaps exist in production.--Issues are grouped by severity.-------## CRITICAL-------### C-2 · `refreshSourceInternal` deletes EPG data before new data is committed — data loss on failure--**File**: `EpgSourceRepositoryImpl.kt` (~line 269)--**Problem**:-```kotlin-epgChannelDao.deleteBySource(sourceId) // old data gone-epgProgrammeDao.deleteBySource(sourceId) // old data gone-// … parse from network …-// If an exception is thrown here:-} catch (e: Exception) {- epgSourceDao.updateRefreshStatus(sourceId, now, e.message)- Result.error(...) // no restore — source is now permanently empty-}-```--The two deletes are not in a transaction and no staging area is used. A parse failure,-OOM, network drop, or process kill between the delete and insert leaves the EPG source-with zero channels and zero programmes permanently. The user's guide is blank until-a successful full refresh.--`EpgRepositoryImpl.refreshEpg` already solves this with a negative-providerId staging-area. Use the same pattern here.--**Fix**: stage all inserts under a temporary source row with id `= -sourceId`, then-swap atomically:--```kotlin-val stagingId = -sourceId-epgProgrammeDao.deleteBySource(stagingId)-epgChannelDao.deleteBySource(stagingId)-// … write to stagingId …-transactionRunner.inTransaction {- epgChannelDao.deleteBySource(sourceId)- epgProgrammeDao.deleteBySource(sourceId)- epgChannelDao.moveToSource(stagingId, sourceId)- epgProgrammeDao.moveToSource(stagingId, sourceId)-}-```--Add `deleteBySource(stagingId)` to the catch block to clean up the staging rows on-failure.-------### C-4 · Local-time XMLTV timestamps without timezone offset are silently treated as UTC--**File**: `XmltvParser.kt` — `parseLocalDateTime` and the "last resort" path--**Problem**:-Many real-world XMLTV providers emit local-time timestamps without timezone offsets:-```-<programme start="20250101200000" stop="20250101210000" channel="bbc1">-```-The XMLTV spec says these are local (provider) time, not UTC. `parseLocalDateTime`-passes them through `ZoneOffset.UTC`, shifting them by the provider's timezone — up-to ±14 hours. A programme broadcast at 20:00 local (+05:00) appears in the guide at-01:00 the next day.--Worse, the "last resort" digit-strip path drops any timezone suffix before the UTC-assumption:-```kotlin-val cleaned = dateStr.replace("""[^\d]""".toRegex(), "")-// "20250101120000 +0500" → "202501011200000500" → substring(0,14) = "20250101120000"-// tz offset is silently discarded, UTC assumed-```--**Fixes**:-1. Expose a `defaultOffset: ZoneOffset` parameter on `XmltvParser` (defaulting to- `ZoneOffset.UTC` for backward compat). EPG source settings can optionally carry a- per-source timezone string that the caller converts to a `ZoneOffset` at parse time.-2. In the last-resort path, try parsing the trailing digits as an offset before- discarding them:- ```kotlin- // If length ≥ 19 and last 5 chars match [+-]\d{4}, parse as offset-aware- ```-------## HIGH-------### H-2 · SQL LIKE wildcards in program search are not escaped — logical bypass--**File**: `EpgRepositoryImpl.kt` — `searchPrograms`--**Problem**:-```kotlin-val normalizedQuery = query.trim() // NOT run through EpgNameNormalizer-return programDao.searchPrograms(- queryPattern = "%$normalizedQuery%", // user input directly interpolated into LIKE pattern- ...-)-```-Searching for `%` produces `WHERE title LIKE '%%'` which matches every title, ignoring-the 2-character minimum guard. Searching for `%a%` returns exactly the same as `a`.-SQLite wildcard `_` matches any single character.--**Fix** — escape reserved LIKE characters before building the pattern:-```kotlin-fun String.escapeSqlLike(escape: Char = '\\'): String =- this.replace("$escape", "$escape$escape")- .replace("%", "$escape%")- .replace("_", "$escape_")--val escaped = normalizedQuery.escapeSqlLike()-queryPattern = "%$escaped%",-// Also update the DAO @Query to use ESCAPE '\'-```-------### H-3 · `refreshSourceInternal` deletes before inserting — empty guide window for users--Even absent a failure (C-2), the gap between:-```kotlin-epgChannelDao.deleteBySource(sourceId)-epgProgrammeDao.deleteBySource(sourceId)-// ← any read here sees zero EPG data-// ... network download + parse (can take minutes) ...-// inserts happen-```-means that any guide read during the refresh sees an empty schedule. On large feeds-(>10 MB), the parse can take 30–120 seconds. The staging-area pattern (see C-2) also-closes this availability gap.-------### H-4 · `exactIdIndex` in `EpgResolutionEngine` maps each ID to itself — silent mismatch risk--**File**: `EpgResolutionEngine.kt`--**Problem**:-```kotlin-exactIdIndex[sourceId] = epgChannels.associate { it.xmltvChannelId to it.xmltvChannelId }-```-The map value is identical to its key. The lookup result (`channelEpgId in index`) is-only used for existence checking:-```kotlin-if (channelEpgId != null && channelEpgId in index) { ... }-```-The value side (`index[channelEpgId]`) is never used, so the map could be a `Set`.-More importantly, `channelEpgId` is compared against `xmltvChannelId` raw — no-normalization, no case-folding, no whitespace trimming. An XMLTV file that stores-`" bbc1.uk "` (with spaces) would not match a channel with `tvg-id="bbc1.uk"`. Some-XMLTV providers pad their IDs with extra spaces or use different casing.--**Fix**: normalize both sides of the exact-ID lookup (at least `trim()` on both), and-use a `Set<String>` for the existence index:-```kotlin-exactIdIndex[sourceId] = epgChannels.map { it.xmltvChannelId.trim() }.toHashSet()-// lookup:-if (channelEpgId != null && (channelEpgId.trim() in exactIdIndex[sid] ?: emptySet()))-```-------### H-5 · `getNowAndNext` "next" program selection skips over gaps incorrectly--**File**: `EpgRepositoryImpl.kt`--**Problem**:-```kotlin-val current = programs.find { it.startTime <= now && it.endTime > now }-val next = programs.find { it.startTime > now }-```-`next` is found independently: the first program whose `startTime > now`. If `current`-is null (gap in schedule) and two future programs exist, `next` picks the nearer one —-that is correct. But if `current` is non-null and there are overlapping programs (a-common provider data quality issue), `next` could return a program whose `startTime`-falls *within* the current window, making both `current` and `next` appear to run at-the same time.--**Fix**: pick `next` relative to `current`:-```kotlin-val current = programs.find { it.startTime <= now && it.endTime > now }-val nextStart = current?.endTime ?: now-val next = programs.firstOrNull { it.startTime >= nextStart && it != current }-```-------## MEDIUM-------### M-1 · `refreshSource` marks `lastRefreshAt` at start of download, not success--**File**: `EpgSourceRepositoryImpl.kt`--```kotlin-epgSourceDao.updateRefreshStatus(sourceId, now, null) // called BEFORE download-```--`lastRefreshAt` is set to the start of the attempt. If the download takes 2 minutes-and fails, the UI displays "Last refreshed: 2 minutes ago" with an error badge — which-reads as contradictory. `lastRefreshAt` should only be updated on success alongside-`lastSuccessAt`:--```kotlin-// Remove upfront call; on success:-epgSourceDao.updateRefreshSuccess(sourceId, System.currentTimeMillis())-// On failure, only update the error field:-epgSourceDao.updateRefreshError(sourceId, e.message ?: "Unknown error")-```-------### M-2 · `getOverrideCandidates` loads all EPG channels into heap memory--**File**: `EpgSourceRepositoryImpl.kt`--```kotlin-epgChannelDao.getBySource(assignment.epgSourceId) // returns List<EpgChannelEntity>- .asSequence()- .filter { ... }-```--For a source with 50 000 channels (common for large multi-country XMLTV feeds),-`getBySource` returns all rows. With 3–4 enabled sources, this can allocate 10–20 MB-of object heap per override search.--**Fix**: move the filter to the DAO with a Room `@Query` using `LIKE` on both-`xmltvChannelId` and `displayName`, and use a `LIMIT` clause:-```kotlin-@Query("""SELECT * FROM epg_channels- WHERE epg_source_id = :sourceId- AND (xmltv_channel_id LIKE :pattern OR display_name LIKE :pattern)- LIMIT :limit""")-suspend fun searchBySource(sourceId: Long, pattern: String, limit: Int): List<EpgChannelEntity>-```-------### M-3 · Program search has no debounce — expensive recomposition per keystroke--**File**: `EpgViewModel.kt` — `observeGuidePresentation`--Every character typed in the guide search bar triggers `buildGuideDisplaySnapshot` on-`Dispatchers.Default`. With 5 000+ programs in memory, this is a CPU-heavy map/filter-over the full dataset with no delay:--```kotlin-} .collectLatest { presentation ->- // called on every keystroke- val displaySnapshot = withContext(Dispatchers.Default) {- buildGuideDisplaySnapshot(...) // expensive- }-```--**Fix**: add a flow debounce of 150–200 ms on `programSearchQuery` before it reaches-the combine:-```kotlin-programSearchQuery.debounce(150L)-```-------### M-4 · EpgResolutionEngine — name match confidence 0.7 is too aggressive for partial matches--**File**: `EpgResolutionEngine.kt`--`EpgNameNormalizer.normalize` removes *all* non-alphanumeric characters:-- `"BBC ONE"` → `"bbcone"`-- `"BBC ONE HD"` → `"bbconehd"`-- `"BBC ONE+1"` → `"bbcone1"`--Only `"BBC ONE"` (normalized: `"bbcone"`) would match `"bbcone"` exactly, while the-HD/+1 variants won't. That is actually reasonable. The risk is that two *different*-channels collide after normalization (e.g., `"TV5"` and `"TV 5"`). Confidence of 0.7-should be acceptable but the resolution engine should log per-channel collisions for-debugging (see M-6).-------### M-5 · `assignSourceToProvider` / `resolveAffectedProviders` always pass empty `hiddenLiveCategoryIds`--**File**: `EpgSourceRepositoryImpl.kt`--All internal resolution calls use `resolveForProvider(providerId, emptySet())`. The-hidden-category set comes from user preferences and is only available at the ViewModel-layer. Resolution runs without it, so channels in hidden categories get EPG mappings-that will never be used — wasted work, and the mapping table grows with stale noise.-In practice this is harmless but contributes to resolution summary counts that-misrepresent match quality.--No fix required for correctness, but consider making the ViewModel trigger resolution-through a use case that injects the hidden-category set from preferences.-------### M-6 · No per-channel EPG resolution failure logging--**File**: `EpgResolutionEngine.kt`--The only observability into mapping quality is a single summary line:-```kotlin-Log.d(TAG, "Resolution for provider $providerId: $summary")-```--When a user reports "Channel X has no guide data", there is no log to distinguish:-- Channel has `epgChannelId = null`-- Channel has an ID but no EPG source is assigned-- Channel ID exists in source but has zero programmes for today-- Name normalization matched the wrong channel--**Fix**: log (at `VERBOSE` level) every unresolved channel along with the attempted-normalize key and whether any candidates existed in the name index.-------### M-7 · `EpgSourceRepositoryImpl` and `EpgRepositoryImpl` both define separate `MAX_EPG_SIZE_BYTES` and `epgHttpClient` — divergence risk--Both files duplicate:-```kotlin-private const val MAX_EPG_SIZE_BYTES = 200L * 1_048_576-private val epgHttpClient: OkHttpClient by lazy { ... }-```--If one is updated (e.g., size cap raised to 500 MB), the other is silently left at-the old value. Extract these into a shared `EpgDownloadConfig` object injected by Hilt.-------## LOW-------### L-1 · `nowTicker` creates a fresh coroutine loop per subscriber--**File**: `EpgRepositoryImpl.kt`--Each call to `getNowAndNext` starts a new `while(true) { emit(); delay(60s) }` loop.-With 60 channels on screen, 60 timers fire independently, each potentially issuing a-DB query. Using a `SharedFlow` ticker would reduce this to one timer feeding all-subscribers:--```kotlin-private val nowTicker: Flow<Long> = flow {- while (true) { emit(System.currentTimeMillis()); delay(NOW_AND_NEXT_REFRESH_INTERVAL_MS) }-}.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 1)-```-------### L-2 · `jumpToDay` uses UTC epoch modulo for "time of day" — off by timezone for non-UTC users--**File**: `EpgViewModel.kt`--```kotlin-fun jumpToDay(dayStartMillis: Long) {- val currentTimeOfDay = guideAnchorTime.value.mod(DAY_SHIFT_MS)- .let { if (it < 0L) it + DAY_SHIFT_MS else it }- updateGuideAnchorTime(dayStartMillis + currentTimeOfDay)-}-```--`mod(DAY_SHIFT_MS)` gives the UTC time-within-day. If `dayStartMillis` is the UTC-midnight of the selected date but the user is in UTC+8, "current time of day" is-8 hours behind local reality. The compound anchor can land on a time a full `tz-offset`-away from what the user expects. Use `ZonedDateTime` arithmetic (same local-time fix as-`G-06` in `EPG_GRID_CODE_REVIEW.md`).-------### L-3 · `GuideTimelineHeader` uses `SimpleDateFormat` — not `java.time`--**File**: `EpgGridComponents.kt`--```kotlin-val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }-```--`SimpleDateFormat` is mutable and not thread-safe. Inside `remember {}` per composition-site it is used from only one thread (composition), so there is no data race, but-`HH:mm` is hardcoded 24-hour which ignores the device's 12/24-hour system setting-(available via `DateFormat.getTimeFormat(context)`). This also applies to `ProgramItem`.--**Fix**: replace with `DateTimeFormatter` or pull the format from the system-`DateFormat.getTimeFormat(context)` so it respects the user's locale setting.-------### L-4 · `Program.progressPercent` depends on the caller-set `isNowPlaying` flag--**File**: `domain/model/Program.kt`--```kotlin-fun progressPercent(currentTimeMillis: Long = System.currentTimeMillis()): Float {- if (!isNowPlaying) return 0f- ...-}-```--`isNowPlaying` is only set by certain code paths (e.g., the streaming path in-`parseStreaming`). Programs produced by the legacy `parse()` method never have it set.-Any UI component that calls `progressPercent()` on a program fetched outside the-now-playing path always gets `0f`, producing a stuck progress bar. The flag is-superfluous — just compute from the timestamps:--```kotlin-fun progressPercent(currentTimeMillis: Long = System.currentTimeMillis()): Float {- if (endTime <= startTime || currentTimeMillis < startTime || currentTimeMillis >= endTime) return 0f- return ((currentTimeMillis - startTime).toFloat() / (endTime - startTime)).coerceIn(0f, 1f)-}-```-------### L-5 · No EPG refresh rate-limiting or back-off--Manual and automatic EPG refresh can be triggered repeatedly via `refresh()` in-`EpgViewModel`. The per-source `Mutex` serializes concurrent calls but does not-prevent rapid sequential calls. An unhappy user rage-clicking "Refresh EPG" can saturate-the CDN endpoint or the device's network. Add a minimum re-refresh interval check-against `EpgSource.lastRefreshAt` (e.g., 5 minutes) before issuing the download.-------### L-6 · `EpgUiState` initializes anchor times via `System.currentTimeMillis()` at data-class construction--**File**: `EpgViewModel.kt`--```kotlin-data class EpgUiState(- val guideAnchorTime: Long = System.currentTimeMillis(),- val guideWindowStart: Long = System.currentTimeMillis() - EpgViewModel.LOOKBACK_MS,- val guideWindowEnd: Long = System.currentTimeMillis() + EpgViewModel.LOOKAHEAD_MS-)-```--These three `currentTimeMillis()` calls are evaluated at (potentially) different-instants, so `guideWindowStart` and `guideWindowEnd` can disagree with-`guideAnchorTime`. In practice the difference is sub-millisecond, but unit tests may-observe skew. Initialise all three from a single captured `now` constant.-------## Test Coverage Gaps--| Area | Status | Gap |-|---|---|---|-| `XmltvParser` — timezone handling | Tested (offset + +0300) | No test for no-offset local-time, or the digit-strip last-resort |-| `XmltvParser` — BOM / encoding | Not tested | UTF-16 BOM, ISO-8859-1 encoded real feeds |-| `EpgResolutionEngine` — ID trimming | Not tested | Leading/trailing spaces in `xmltvChannelId` |-| `searchPrograms` LIKE wildcards | Not tested | `%` and `_` in query string |-| `refreshSourceInternal` failure recovery | Not tested | Parse crash after delete — empty state |-------## Prioritized Fix Plan--| Priority | Issue | Effort |-|---|---|---|-| 🔴 Critical | C-2 — Stage-then-swap for source refresh | M |-| 🔴 Critical | C-4 — Local-time UTC assumption + digit-strip drops tz | M |-| 🟠 High | H-2 — LIKE wildcard escape in search | S |-| 🟠 High | H-3 — Empty guide window during refresh | M (see C-2) |-| 🟠 High | H-4 — ID-index exact match no normalization | S |-| 🟠 High | H-5 — `getNowAndNext` next-program selection | S |-| 🟡 Medium | M-1 — `lastRefreshAt` at start not success | S |-| 🟡 Medium | M-2 — `getOverrideCandidates` in-memory load | M |-| 🟡 Medium | M-3 — No debounce on guide search | S |-| 🟡 Medium | M-6 — Per-channel resolution failure logging | S |-| 🟡 Medium | M-7 — Deduplicate EPG config constants | S |-| 🟢 Low | L-1 through L-6 | S each |--**Effort key**: S = small (< 2 h), M = medium (2–8 h), L = large (> 8 h)-------## Improvement Opportunities & Missing Features--The items below are not bugs — they are genuine gaps in functionality or architecture-that would materially improve the user experience or system reliability in production.-------### Technical Capabilities--#### TC-1 · No HTTP conditional requests — full file re-download on every refresh---Every EPG refresh downloads the full XMLTV file regardless of whether the server's-content has changed. Many CDNs serving EPG files expose `ETag` and `Last-Modified`-headers, making `If-None-Match` / `If-Modified-Since` `304 Not Modified` fast-paths-trivially achievable.--**Suggested approach**: persist the last `ETag` and `Last-Modified` response header-values per `EpgSource` (two nullable `String` columns in `EpgSourceEntity`). On the-next refresh send conditional headers:--```kotlin-val request = Request.Builder()- .url(source.url)- .apply { source.etag?.let { header("If-None-Match", it) } }- .apply { source.lastModified?.let { header("If-Modified-Since", it) } }- .build()-// HTTP 304 → skip parse, just call epgSourceDao.updateRefreshSuccess(sourceId, now)-```--For large feeds (100+ MB) this is the highest-value performance improvement available-with no architecture changes.-------#### TC-2 · No per-source configurable refresh interval--All EPG sources share a single app-wide refresh cadence. Some XMLTV providers update-hourly; others update weekly. There is no `refreshIntervalHours` field on `EpgSource`-and no per-source job scheduler — a single global `SyncWorker` handles everything.--**Suggested approach**: add `refreshIntervalHours: Int` to `EpgSource` (default 24).-`SyncWorker` or a dedicated `EpgRefreshWorker` should schedule per-source-`PeriodicWorkRequest` instances keyed by source ID and updated whenever the interval-setting changes.-------#### TC-3 · EPG `<channel>` icon URL never used as provider channel logo fallback--`EpgChannelEntity.iconUrl` is parsed from XMLTV `<channel><icon src="…"/>` elements-and stored in the database, but it is never consulted when a provider channel has no-logo. For M3U providers that don't include `tvg-logo`, this data is a direct substitute.--**Suggested approach**: in `ChannelRepositoryImpl` (or a new `ChannelIconResolver`),-after resolving the channel's own `logoUrl`, fall back to the mapped-`EpgChannelEntity.iconUrl` when the primary logo is null or empty. No network-round-trips required — the data is already local.-------#### TC-4 · No horizontal virtualization in the program timeline--The program strip for each row renders *all* `ProgramItem` composables for the full-loaded time window as children of a `Box`, even when only 6–8 are visible. With a-7-day window (336 half-hour slots) and 60 channels, the first render allocates up to-20 160 composable slots.--**Suggested approach**: convert the row's inner `Box` to a `LazyRow`, or use a-single-pass `Canvas` draw approach, so only the programs visible in the horizontal-viewport are composed at any given time.--> Also noted in `EPG_GRID_CODE_REVIEW.md` section 2.1.-------### Data & Integration Gaps--#### DI-1 · EPG-to-catch-up alignment is not validated--The guide marks programs with `hasArchive = true` based on EPG metadata, but there is-no check that the program's `startTime` falls within the channel's actual rewind window-(typically 7 days from the provider). A program aired 10 days ago with `hasArchive =-true` will silently fail when the user attempts to watch it, producing a generic player-error rather than a predictive guide-level "Replay unavailable" message.--**Suggested approach**: add a `catchUpWindowDays: Int` field to `Channel` (populated-from Xtream `tv_archive_duration` or M3U `catchup-days`). Compute archive eligibility-at display time:-```kotlin-val replayAvailable = program.hasArchive &&- program.startTime >= now - channel.catchUpWindowDays * 86_400_000L-```-------#### DI-2 · Combined guide ignores hidden categories--In `observeCombinedGuide`, `hiddenCategoryIds = emptySet()` is hardcoded:--```kotlin-hiddenCategoryIds = emptySet(), // user hidden-category preferences are ignored-```--A user who has hidden adult or regional categories from provider A still sees all their-channels in the combined guide. The fix is to read `PreferencesRepository`-`getHiddenCategoryIds(providerId, ContentType.LIVE)` per-member inside-`observeCombinedGuide` and pass the correct set per provider into the channel filter.-------#### DI-3 · `providerHasEpg` check is too coarse — generates phantom PROVIDER_NATIVE mappings--In `EpgResolutionEngine`:-```kotlin-val providerHasEpg = programDao.countByProvider(providerId) > 0-```--This returns `true` if *any* programs exist for the provider. Every channel therefore-receives a `PROVIDER_NATIVE` mapping (confidence 0.5) — including channels that have-zero associated programs. These phantom mappings cause the resolution summary to-overcount `providerNativeMatches` and make guide rows show "No schedule" where the-mapping falsely implies EPG coverage exists.--**Fix**: replace the global count with a per-channel check inside the resolution map loop:-```kotlin-// in the channel mapping step, replace step 4 with:-val hasNativeEpg = channelEpgId != null &&- programDao.countByChannel(providerId, channelEpgId) > 0-if (hasNativeEpg) {- providerNativeMatches++- return@map ChannelEpgMappingEntity( ... EpgSourceType.PROVIDER ... )-}-```-------#### DI-4 · No automatic EPG stale detection at the source level--`isGuideStale` is a ViewModel-level signal computed from whether the current time window-has any usable programs. But an `EpgSource` last refreshed 3 weeks ago shows-`lastError = null` with a 3-week-old `lastSuccessAt` — no TTL or staleness flag warns-the user or the resolution engine before guide reads fail.--**Suggested approach**: add a computed `isStale` check (or a DAO query):-```kotlin-val EpgSource.isStale: Boolean- get() = System.currentTimeMillis() - lastSuccessAt > refreshIntervalHours * 3_600_000L * 2-```--Surface stale sources with a warning badge in `SettingsEpgSection`. Optionally, the-resolution engine could prefer non-stale sources when multiple candidates match, and-`EpgResolutionSummary` could include a `staleSourceCount` field.-diff --git a/docs/recording-review.md b/docs/recording-review.mddeleted file mode 100644index f508f317..00000000--- a/docs/recording-review.md+++ /dev/null@@ -1,682 +0,0 @@-# Recording System — Comprehensive Review--**Date:** 2026-04-16-**Scope:** All recording-related code across `domain/`, `data/`, `app/` modules-------## 1. Architecture Overview--The recording stack consists of:--| Layer | Files |-|---|---|-| Domain model | `RecordingModels.kt` (enums, request/item/storage DTOs) |-| Domain interface | `RecordingManager.kt` |-| Domain use case | `ScheduleRecording.kt` |-| Data implementation | `RecordingManagerImpl.kt` |-| Data support | `RecordingSupport.kt`, `RecordingConflictDetector.kt` |-| Capture engines | `RecordingCaptureEngine.kt` (TS + HLS) |-| Scheduling | `RecordingAlarmScheduler.kt`, `RecordingAlarmReceiver.kt` |-| Foreground service | `RecordingForegroundService.kt` |-| Background worker | `RecordingReconcileWorker.kt` |-| Boot restore | `RecordingRestoreReceiver.kt` |-| Source resolver | `RecordingSourceResolver.kt` |-| Persistence | `RecordingEntities.kt`, `RecordingDaos.kt` |-| UI | `SettingsRecordingComponents.kt`, `SettingsRecordingActions.kt` |-| Player wiring | `PlayerViewModelActions.kt`, `ScheduleRecording.kt` use-case |-------## 2. Critical Bugs--### 2.1 TOCTOU Race on Simultaneous Recording Start--**Files:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`, `startManualRecording()`, `scheduleRecording()`-**Severity:** HIGH--`validateRecordingWindow()` reads overlapping DB rows, checks the count, and returns. The actual `recordingRunDao.insert()` happens afterwards with no mutex or transaction. Two concurrent `startManualRecording` / `scheduleRecording` calls can both pass the window check and both be inserted, potentially exceeding `maxSimultaneousRecordings`.--```kotlin-// validateRecordingWindow() — read-only check-val overlapping = recordingRunDao.getOverlapping(startMs, endMs) ...-if (overlapping.size >= storage.maxSimultaneousRecordings) return "conflict"--// — gap here — no mutex, another call can pass the check simultaneously--recordingRunDao.insert(run) // inserted by two concurrent callers-```--**Fix:** Wrap the validate → insert → schedule-alarm sequence inside a `Mutex` (or a Room `withTransaction` that includes the overlap query).-------### 2.2 `retryRecording()` Crashes if Schedule Window Has Expired--**File:** `RecordingManagerImpl.kt` — `retryRecording()`-**Severity:** HIGH--`retryRecording` builds a `RecordingRequest` with:--```kotlin-scheduledStartMs = maxOf(System.currentTimeMillis() + 2_000L, schedule.requestedStartMs),-scheduledEndMs = schedule.requestedEndMs // unchanged from original-```--If the original schedule has already passed its end time, `scheduledStartMs > scheduledEndMs` and `RecordingRequest.init` throws `IllegalArgumentException`. The enclosing `withContext` does not use `runCatching`, so the exception propagates uncaught into the caller's coroutine scope (seen in `SettingsRecordingActions.retryRecording`) and crashes the coroutine silently; the UI receives no actionable error message.--**Fix:** Wrap the body of `retryRecording` in `runCatching { ... }.fold(...)` (matching `startManualRecording` / `scheduleRecording`), and add an explicit guard returning an error when `requestedEndMs <= now`.-------### 2.3 Orphan DB Row Left on `startManualRecording` Capture Failure--**File:** `RecordingManagerImpl.kt` — `startManualRecording()`-**Severity:** MEDIUM--After `recordingRunDao.insert(run)` and `alarmScheduler.scheduleStop(...)` succeed, if `startCapture()` returns `Result.Error`, an `IllegalStateException` is thrown, caught by `runCatching`, and returned as `Result.error`. The row is left in the DB with `status = RECORDING` and no active coroutine job. `reconcileRecordingState()` will attempt to restart it via `RecordingForegroundService.startCapture()` indefinitely, potentially causing repeated useless foreground-service churn until the end alarm fires.--**Fix:** On `startCapture` failure inside `startManualRecording`, immediately mark the run as `FAILED` via `markRunFailed()` before propagating the error.-------### 2.4 `stopRecording` Marks Partial Writes as COMPLETED--**File:** `RecordingManagerImpl.kt` — `stopRecording()`-**Severity:** MEDIUM--```kotlin-status = if (run.bytesWritten > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,-```--`bytesWritten` is written by `updateRunProgress()`, which is called asynchronously during capture. Between the first bytes flowing from the network and the first DB progress update, the field reads `0`. A user who immediately stops a just-started recording gets `CANCELLED`. Conversely, the inverse corner case is meaningful: a recording where bytes were written but the stream was cut (network drop) and then the user presses stop would be marked `COMPLETED`, even though the file is truncated. The distinction silently misrepresents the recording quality to the user.-------## 3. Race Conditions--### 3.1 `promoteScheduledRecording` Is Not Serialized--**File:** `RecordingManagerImpl.kt` — `promoteScheduledRecording()`-**Severity:** MEDIUM--`promoteScheduledRecording` is called from two independent paths for the same `recordingId`:-- The alarm fires → `RecordingAlarmReceiver` → `RecordingForegroundService.onStartCommand` → `manager.promoteScheduledRecording(recordingId)`-- `reconcileRecordingState()` → `RecordingForegroundService.startCapture(context, run.id)` → same service path--The `startCapture()` function has an `isActiveJob` guard, but the promote flow between `resolveRecordableSource()`, `recordingRunDao.update(updatedRun)`, and `startCapture()` is not atomically serialized. Two concurrent promote calls for the same run can both call `resolveRecordableSource()` (making duplicate network requests), both call `recordingRunDao.update()` (last writer wins), and both attempt `startCapture()`. The second call hits `isActiveJob → true` and returns `Result.success(Unit)`, but the state may have been partially mutated by both calls.--**Fix:** Add a per-recording mutex keyed by `recordingId`, or serialize promotion through the existing `activeJobsMutex` with a broader lock scope.-------### 3.2 `spawnNextRecurringRunIfNeeded` Is Not Transactional--**File:** `RecordingManagerImpl.kt` — `spawnNextRecurringRunIfNeeded()`-**Severity:** MEDIUM--This function reads `scheduledRuns` from the DB, checks for an existing next-occurrence run, and then inserts a new one — all without a transaction or mutex. If a concurrent alarm triggers `promoteScheduledRecording` for another occurrence of the same recurring rule simultaneously, both calls could fail to see the pending insertion by the other and insert duplicate next-occurrence runs.-------### 3.3 `updateRunProgress` Has a Read-Modify-Write Race--**File:** `RecordingManagerImpl.kt` — `updateRunProgress()`-**Severity:** LOW--```kotlin-val run = recordingRunDao.getById(recordingId) ?: return-recordingRunDao.update(run.copy(...))-```--Progress is reported via a flow of callbacks. If two `onProgress` calls arrive with small delay (possible if the coroutine resumes twice before the DB write completes), the second call reads the un-updated row and writes a stale `retryCount`. Room does not serialize these reads/writes. In practice this is low frequency, but `retryCount = maxOf(run.retryCount, progress.retryCount)` could revert a fresh retry count to a stale cached value.-------## 4. Storage Issues--### 4.1 `retentionDays` Is Never Enforced--**Files:** `RecordingStorageConfig`, `RecordingStorageEntity`, `RecordingStorageState`-**Severity:** HIGH — Feature gap masquerading as working functionality--`retentionDays` is stored in the DB, exposed in the UI, included in backup/restore — but **no code anywhere deletes recordings older than this threshold**. `DatabaseMaintenanceManager` purges EPG programs, not recording files or recording run rows. The periodic `RecordingReconcileWorker` calls only `reconcileRecordingState()`, which handles status checks and alarm rescheduling, not file retention.--Users who configure a 30-day retention policy will accumulate recordings indefinitely.--**Fix:** Add a `pruneExpiredRecordings()` step inside `reconcileRecordingState()` (or as a dedicated `DatabaseMaintenanceManager` step) that:-1. Queries all COMPLETED/FAILED/CANCELLED runs where `terminalAtMs < (now - retentionDays * 86_400_000)`.-2. Calls `deleteOutputTarget()` for each.-3. Deletes the `recording_runs` row.-------### 4.2 SAF (DocumentFile) Storage Doesn't Report Available Bytes--**File:** `RecordingSupport.kt` — `resolveStorageDetails()`-**Severity:** MEDIUM--When a SAF tree URI is configured, `availableBytes` is always `null`:--```kotlin-return Triple(documentTree?.name ?: treeUriString, null, isWritable)-```--The UI shows "available bytes" and the storage card displays the value — but it will always be empty for SAF paths. There is also no pre-flight disk-space check before starting any recording (SAF or plain file), meaning a recording can start even if only 10 MB remain.--**Fix:** Use `DocumentsContract.getDocumentUri()` + `ContentResolver.query(COLUMN_SIZE)` to get available space for a SAF tree, and add a minimum-space guard in `startManualRecording` / `promoteScheduledRecording`.-------### 4.3 SAF File Collision Silently Overwrites Existing Recording--**File:** `RecordingSupport.kt` — `createOutputTarget()`-**Severity:** MEDIUM--```kotlin-val existing = documentTree.findFile(fileName)-val document = existing ?: documentTree.createFile("video/mp2t", fileName.removeSuffix(".ts"))-```--If a file with the computed name already exists, it is silently reused as the output target. A SAF `OutputStream` opened in `"w"` mode truncates the file. This means re-recording the same channel in the same minute (exact minute matches pattern `yyyy-MM-dd_HH-mm`) overwrites the previous recording without warning.--**Fix:** Append a counter suffix when a filename collision is detected (`_1`, `_2`, etc.), or generate a UUID suffix for SAF paths.-------### 4.4 Partial Files Not Cleaned Up on Capture Failure--**Severity:** LOW--When `TsPassThroughCaptureEngine` or `HlsLiveCaptureEngine` throws during capture (network error, storage full, etc.), `markRunFailed()` updates the DB status but does not delete the partially written file. Subsequent retries create a new output file anyway (from the retry's `createPendingRun` → eventual promote). The partial file is left orphaned on storage with no DB reference.-------## 5. Logic Issues--### 5.1 Retry Against Expired Schedule--**File:** `RecordingManagerImpl.kt` — `retryRecording()`--As noted in §2.2, there is no guard preventing retry when `schedule.requestedEndMs < now`. Beyond the crash risk, even if defensive code were added and an end-time extension were applied, the alarm for the new `scheduledEndMs` would fire at whatever extension time is used — creating ambiguity about what "retry" means for finished programs.-------### 5.2 Manual Recording End Time Falls Back to 30 Minutes Without UI Notice--**File:** `PlayerViewModelActions.kt` — `startManualRecording()`--```kotlin-scheduledEndMs = currentProgram.value?.endTime ?: (now + 30 * 60_000L),-```--If there is no EPG data (common for M3U providers), the recording silently ends at exactly 30 minutes. The user gets a brief toast but no mention of the 30-minute cap. Channels with live events (sports, concerts) would be cut arbitrarily.-------### 5.3 `seenSegments` Set Grows Unboundedly in HLS Engine--**File:** `RecordingCaptureEngine.kt` — `HlsLiveCaptureEngine`--```kotlin-val seenSegments = linkedSetOf<String>()-```--For a 4-hour HLS recording at 10-second segment intervals, `seenSegments` accumulates ~1,440 segment URI strings. Each URI can be 200–300 bytes. This is manageable, but for very long recordings (overnight, 8+ hours) on devices with limited memory, this set should be bounded. A sliding window or a bloom filter would cap memory at a fixed size.-------### 5.4 `cancelRecording` Disables the Schedule but `retryRecording` Ignores That--**File:** `RecordingManagerImpl.kt`--`cancelRecording` sets `schedule.enabled = false`. `retryRecording` reads the schedule entity but creates a new run with `scheduleEnabled = true` regardless. A user who cancels a recurring recording (intending to stop the series) and then retries it will inadvertently re-enable the schedule. There is no guard in `retryRecording` checking whether the parent schedule has been disabled by an explicit cancel.-------### 5.5 `cancelRecording` Does Not Cascade to Future Pending Occurrences--**Severity:** MEDIUM--For a recurring recording (`DAILY` / `WEEKLY`), `spawnNextRecurringRunIfNeeded` inserts future occurrences into `recording_runs` as they are promoted. `cancelRecording` disables the schedule and the one run, but pending child runs for future occurrences are **not cancelled**. Each will be promoted to RECORDING when their alarm fires, even though the user cancelled the series. `setScheduleEnabled(..., false)` has the same gap: it only toggles a single run's alarm, it does not query and cancel all pending runs sharing the same `recurringRuleId`.--**Fix:** In `cancelRecording` and `setScheduleEnabled(..., false)`, also query `recording_runs WHERE recurring_rule_id = ? AND status = 'SCHEDULED'` and cancel all matching runs.-------### 5.6 `validateRecordingWindow` Silently Skips Provider Limit for Missing Provider--**File:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`--```kotlin-val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE-```--If the provider was deleted between scheduling and the alarm firing, `maxConnections` defaults to `Int.MAX_VALUE`, effectively disabling the per-provider connection limit. An expired provider's recording would proceed regardless of account limits. A more defensive behavior would be to fail the recording with `RecordingFailureCategory.PROVIDER_LIMIT`.-------## 6. Thread Safety--### 6.1 `activeJobs` Map Is Properly Guarded--`activeJobs` uses `activeJobsMutex.withLock { ... }` consistently through `registerActiveJob`, `removeActiveJob`, `isActiveJob`, and `cancelActiveJob`. This is correct. The mutex is a `Mutex` (kotlinx coroutines), which is fair and non-reentrant — no risk of deadlock given the usage pattern.--### 6.2 DB State vs. In-Memory Job State Are Not Synchronized--`observeActiveRecordingCountSync()` counts live coroutine jobs (`activeJobs.values.count { it.isActive }`). `onCaptureFinished` uses this count to decide whether to stop the foreground service. But `observeActiveRecordingCount()` (from `RecordingManager` interface) counts DB rows with `status == RECORDING`. These two counts can diverge:-- A zombie DB row (job died, no `markRunFailed()` cleanup) keeps the DB count high, keeping the notification alive and the service running forever.-- An unexpected process death and restart clears `activeJobs` entirely; reconcile then re-enqueues via the service, but there is a window where the service runs with zero in-memory jobs and a stale DB count.--The foreground service stops on `count == 0` from the DB-backed flow (`observeActiveRecordingCount()`), while `onCaptureFinished` uses the in-memory count. The inconsistency means the service keeps running until a DB observation fires — which is correct long-term, but the `onCaptureFinished` check for `remaining == 0` to call `stopIfIdle()` fires prematurely when the in-memory count reaches 0 while DB rows are still RECORDING. The service then receives the DB update and `collectLatest` stops it cleanly anyway, so in practice this is benign — but it represents conceptual inconsistency.-------## 7. Error Handling--### 7.1 `inferFailureCategory` Is String-Matching Based--**File:** `RecordingSupport.kt`--```kotlin-"connection" in normalized || "http 401" in normalized || "http 403" in normalized ...-```--Failure classification depends on the human-readable exception message. If OkHttp or a capture engine changes its error message wording, the category silently falls back to `UNKNOWN`. The categories `NETWORK`, `AUTH`, `TOKEN_EXPIRED` etc. are important for UI guidance and retry logic. Using structured exception types (sealed class hierarchy) or explicit HTTP status codes would be more reliable.-------### 7.2 HLS AES-128 IV Falls Back Silently to All-Zero IV--**File:** `RecordingCaptureEngine.kt` — `decryptAes128()`--```kotlin-val iv = ivHex?.removePrefix("0x")- ...- ?.takeIf { it.size == 16 }- ?: ByteArray(16) // silent fallback — all zeros-```--If the `#EXT-X-KEY IV=` attribute is absent or has an unexpected format, the IV is silently set to 16 zero bytes. For HLS streams that rely on explicit per-segment IVs (RFC 8216 §4.3.2.4), this produces garbage decryption output. The file is written but cannot be played back. A clear `UnsupportedRecordingException` should be thrown when an IV is expected but cannot be parsed.-------### 7.3 DASH Detection Falls Through to `RecordingSourceType.TS`--**File:** `RecordingSourceResolver.kt` — `probeAdaptiveType()`--If the network probe fails (`runCatching` returning empty string) and the body prefix is empty, the function returns `RecordingSourceType.TS`. A DASH stream that happened to produce a connection error during sniffing would be passed to `TsPassThroughCaptureEngine`, which would fail silently writing non-TS bytes to the output file. After the full `scheduledEndMs` window, the recording would be marked COMPLETED with a corrupted file.-------### 7.4 `migrateLegacyStateIfNeeded` Imports "RECORDING" Status as-is--**File:** `RecordingManagerImpl.kt`--Legacy recordings with `status = RECORDING` are inserted into `recording_runs` at their original status. `reconcileRecordingState()` then calls `RecordingForegroundService.startCapture()` for each, trying to resume recordings that were already complete or interrupted. The run has no `resolvedUrl` populated (the legacy JSON didn't carry resolved URLs), so `startCapture` would fail at `run.resolvedUrl ?: return Result.error(...)`. The run is then left dangling in `RECORDING` state without automatic marking as failed. Consider clamping migrated RECORDING entries to `FAILED` during import.-------## 8. Android Platform Issues--### 8.1 `SCHEDULE_EXACT_ALARM` Permission Revocable on Android 12+--**File:** `RecordingAlarmScheduler.kt`--The app declares `SCHEDULE_EXACT_ALARM`. On Android 12+ (API 31+), users can revoke this permission from Special App Access. The scheduler catches `SecurityException` and falls back to `setAndAllowWhileIdle`, which is **inexact** — it can fire minutes or hours late. For live TV recordings (timed to the minute), this silently degrades scheduling accuracy with no user-visible warning.--Additionally, Android 13 (API 33) introduced `USE_EXACT_ALARM` as an alternative that does not require user grant for certain calendar/alarm applications. Since this is an IPTV player with an explicit DVR use case, that permission may be a better choice. At minimum, the app should check `alarmManager.canScheduleExactAlarms()` before relying on exact timing and surface a prompt if the permission is missing.-------### 8.2 `foregroundServiceType="dataSync"` May Require Additional Permission on Android 14+--**File:** `data/src/main/AndroidManifest.xml`--Android 14 (API 34) requires `FOREGROUND_SERVICE_DATA_SYNC` permission for `dataSync`-type foreground services. This permission is not declared in either `data/AndroidManifest.xml` or `app/AndroidManifest.xml`. The service will fail to start on Android 14+ without it.--```xml-<!-- Missing from manifests -->-<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />-```-------### 8.3 `LOCKED_BOOT_COMPLETED` Triggers Room DB Access Before Decryption--**File:** `RecordingRestoreReceiver.kt`--`LOCKED_BOOT_COMPLETED` fires before the user has unlocked the device. If the app uses device-encrypted storage (the default), the Room database is in the DE (device-encrypted) area and may not be accessible via CE (credential-encrypted) paths. Calling `reconcileRecordingState()` at this point could trigger DB access failures. The receiver should check whether CE storage is available or limit the `LOCKED_BOOT_COMPLETED` response to starting minimal bootstrap only, deferring full reconcile to `BOOT_COMPLETED`.-------### 8.4 `RecordingReconcileWorker` Requires Network for Non-Network Tasks--**File:** `RecordingReconcileWorker.kt`--```kotlin-.setRequiredNetworkType(NetworkType.CONNECTED)-```--The reconcile worker's primary purpose is to mark expired recording rows as FAILED and reschedule alarms. Neither of these operations requires network. The `NetworkType.CONNECTED` constraint prevents the worker from running (for example, after boot in airplane mode), which means recordings that expired while offline keep their stale `SCHEDULED` or `RECORDING` status indefinitely. The network constraint should be removed from the periodic reconcile worker (it's appropriate only if the worker fetched remote data, which it does not).-------### 8.5 `PendingIntent` Request Code Hash Collision Risk--**File:** `RecordingAlarmScheduler.kt`--```kotlin-private fun requestCode(action: String, recordingId: String): Int =- 31 * action.hashCode() + recordingId.hashCode()-```--UUID strings are large but their `String.hashCode()` is a 32-bit integer. Two different UUIDs can share a hash. If two recordings produce the same `requestCode` for the same action, the second `PendingIntent.getBroadcast` call (with `FLAG_UPDATE_CURRENT`) overwrites the first alarm's extra data, silently redirecting the alarm to start/stop the wrong recording. With `FLAG_UPDATE_CURRENT`, only the extras are replaced — so the wrong `recording_id` is delivered to `RecordingAlarmReceiver`.--**Fix:** Pre-allocate monotonically incrementing alarm request codes persisted in the DB (`alarm_request_code` column), or use a stable hash with lower collision probability (e.g., `abs(recordingId.hashCode() xor action.hashCode() * 31)`). Even better: use two separate action strings no longer and separate PendingIntent buckets to reduce the keyspace shared between start and stop alarms.-------## 9. Consistency Issues--### 9.1 `RecordingItem.outputPath` and `outputDisplayPath` Are Identical--**File:** `RecordingSupport.kt` — `toDomain()`, `RecordingManagerImpl.kt` — `toStandaloneDomain()`--```kotlin-outputPath = outputDisplayPath,-outputDisplayPath = outputDisplayPath,-```--`RecordingItem` has both `outputPath` and `outputDisplayPath` populated from the same source. `outputPath` appears to be a legacy field (from the old JSON-file state model). In `deleteOutputTarget`, **both** the SAF URI and the `outputDisplayPath` are used for deletion. For SAF recordings, `outputDisplayPath` is a human-readable label like `"Recordings/ChannelName_...ts"`, not a real filesystem path: `File(outputDisplayPath).delete()` is a silent no-op since the path doesn't exist on the filesystem. This is not harmful (the SAF deletion succeeds), but it's confusing and leaves dead code.-------### 9.2 Backup Import Re-schedules Expired Recording Windows--**File:** `BackupManagerImpl.kt`--```kotlin-if (scheduled.scheduledEndMs <= System.currentTimeMillis()) {- return@forEach-}-```--Historical recordings with past end times are correctly skipped. But the check is coarse: a recording scheduled in the past with daily recurrence is entirely dropped. There is no attempt to roll the recurrence forward to the next occurrence. After a backup restore, recurring recording series are lost if their last scheduled occurrence was before the restore time.-------### 9.3 Manual Recording Has No Conflict Checking for Provider Connection Limit--**File:** `RecordingManagerImpl.kt` — `validateRecordingWindow()`--The connection-limit check `overlapping.count { it.providerId == providerId } >= providerMaxConnections` runs for both `startManualRecording` and `scheduleRecording` (both call `validateRecordingWindow`). This is correct. However, the conflict check for scheduled recordings uses `RecordingConflictDetector.findRecordingRunConflict`, while `validateRecordingWindow` uses a raw DB query. These two paths could reach different conclusions if the `scheduleEnabled` flag on a run has been toggled between the check and the query, since `getOverlapping` does not filter by `scheduleEnabled` but `findRecordingRunConflict` does:--```kotlin-// In validateRecordingWindow — does NOT filter by scheduleEnabled:-val overlapping = recordingRunDao.getOverlapping(startMs, endMs)- .filter { it.status == ... }- .filter { it.scheduleEnabled } // ← manual filter applied after fetch--// In spawnNextRecurringRunIfNeeded:-conflict = activeRuns.findRecordingRunConflict(...) // checks scheduleEnabled too-```--The `validateRecordingWindow` does filter `scheduleEnabled` on the Kotlin side after the DB query, so the semantics match. This is correct but fragile — adding `scheduleEnabled` filtering to the SQL query would be more explicit.-------## 10. Missing Test Coverage--| Area | Test Status |-|---|---|-| `RecordingConflictDetector` | Covered (`RecordingConflictDetectorTest`) — 4 cases |-| `ScheduleRecording` use case | Covered (`ScheduleRecordingTest`) |-| `RecordingManagerImpl` (all paths) | **Not tested** |-| `TsPassThroughCaptureEngine` | **Not tested** |-| `HlsLiveCaptureEngine` (segment fetch, AES, timeout) | **Not tested** |-| `RecordingSourceResolver` (DASH fallback, probe logic) | **Not tested** |-| `RecordingAlarmScheduler` (hash collisions, fallback) | **Not tested** |-| Retention enforcement | **Not tested** (no enforcement exists) |-| `migrateLegacyStateIfNeeded` | **Not tested** |-| Recurring rollover (`spawnNextRecurringRunIfNeeded`) | **Not tested** |--The conflict detector tests are well-structured and cover the boundary (adjacent window = no conflict), terminal-status ignoring, and recurring skip cases. The use-case tests cover the main error paths. However, the `RecordingManagerImpl` core — the most complex component — has zero unit tests. Given the threading concerns and state transitions documented above, this is the most urgent gap.-------## 11. Security Notes--### 11.1 Gson Still Used for Header Serialization--**Files:** `RecordingManagerImpl.kt`, `RecordingSupport.kt` — `headersToJson()` / `headersFromJson()`--The project has migrated to `kotlinx.serialization` for Xtream API responses, but `Gson` is still injected into `RecordingManagerImpl` for recording header persistence. `Map<String, String>` serialization via Gson doesn't expose gadget-chain deserialization risks, but it's inconsistent and keeps a Gson dependency. The header map is trivially representable with `kotlinx.serialization`.-------### 11.2 AES-128 IV Fallback Produces Silent Garbage Output--Covered in §7.2. From a security standpoint, silently falling back to an all-zero IV when the stream provides an explicit IV may produce output that leaks partially decrypted segment data or, more practically, produces a corrupt but not-empty file that appears to have succeeded.-------### 11.3 `sanitizeRecordingFileName` Allows Dots--Pattern: `[^a-zA-Z0-9._ -]` — dots are allowed. While not a path traversal risk (the filename is resolved against a fixed directory), a channel name of `"..ts"` produces a filename of `"..ts"`, which `File.getName()` would return as `"..ts"` and might confuse directory traversal checks in other tooling. Excluding dots from the allowlist (or limiting to a single dot before the extension) would be more robust.-------## 12. Summary Table--| # | Area | Finding | Severity |-|---|---|---|---|-| 2.1 | Race | TOCTOU on concurrent recording start | HIGH |-| 2.2 | Logic | `retryRecording` crashes on expired schedule | HIGH |-| 4.1 | Storage | `retentionDays` stored but never enforced | HIGH |-| 8.2 | Android | Missing `FOREGROUND_SERVICE_DATA_SYNC` permission on API 34+ | HIGH |-| 2.3 | Error | Orphan RECORDING row after `startCapture` failure | MEDIUM |-| 2.4 | Logic | `stopRecording` misclassifies based on stale `bytesWritten` | MEDIUM |-| 3.1 | Race | `promoteScheduledRecording` not serialized per recording | MEDIUM |-| 3.2 | Race | `spawnNextRecurringRunIfNeeded` not transactional | MEDIUM |-| 4.2 | Storage | SAF `availableBytes` always null, no disk-space pre-check | MEDIUM |-| 4.3 | Storage | SAF file name collision silently overwrites existing recording | MEDIUM |-| 5.5 | Logic | Cancel does not cascade to future recurring occurrences | MEDIUM |-| 7.1 | Error | Failure category classification is string-match based | MEDIUM |-| 7.3 | Error | Failed DASH probe falls through as TS, produces corrupt file | MEDIUM |-| 7.4 | Error | Migrated RECORDING-status rows left dangling after legacy migration | MEDIUM |-| 8.1 | Android | `SCHEDULE_EXACT_ALARM` revocable, fallback is silent | MEDIUM |-| 8.3 | Android | `LOCKED_BOOT_COMPLETED` triggers DB access before decryption | MEDIUM |-| 8.4 | Android | Reconcile worker requires network for non-network task | MEDIUM |-| 3.3 | Race | `updateRunProgress` read-modify-write is non-atomic | LOW |-| 4.4 | Storage | Partial files not cleaned up on capture failure | LOW |-| 5.1 | Logic | `retryRecording` has no guard against expired end time (pre-crash) | LOW |-| 5.2 | Logic | Manual recording silently caps at 30 min with no UI notice | LOW |-| 5.3 | Logic | `seenSegments` set unbounded for very long HLS recordings | LOW |-| 5.4 | Logic | `cancelRecording` + `retryRecording` re-enables disabled schedule | LOW |-| 5.6 | Logic | Missing provider silently bypasses connection limit | LOW |-| 7.2 | Error | AES-128 IV fallback to all-zeros is silent | LOW |-| 8.5 | Android | PendingIntent request code hash collision risk | LOW |-| 9.1 | Consistency | `outputPath` and `outputDisplayPath` are redundant | LOW |-| 9.2 | Consistency | Backup import drops recurring schedules instead of rolling forward | LOW |-| 11.1 | Security | Gson still used for header serialization | LOW |-| 11.3 | Security | `sanitizeRecordingFileName` allows dots in pattern | LOW |-| 13.1 | Feature | No in-app recordings playback or library screen | GAP — HIGH |-| 13.2 | Feature | EPG-level scheduling requires user to be watching the channel | GAP — HIGH |-| 13.3 | Feature | No pre/post recording padding | GAP — HIGH |-| 13.4 | Feature | No stalled-capture watchdog (`lastProgressAtMs` never checked) | GAP — MEDIUM |-| 13.5 | Feature | No automatic retry on transient network failure | GAP — MEDIUM |-| 13.6 | Feature | No proactive low-disk-space warning before scheduled recording | GAP — MEDIUM |-| 13.7 | Feature | No WiFi-only recording restriction | GAP — MEDIUM |-| 13.8 | Feature | HLS always picks highest-bandwidth variant regardless of user pref | GAP — MEDIUM |-| 13.9 | Feature | HLS multi-audio and subtitle tracks silently dropped | GAP — MEDIUM |-| 13.10 | Feature | Output always raw `.ts`, no remux to MP4/MKV | GAP — MEDIUM |-| 13.11 | Feature | No series/keyword-based recurring recording rule | GAP — MEDIUM |-| 13.12 | Feature | No "cancel this occurrence" vs. "cancel entire series" UI | GAP — MEDIUM |-| 13.13 | Feature | Completed recordings not integrated with Continue Watching | GAP — LOW |-| 13.14 | Feature | No recording status indicator in channel cards or home screen | GAP — LOW |-| 13.15 | Feature | No push notification on recording failure | GAP — LOW |-| 13.16 | Feature | No search or filter in recordings list | GAP — LOW |-| 13.17 | Feature | No live rewind → recording integration | GAP — LOW |-| 13.18 | Feature | Conflict resolution surfaces an error string, no resolution UI | GAP — LOW |-| 13.19 | Feature | No DLNA/media-server exposure of recordings folder | GAP — LOW |-------## 13. Feature Gaps & Missing Functionality--### 13.1 No In-App Recordings Playback or Library Screen--**Severity:** GAP — HIGH--Completed recordings are files on disk or SAF storage, but there is no player integration and no dedicated "My Recordings" screen reachable from the main navigation. The only recording management UI is buried inside Settings. Users cannot browse or watch what they have recorded without leaving the app and using a file manager or external player. This is the most fundamental feature gap for a DVR.-------### 13.2 EPG-Level Recording Scheduling Not Available--**Severity:** GAP — HIGH--`ScheduleRecording` and `startManualRecording` are only reachable from `PlayerViewModelActions`, requiring the user to navigate to the channel and begin watching before scheduling. A standard DVR allows browsing the EPG grid and pressing Record on any future program without navigating to it first. Additionally, the EPG grid shows no visual indicator (red dot, recording icon) for programs that are already scheduled, so the user has no way to confirm a recording is set without returning to Settings.-------### 13.3 No Pre/Post Recording Padding--**Severity:** GAP — HIGH--There is no option to start recording N minutes before the scheduled program start or to continue recording N minutes after the scheduled end. EPG program times from IPTV providers are frequently off by 1–5 minutes, and live events (sports, concerts) routinely run over. This is a baseline DVR feature expected by users. The `RecordingRequest` model would need `paddingStartMs` and `paddingEndMs` fields, applied before conflict detection and alarm scheduling.-------### 13.4 No Stalled-Capture Watchdog--**Severity:** GAP — MEDIUM--`lastProgressAtMs` is written to the DB by `updateRunProgress()` on every progress callback from the capture engines. However, nothing reads this field to detect a stalled capture. If a stream continuously delivers data at an extremely slow rate (a hung IPTV server sending 1 byte/minute), the recording stays in `RECORDING` state, `bytesWritten` increments slowly, and the recording is eventually marked `COMPLETED` with a useless file. A watchdog timer that fires if `lastProgressAtMs` has not advanced for a configurable threshold (e.g., 60 seconds) would catch this class of failure.-------### 13.5 No Automatic Retry on Transient Network Failure--**Severity:** GAP — MEDIUM--`retryCount` is stored in `RecordingRunEntity` and surfaced in `RecordingItem`, implying retry behavior — but neither `TsPassThroughCaptureEngine` nor `HlsLiveCaptureEngine` has a retry loop. Any network interruption (transient blip, brief server restart) immediately fails the recording permanently via `markRunFailed()`. A backoff retry policy (e.g., 3 attempts with 15-second backoff) inside the capture engines would recover the vast majority of real-world IPTV interruptions without user intervention.-------### 13.6 No Proactive Low-Disk-Space Warning Before Scheduled Recordings--**Severity:** GAP — MEDIUM--There is no threshold check before a scheduled recording fires. If available bytes have dropped below a safe minimum (e.g., < 1 GB) since the recording was scheduled, the alarm fires, the foreground service starts, and the capture engine writes until storage is exhausted — failing mid-recording. A pre-flight check inside `promoteScheduledRecording` comparing `storage.availableBytes` against a configurable minimum (or a fixed conservative default like 512 MB) would allow failing with a clear `RecordingFailureCategory.STORAGE` and a user notification before any bytes are written.-------### 13.7 No WiFi-Only Recording Restriction--**Severity:** GAP — MEDIUM--Recordings run on mobile data as readily as on WiFi. A high-bitrate IPTV stream can easily consume several GB per hour. There is no "record only on WiFi" setting, which users with mobile data plans would expect. The `RecordingStorageConfig` model is a natural place to add a `requireWifi: Boolean` flag, with enforcement in `promoteScheduledRecording` via `ConnectivityManager` before starting capture.-------### 13.8 HLS Capture Always Picks Highest-Bandwidth Variant--**Severity:** GAP — MEDIUM--`HlsLiveCaptureEngine` selects the best variant unconditionally:--```kotlin-val bestVariantUrl = variants.maxByOrNull { it.first }?.second-```--The app already has a per-network quality-cap system for the player (`preferredVideoQuality` persisted per network type). Recording ignores this entirely. A user on a constrained connection who has set a quality cap for WiFi would still record at maximum bitrate, potentially filling storage faster than expected or straining a shared network connection. Recording quality should respect the same preference or expose an independent cap.-------### 13.9 HLS Multi-Audio and Subtitle Tracks Are Silently Dropped--**Severity:** GAP — MEDIUM--The HLS capture engine processes only the video/audio segment stream selected from the master playlist. `#EXT-X-MEDIA TYPE=AUDIO` alternative renditions (e.g., secondary language audio) and `TYPE=SUBTITLES` tracks are never downloaded or muxed. For multi-language IPTV providers, this means every recording loses secondary audio and subtitles. At minimum a warning should be surfaced; ideally, the engine should download and mux the preferred audio rendition alongside the video stream.-------### 13.10 Output Always Written as Raw `.ts` — No Container Remux--**Severity:** GAP — MEDIUM--All recordings are written as raw MPEG-TS (`.ts`) files. While VLC and most IPTV players handle `.ts` natively, most consumer devices (Android gallery, smart TVs, DLNA renderers) expect `.mp4` or `.mkv`. Even a passthrough remux using Android's `MediaMuxer` (copying A/V tracks without transcoding) after the capture completes would significantly improve playback compatibility outside the app. This could be offered as an optional post-processing step in `RecordingStorageConfig`.-------### 13.11 No Series/Keyword-Based Recurring Recording Rule--**Severity:** GAP — MEDIUM--Current recurrence supports `DAILY` and `WEEKLY` at a **fixed time slot**. There is no mechanism to record every episode of a named program regardless of when it airs (a "series link" or "keyword timer" as found in conventional DVRs). EPG data with `Program.title` is already stored; a rule engine that matches program titles against a configured keyword and auto-schedules matching future programs would complete the DVR feature set. The domain model for `RecordingScheduleEntity` would need a `matchRule` field alongside the existing `recurrence`.-------### 13.12 No "Cancel This Occurrence" vs. "Cancel Entire Series" UI--**Severity:** GAP — MEDIUM--`cancelRecording` cancels a single run and disables its parent schedule. For a recurring series this is the equivalent of cancelling the whole series (once the schedule is disabled, `spawnNextRecurringRunIfNeeded` stops spawning). There is no UI distinction between "skip this one episode" and "stop the entire recurring recording". A "skip occurrence" action would mark just the one run as `CANCELLED` while leaving the schedule enabled and future runs untouched. See also §5.5 which covers the related technical gap of cancellation not cascading to already-spawned future runs.-------### 13.13 Completed Recordings Not Integrated with Continue Watching--**Severity:** GAP — LOW--If a user starts watching a completed recording and pauses midway, the resume position is not tracked anywhere. The existing `PlaybackHistoryRepository` infrastructure (used for VOD continue-watching) is sufficient to track recording playback if recordings were treated as a playable content type with a stable content ID. Without this, every re-open of a recording starts from the beginning.-------### 13.14 No Recording Status Indicator in Channel Cards or Home Screen--**Severity:** GAP — LOW--There is no visual indicator on channel cards or in the home screen showing that a recording is currently in progress for a channel, or that a future recording is scheduled. Every mainstream DVR shows at least a red dot on an actively recording channel. `RecordingManager.observeRecordingItems()` is available as a flow; the home and live channel list screens could filter it to decorate the relevant channel cards.-------### 13.15 No Push Notification on Recording Failure--**Severity:** GAP — LOW--When a scheduled recording silently fails at 2 AM (network dropped, storage full, token expired), the only discovery mechanism is the user opening Settings and checking the recordings list. The foreground service notification disappears when recording ends. A separate `NotificationManager` notification posted by `markRunFailed()` — outside the foreground service channel — with the failure reason and a "Retry" action would make failures visible without requiring the user to actively check.-------### 13.16 No Search or Filter in the Recordings List--**Severity:** GAP — LOW--The recordings list in Settings renders a flat `LazyColumn` of all `RecordingItem` entries with no search input, status filter, or sort options. With any meaningful number of recordings (a daily recording rule over weeks produces dozens of entries) the list becomes difficult to use. Status-based filtering (`Scheduled` / `Completed` / `Failed`) and a simple title search would be standard.-------### 13.17 No Live Rewind → Recording Integration--**Severity:** GAP — LOW--`docs/LIVE_REWIND_PLAN.md` describes a live rewind buffer. When a user is watching live TV and realizes mid-program they want to record it from the start, there is no way to "record from the beginning of the buffer". The recording simply starts from now. Integrating the rewind buffer write path with `RecordingCaptureEngine` would allow capturing already-buffered content into the output file before switching to the live stream, a feature called "catch-up recording" on commercial DVRs.-------### 13.18 Conflict Resolution Shows an Error String, No Resolution UI--**Severity:** GAP — LOW--When `validateRecordingWindow` detects a conflict, the result is a plain error string surfaced as a player notice or settings toast. There is no dialog offering the user choices such as: keep the existing recording, replace it with the new one, or adjust timing. A conflict resolution dialog — similar to `BackupImportPreviewDialog` — would give the user agency instead of a dead end.-------### 13.19 No DLNA / Media-Server Exposure of Recordings Folder--**Severity:** GAP — LOW--Recorded files are stored in the app-private external movies directory or a user-chosen SAF folder. Neither is automatically accessible to network media renderers (smart TVs, Kodi, etc.) via DLNA/UPnP. Exposing the recordings folder through an embedded media server (or at minimum documenting that the SAF path should be set to a publicly accessible location) would allow users to watch recordings on other devices without transferring files manually.diff --git a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.ktindex 6665dee7..bc94402f 100644--- a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt@@ -28,4 +28,10 @@ interface RecordingManager {suspend fun reconcileRecordingState(): Result<Unit> = Result.success(Unit)suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> =Result.error("Scheduled promotion is not supported by this recording manager.")+ suspend fun skipOccurrence(recordingId: String): Result<Unit> =+ Result.error("Skip occurrence is not supported by this recording manager.")+ suspend fun forceScheduleRecording(request: RecordingRequest): Result<RecordingItem> =+ Result.error("Force scheduling is not supported by this recording manager.")+ suspend fun getConflictingRecordings(startMs: Long, endMs: Long, providerId: Long): List<RecordingItem> =+ emptyList()}diff --git a/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt b/domain/src/main/java/com/streamvault/domain/model/EpgModels.ktindex 6b1e9e45..7b9f961c 100644--- a/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt+++ b/domain/src/main/java/com/streamvault/domain/model/EpgModels.kt@@ -13,7 +13,9 @@ data class EpgSource(val lastError: String? = null,val priority: Int = 0,val createdAt: Long = System.currentTimeMillis(),- val updatedAt: Long = System.currentTimeMillis()+ val updatedAt: Long = System.currentTimeMillis(),+ val etag: String? = null,+ val lastModifiedHeader: String? = null)/**diff --git a/domain/src/main/java/com/streamvault/domain/model/Program.kt b/domain/src/main/java/com/streamvault/domain/model/Program.ktindex a28f4391..aabed4fd 100644--- a/domain/src/main/java/com/streamvault/domain/model/Program.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Program.kt@@ -20,8 +20,7 @@ data class Program(get() = ((endTime - startTime) / 60000).toInt()fun progressPercent(currentTimeMillis: Long = System.currentTimeMillis()): Float {- if (!isNowPlaying) return 0f- if (currentTimeMillis < startTime || endTime <= startTime) return 0f+ if (endTime <= startTime || currentTimeMillis < startTime || currentTimeMillis >= endTime) return 0freturn ((currentTimeMillis - startTime).toFloat() / (endTime - startTime).toFloat()).coerceIn(0f, 1f)}}diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.ktindex b47f529b..3a39da01 100644--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt@@ -16,7 +16,7 @@ data class Provider(val allowedOutputFormats: List<String> = emptyList(),val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,val xtreamFastSyncEnabled: Boolean = true,- val m3uVodClassificationEnabled: Boolean = true,+ val m3uVodClassificationEnabled: Boolean = false,val status: ProviderStatus = ProviderStatus.UNKNOWN,val lastSyncedAt: Long = 0L,val createdAt: Long = System.currentTimeMillis()diff --git a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.ktindex 087ae0f2..dfbc7f7f 100644--- a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt+++ b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt@@ -46,7 +46,9 @@ data class RecordingRequest(val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,val recurringRuleId: String? = null,val recordNextProgram: Boolean = false,- val priority: Int = 0+ val priority: Int = 0,+ val paddingBeforeMs: Long = 0L,+ val paddingAfterMs: Long = 0L) {init {require(channelName.isNotBlank()) { "channelName must not be blank" }diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.ktindex e887dea3..cddd3a76 100644--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt@@ -20,7 +20,7 @@ interface ProviderRepository {suspend fun deleteProvider(id: Long): Result<Unit>suspend fun setActiveProvider(id: Long): Result<Unit>suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, xtreamFastSyncEnabled: Boolean, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>- suspend fun validateM3u(url: String, name: String, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT, m3uVodClassificationEnabled: Boolean = true, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>+ suspend fun validateM3u(url: String, name: String, epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT, m3uVodClassificationEnabled: Boolean = false, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>suspend fun refreshProviderData(providerId: Long,force: Boolean = false,diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.ktindex 4e4be3b7..511d3b7e 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt@@ -24,7 +24,7 @@ data class M3uProviderSetupCommand(val url: String,val name: String,val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,- val m3uVodClassificationEnabled: Boolean = true,+ val m3uVodClassificationEnabled: Boolean = false,val existingProviderId: Long? = null)diff --git a/domain/src/main/java/com/streamvault/domain/util/AdultContentVisibilityPolicy.kt b/domain/src/main/java/com/streamvault/domain/util/AdultContentVisibilityPolicy.ktnew file mode 100644index 00000000..6ff132ca--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/util/AdultContentVisibilityPolicy.kt@@ -0,0 +1,53 @@+package com.streamvault.domain.util++/**+ * Central policy for adult/protected content visibility across all surfaces.+ *+ * Levels:+ * 0 = OFF – no restrictions+ * 1 = LOCKED – categories visible + PIN-gated; content shown in all surfaces+ * 2 = PRIVATE – categories visible + PIN-gated; content excluded from aggregated surfaces+ * 3 = HIDDEN – adult categories hidden everywhere; content excluded from all surfaces+ *+ * "Aggregated surfaces" are views that mix content from multiple categories:+ * All Channels, Recent (Home + Dashboard), Search, and EPG guide.+ */+object AdultContentVisibilityPolicy {+ const val LEVEL_OFF = 0+ const val LEVEL_LOCKED = 1+ const val LEVEL_PRIVATE = 2+ const val LEVEL_HIDDEN = 3++ /**+ * True when adult content may appear in aggregated surfaces (All Channels,+ * Recent, Search, EPG). Only OFF and LOCKED allow this.+ */+ fun showInAggregatedSurfaces(level: Int): Boolean = level <= LEVEL_LOCKED++ /**+ * True when adult categories appear in navigation/sidebar at all.+ * OFF, LOCKED, and PRIVATE show categories (with lock for the latter two).+ */+ fun showCategories(level: Int): Boolean = level <= LEVEL_PRIVATE++ /**+ * True when accessing an adult category requires a PIN.+ */+ fun requiresPin(level: Int): Boolean = level in LEVEL_LOCKED..LEVEL_PRIVATE++ /**+ * True when repositories should remove adult content from ALL queries,+ * including category-specific browsing. Only applies at HIDDEN level.+ */+ fun hideAllContent(level: Int): Boolean = level >= LEVEL_HIDDEN++ /**+ * Filters [items] for an aggregated surface, removing adult/protected items+ * when the current [level] requires it.+ */+ fun <T> filterForAggregatedSurface(+ items: List<T>,+ level: Int,+ isProtected: T.() -> Boolean+ ): List<T> = if (showInAggregatedSurfaces(level)) items else items.filterNot { it.isProtected() }+}