Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Checkpoint current app and sync refactors

David Nashash6f634b5f24bf
diff --git a/.gitignore b/.gitignore
index b99d9823..e733babe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,6 +21,7 @@ captures/
local.properties
keystore.properties
keystore/
+release-signing-info.local.txt
*.jks
*.keystore
*.p12
diff --git a/app/src/main/java/com/streamvault/app.zip b/app/src/main/java/com/streamvault/app.zip
new file mode 100644
index 00000000..389715d0
Binary files /dev/null and b/app/src/main/java/com/streamvault/app.zip differ
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.kt
index 108d7ab3..c56b8d74 100644
--- a/app/src/main/java/com/streamvault/app/MainActivity.kt
+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt
@@ -95,7 +95,6 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
_pictureInPictureModeFlow.value = isInPictureInPictureMode
handleExternalIntent(intent)
- castManager.ensureInitialized()
if (isTelevisionDevice()) {
lifecycleScope.launch {
watchNextManager.refreshWatchNext()
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index b882b056..fe25593d 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -40,7 +40,10 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_12_13,
StreamVaultDatabase.MIGRATION_13_14,
StreamVaultDatabase.MIGRATION_14_15,
- StreamVaultDatabase.MIGRATION_15_16
+ StreamVaultDatabase.MIGRATION_15_16,
+ StreamVaultDatabase.MIGRATION_16_17,
+ StreamVaultDatabase.MIGRATION_17_18,
+ StreamVaultDatabase.MIGRATION_18_19
)
// 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/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
index 338ed156..17f43d47 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -64,6 +64,7 @@ object Routes {
const val PLAYER = "player"
const val SEARCH = "search"
const val SEARCH_DESTINATION = "search?query={query}"
+ const val MOVIE_DETAIL = "movie_detail/{movieId}"
const val SERIES_DETAIL = "series_detail/{seriesId}"
const val WELCOME = "welcome"
const val PARENTAL_CONTROL_GROUPS = "parental_control_groups/{providerId}"
@@ -158,6 +159,7 @@ object Routes {
)
}
+ fun movieDetail(movieId: Long) = "movie_detail/$movieId"
fun seriesDetail(seriesId: Long) = "series_detail/$seriesId"
fun parentalControlGroups(providerId: Long) = "parental_control_groups/$providerId"
}
@@ -276,7 +278,7 @@ fun AppNavigation(mainActivity: MainActivity) {
)
},
onMovieClick = { movie ->
- navController.navigateToPlayer(Routes.moviePlayer(movie))
+ navController.navigateIfResumed(Routes.movieDetail(movie.id))
},
onSeriesClick = { series ->
navController.navigateIfResumed(Routes.seriesDetail(series.id))
@@ -352,7 +354,7 @@ fun AppNavigation(mainActivity: MainActivity) {
composable(Routes.MOVIES) {
MoviesScreen(
onMovieClick = { movie ->
- navController.navigateToPlayer(Routes.moviePlayer(movie))
+ navController.navigateIfResumed(Routes.movieDetail(movie.id))
},
onNavigate = { route -> tabNavigate(route) },
currentRoute = Routes.MOVIES
@@ -547,7 +549,7 @@ fun AppNavigation(mainActivity: MainActivity) {
)
},
onMovieClick = { movie ->
- navController.navigateToPlayer(Routes.moviePlayer(movie))
+ navController.navigateIfResumed(Routes.movieDetail(movie.id))
},
onSeriesClick = { series ->
navController.navigateIfResumed(Routes.seriesDetail(series.id))
@@ -589,6 +591,20 @@ fun AppNavigation(mainActivity: MainActivity) {
)
}
+ composable(
+ route = Routes.MOVIE_DETAIL,
+ arguments = listOf(
+ navArgument("movieId") { type = NavType.LongType }
+ )
+ ) {
+ com.streamvault.app.ui.screens.movies.MovieDetailScreen(
+ onPlay = { movie ->
+ navController.navigateToPlayer(Routes.moviePlayer(movie))
+ },
+ onBack = { navController.popBackStack() }
+ )
+ }
+
composable(
route = Routes.SERIES_DETAIL,
arguments = listOf(
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.kt
index bdb39db1..d5b33a1f 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
@@ -73,6 +73,7 @@ import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.interaction.rememberTvInteractionSounds
private object ChannelProgressTicker {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@@ -103,6 +104,7 @@ fun FocusableCard(
content: @Composable BoxScope.(Boolean) -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
+ val sounds = rememberTvInteractionSounds()
val scale by animateFloatAsState(
targetValue = if (isFocused) {
@@ -115,7 +117,10 @@ fun FocusableCard(
)
Surface(
- onClick = onClick,
+ onClick = {
+ sounds.playSelect()
+ onClick()
+ },
onLongClick = onLongClick,
modifier = modifier
.width(width)
@@ -128,7 +133,12 @@ fun FocusableCard(
semanticsDescription?.let { contentDescription = it }
semanticsStateDescription?.let { stateDescription = it }
}
- .onFocusChanged { isFocused = it.isFocused },
+ .onFocusChanged {
+ if (it.isFocused && !isFocused) {
+ sounds.playNavigate()
+ }
+ isFocused = it.isFocused
+ },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
scale = ClickableSurfaceDefaults.scale(
focusedScale = 1f,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
index b1a12fed..ca470b56 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
@@ -10,7 +10,12 @@ import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -25,6 +30,7 @@ import com.streamvault.app.ui.theme.OnSurfaceDim
import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.SurfaceElevated
import com.streamvault.app.ui.theme.SurfaceHighlight
+import com.streamvault.app.ui.interaction.rememberTvInteractionSounds
data class SelectionChip(
val key: String,
@@ -54,6 +60,7 @@ fun ChipRowSection(
focusedContainerBoostWhenSelected: Boolean = false
) {
if (chips.isEmpty()) return
+ val sounds = rememberTvInteractionSounds()
Column(
modifier = modifier
@@ -86,8 +93,18 @@ fun ChipRowSection(
contentType = { "selection_chip" }
) { chip ->
val isSelected = chip.key == selectedKey
+ var wasFocused by remember(chip.key) { mutableStateOf(false) }
Surface(
- onClick = chip.onClick,
+ onClick = {
+ sounds.playSelect()
+ chip.onClick()
+ },
+ modifier = Modifier.onFocusChanged {
+ if (it.isFocused && !wasFocused) {
+ sounds.playNavigate()
+ }
+ wasFocused = it.isFocused
+ },
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
focusedContainerColor = if (isSelected && focusedContainerBoostWhenSelected) Primary.copy(alpha = 0.28f) else SurfaceHighlight,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
index 0aac319a..b649c059 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppMediaCards.kt
@@ -52,6 +52,7 @@ import com.streamvault.app.ui.components.rememberCrossfadeImageModel
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.AppMotion
import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.interaction.rememberTvInteractionSounds
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Episode
import com.streamvault.domain.model.Movie
@@ -185,6 +186,7 @@ fun LiveChannelRowSurface(
rowHeight: Dp = 68.dp
) {
var isFocused by remember { mutableStateOf(false) }
+ val sounds = rememberTvInteractionSounds()
val favoriteLabel = stringResource(R.string.a11y_favorite)
val catchUpLabel = stringResource(R.string.a11y_catch_up_available)
val lockedLabel = stringResource(R.string.a11y_locked)
@@ -214,7 +216,10 @@ fun LiveChannelRowSurface(
)
Surface(
- onClick = onClick,
+ onClick = {
+ sounds.playSelect()
+ onClick()
+ },
onLongClick = onLongClick,
modifier = modifier
.fillMaxWidth()
@@ -228,7 +233,12 @@ fun LiveChannelRowSurface(
stateDescription = lockedLabel
}
}
- .onFocusChanged { isFocused = it.isFocused },
+ .onFocusChanged {
+ if (it.isFocused && !isFocused) {
+ sounds.playNavigate()
+ }
+ isFocused = it.isFocused
+ },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = AppColors.SurfaceElevated,
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
index 05f5323a..aa441c36 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
@@ -71,6 +71,7 @@ import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.design.AppColors
import com.streamvault.app.ui.design.AppMotion
import com.streamvault.app.ui.design.FocusSpec
+import com.streamvault.app.ui.interaction.rememberTvInteractionSounds
import com.streamvault.app.ui.design.LocalAppShapes
import com.streamvault.app.ui.design.LocalAppSpacing
@@ -304,6 +305,7 @@ private fun TopNavigationButton(
onClick: () -> Unit
) {
var isFocused by remember { mutableStateOf(false) }
+ val sounds = rememberTvInteractionSounds()
val scale by animateFloatAsState(
targetValue = if (isFocused) FocusSpec.FocusedScale else 1f,
animationSpec = AppMotion.FocusSpec,
@@ -311,14 +313,22 @@ private fun TopNavigationButton(
)
Surface(
- onClick = onClick,
+ onClick = {
+ sounds.playSelect()
+ onClick()
+ },
modifier = modifier
.zIndex(if (isFocused) 1f else 0f) // Keep focused button on top
.graphicsLayer {
scaleX = scale
scaleY = scale
}
- .onFocusChanged { isFocused = it.isFocused },
+ .onFocusChanged {
+ if (it.isFocused && !isFocused) {
+ sounds.playNavigate()
+ }
+ isFocused = it.isFocused
+ },
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (selected) AppColors.BrandMuted else Color.Transparent,
diff --git a/app/src/main/java/com/streamvault/app/ui/interaction/TvInteractionSounds.kt b/app/src/main/java/com/streamvault/app/ui/interaction/TvInteractionSounds.kt
new file mode 100644
index 00000000..8398cdb5
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/interaction/TvInteractionSounds.kt
@@ -0,0 +1,27 @@
+package com.streamvault.app.ui.interaction
+
+import android.view.SoundEffectConstants
+import android.view.View
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.remember
+import androidx.compose.ui.platform.LocalView
+
+data class TvInteractionSounds(
+ val playNavigate: () -> Unit,
+ val playSelect: () -> Unit
+)
+
+@Composable
+fun rememberTvInteractionSounds(): TvInteractionSounds {
+ val view = LocalView.current
+ return remember(view) {
+ TvInteractionSounds(
+ playNavigate = { playSound(view, SoundEffectConstants.NAVIGATION_RIGHT) },
+ playSelect = { playSound(view, SoundEffectConstants.CLICK) }
+ )
+ }
+}
+
+private fun playSound(view: View, sound: Int) {
+ runCatching { view.playSoundEffect(sound) }
+}
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.kt
index 08aa5e5d..b99aca42 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
@@ -21,6 +21,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -95,6 +96,8 @@ fun FullEpgScreen(
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
var selectedProgram by remember { mutableStateOf<Pair<Channel, Program>?>(null) }
var showAdvancedOptions by rememberSaveable { mutableStateOf(false) }
+ var showSearchBar by rememberSaveable { mutableStateOf(false) }
+ var showCategoryPicker by rememberSaveable { mutableStateOf(false) }
val now = rememberGuideNow()
val returnRoute = remember(uiState.selectedCategoryId, uiState.guideAnchorTime, uiState.showFavoritesOnly) {
Routes.epg(
@@ -127,76 +130,49 @@ fun FullEpgScreen(
.background(MaterialTheme.colorScheme.background)
) {
if (uiState.error == null) {
- GuideFilterRow(
- categories = uiState.categories,
- selectedCategoryId = uiState.selectedCategoryId,
- onCategorySelected = viewModel::selectCategory
- )
-
- GuideProgramSearchRow(
- query = uiState.programSearchQuery,
- onQueryChange = viewModel::updateProgramSearchQuery,
- onClear = viewModel::clearProgramSearch
- )
-
- GuideTimeControlsRow(
+ GuideHeaderDeck(
+ uiState = uiState,
+ showSearchBar = showSearchBar || uiState.programSearchQuery.isNotBlank(),
+ showAdvancedOptions = showAdvancedOptions,
+ onToggleSearch = { showSearchBar = !showSearchBar },
+ onOpenCategoryPicker = { showCategoryPicker = true },
+ onToggleAdvancedOptions = { showAdvancedOptions = !showAdvancedOptions },
+ onProgramSearchQueryChange = viewModel::updateProgramSearchQuery,
+ onClearProgramSearch = viewModel::clearProgramSearch,
onJumpToPreviousDay = viewModel::jumpToPreviousDay,
- onPageBackward = viewModel::pageBackward,
- onJumpBackwardHalfHour = viewModel::jumpBackwardHalfHour,
onJumpBackward = viewModel::jumpBackward,
onJumpToNow = viewModel::jumpToNow,
- onJumpForwardHalfHour = viewModel::jumpForwardHalfHour,
onJumpForward = viewModel::jumpForward,
- onPageForward = viewModel::pageForward,
onJumpToPrimeTime = viewModel::jumpToPrimeTime,
+ onJumpToNextDay = viewModel::jumpToNextDay,
+ onPageBackward = viewModel::pageBackward,
+ onJumpBackwardHalfHour = viewModel::jumpBackwardHalfHour,
+ onJumpForwardHalfHour = viewModel::jumpForwardHalfHour,
+ onPageForward = viewModel::pageForward,
onJumpToTomorrow = viewModel::jumpToTomorrow,
- onJumpToNextDay = viewModel::jumpToNextDay
+ onDaySelected = viewModel::jumpToDay,
+ onModeSelected = viewModel::selectChannelMode,
+ onDensitySelected = viewModel::selectDensity,
+ onToggleScheduledOnly = viewModel::toggleScheduledOnly,
+ onToggleFavoritesOnly = viewModel::toggleFavoritesOnly
)
-
- GuideDayRow(
- selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),
- onDaySelected = viewModel::jumpToDay
- )
-
- GuideOptionsToggleRow(
- expanded = showAdvancedOptions,
- onToggle = { showAdvancedOptions = !showAdvancedOptions }
- )
-
- if (showAdvancedOptions) {
- GuideModeRow(
- selectedMode = uiState.selectedChannelMode,
- onModeSelected = viewModel::selectChannelMode
- )
-
- GuideDensityRow(
- selectedDensity = uiState.selectedDensity,
- onDensitySelected = viewModel::selectDensity
- )
-
- GuideViewOptionsRow(
- showScheduledOnly = uiState.showScheduledOnly,
- onToggleScheduledOnly = viewModel::toggleScheduledOnly
- )
-
- GuideFavoritesRow(
- showFavoritesOnly = uiState.showFavoritesOnly,
- onToggleFavoritesOnly = viewModel::toggleFavoritesOnly
- )
- }
-
- GuideSummaryCard(uiState = uiState)
}
when {
uiState.isLoading -> {
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .weight(1f),
+ contentAlignment = Alignment.Center
+ ) {
Text(stringResource(R.string.epg_loading), color = OnBackground)
}
}
uiState.error != null -> {
GuideMessageState(
+ modifier = Modifier.weight(1f),
title = when (uiState.error) {
EpgViewModel.NO_ACTIVE_PROVIDER -> stringResource(R.string.epg_no_provider)
else -> stringResource(R.string.epg_error)
@@ -212,27 +188,26 @@ fun FullEpgScreen(
uiState.channels.isEmpty() -> {
GuideMessageState(
- title = if (uiState.programSearchQuery.isNotBlank()) {
- stringResource(R.string.epg_no_search_results)
- } else if (uiState.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID) {
- if (uiState.showScheduledOnly) {
- stringResource(R.string.epg_no_scheduled_channels)
- } else {
+ modifier = Modifier.weight(1f),
+ title = when {
+ uiState.programSearchQuery.isNotBlank() ->
+ stringResource(R.string.epg_no_search_results)
+ uiState.totalChannelCount == 0 && uiState.selectedCategoryId != ChannelRepository.ALL_CHANNELS_ID ->
+ stringResource(R.string.epg_no_channels_in_category)
+ uiState.totalChannelCount == 0 ->
stringResource(R.string.epg_no_data)
- }
- } else {
- if (uiState.showScheduledOnly) {
+ else ->
stringResource(R.string.epg_no_scheduled_channels)
- } else {
- stringResource(R.string.epg_no_channels_in_category)
- }
},
- subtitle = if (uiState.programSearchQuery.isNotBlank()) {
- stringResource(R.string.epg_search_empty_hint)
- } else if (uiState.showScheduledOnly) {
- stringResource(R.string.epg_scheduled_only_hint)
- } else {
- stringResource(R.string.epg_filter_hint)
+ subtitle = when {
+ uiState.programSearchQuery.isNotBlank() ->
+ stringResource(R.string.epg_search_empty_hint)
+ uiState.totalChannelCount == 0 ->
+ stringResource(R.string.epg_filter_hint)
+ uiState.showScheduledOnly ->
+ stringResource(R.string.epg_scheduled_only_hint)
+ else ->
+ stringResource(R.string.epg_stale_warning)
},
actionLabel = if (uiState.programSearchQuery.isNotBlank()) {
stringResource(R.string.epg_clear_search)
@@ -249,6 +224,7 @@ fun FullEpgScreen(
else -> {
EpgGrid(
+ modifier = Modifier.weight(1f),
channels = uiState.channels,
favoriteChannelIds = uiState.favoriteChannelIds,
programsByChannel = uiState.programsByChannel,
@@ -264,6 +240,18 @@ fun FullEpgScreen(
}
}
+ if (showCategoryPicker) {
+ GuideCategoryPickerDialog(
+ categories = uiState.categories,
+ selectedCategoryId = uiState.selectedCategoryId,
+ onDismiss = { showCategoryPicker = false },
+ onCategorySelected = { categoryId ->
+ showCategoryPicker = false
+ viewModel.selectCategory(categoryId)
+ }
+ )
+ }
+
val dialogState = selectedProgram
if (dialogState != null) {
val (channel, program) = dialogState
@@ -653,19 +641,23 @@ private fun GuideDensityRow(
private fun GuideProgramSearchRow(
query: String,
onQueryChange: (String) -> Unit,
- onClear: () -> Unit
+ onClear: () -> Unit,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),
+ showLabel: Boolean = true
) {
Column(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 12.dp)
+ .padding(contentPadding)
) {
- Text(
- text = stringResource(R.string.epg_search_label),
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim
- )
- Spacer(modifier = Modifier.height(8.dp))
+ if (showLabel) {
+ Text(
+ text = stringResource(R.string.epg_search_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ }
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
@@ -725,23 +717,30 @@ private fun GuideModeRow(
private fun GuideFilterRow(
categories: List<Category>,
selectedCategoryId: Long,
- onCategorySelected: (Long) -> Unit
+ onCategorySelected: (Long) -> Unit,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp),
+ showLabel: Boolean = true
) {
if (categories.isEmpty()) return
Column(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 24.dp)
+ .padding(contentPadding)
) {
- Text(
- text = stringResource(R.string.epg_filter_label),
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim
- )
- Spacer(modifier = Modifier.height(8.dp))
+ if (showLabel) {
+ Text(
+ text = stringResource(R.string.epg_filter_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ }
LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- items(categories, key = { it.id }) { category ->
+ itemsIndexed(
+ items = categories,
+ key = { index, category -> epgCategoryKey(category, index) }
+ ) { _, category ->
Surface(
onClick = { onCategorySelected(category.id) },
colors = ClickableSurfaceDefaults.colors(
@@ -782,19 +781,23 @@ private fun GuideTimeControlsRow(
onPageForward: () -> Unit,
onJumpToPrimeTime: () -> Unit,
onJumpToTomorrow: () -> Unit,
- onJumpToNextDay: () -> Unit
+ onJumpToNextDay: () -> Unit,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 12.dp),
+ showLabel: Boolean = true
) {
Column(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 12.dp)
+ .padding(contentPadding)
) {
- Text(
- text = stringResource(R.string.epg_time_controls),
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim
- )
- Spacer(modifier = Modifier.height(8.dp))
+ if (showLabel) {
+ Text(
+ text = stringResource(R.string.epg_time_controls),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ }
LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
item {
GuideShortcutChip(
@@ -869,7 +872,9 @@ private fun GuideTimeControlsRow(
@Composable
private fun GuideDayRow(
selectedDayStart: Long,
- onDaySelected: (Long) -> Unit
+ onDaySelected: (Long) -> Unit,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp, vertical = 4.dp),
+ showLabel: Boolean = true
) {
val dayFormat = remember { SimpleDateFormat("EEE d MMM", Locale.getDefault()) }
val dayAnchors = remember(selectedDayStart) {
@@ -881,14 +886,16 @@ private fun GuideDayRow(
Column(
modifier = Modifier
.fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 4.dp)
+ .padding(contentPadding)
) {
- Text(
- text = stringResource(R.string.epg_day_selector_label),
- style = MaterialTheme.typography.labelMedium,
- color = OnSurfaceDim
- )
- Spacer(modifier = Modifier.height(8.dp))
+ if (showLabel) {
+ Text(
+ text = stringResource(R.string.epg_day_selector_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ }
LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
items(dayAnchors, key = { it }) { dayStart ->
val isSelected = dayStart == selectedDayStart
@@ -1100,66 +1107,78 @@ private fun GuideSummaryCard(uiState: EpgUiState) {
windowFormat.format(Date(uiState.guideWindowEnd))
)
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ GuideSummaryPill(
+ title = stringResource(
+ R.string.epg_showing_channels,
+ uiState.channels.size,
+ uiState.totalChannelCount
+ ),
+ subtitle = stringResource(
+ R.string.epg_schedule_summary,
+ uiState.channelsWithSchedule,
+ uiState.channels.size
+ ),
+ modifier = Modifier.weight(1f)
+ )
+ GuideSummaryPill(
+ title = windowLabel,
+ subtitle = lastUpdatedLabel ?: stringResource(R.string.epg_updated_now),
+ modifier = Modifier.weight(1f)
+ )
+ if (uiState.isGuideStale) {
+ GuideSummaryPill(
+ title = stringResource(R.string.epg_stale_warning),
+ subtitle = uiState.providerSourceLabel.ifBlank { stringResource(R.string.nav_epg) },
+ modifier = Modifier.weight(1f),
+ accent = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+}
+
+@Composable
+private fun GuideSummaryPill(
+ title: String,
+ subtitle: String,
+ modifier: Modifier = Modifier,
+ accent: Color = Primary
+) {
Surface(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = 24.dp, vertical = 12.dp),
- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
- shape = RoundedCornerShape(14.dp)
+ modifier = modifier,
+ colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight),
+ shape = RoundedCornerShape(16.dp)
) {
Column(
- modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
- verticalArrangement = Arrangement.spacedBy(6.dp)
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
- text = stringResource(
- R.string.epg_showing_channels,
- uiState.channels.size,
- uiState.totalChannelCount
- ),
+ text = title,
style = MaterialTheme.typography.titleSmall,
color = OnSurface
)
Text(
- text = stringResource(
- R.string.epg_schedule_summary,
- uiState.channelsWithSchedule,
- uiState.channels.size
- ),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- Text(
- text = windowLabel,
+ text = subtitle,
style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
+ color = accent
)
- if (lastUpdatedLabel != null) {
- Text(
- text = lastUpdatedLabel,
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
- if (uiState.isGuideStale) {
- Text(
- text = stringResource(R.string.epg_stale_warning),
- style = MaterialTheme.typography.bodySmall,
- color = MaterialTheme.colorScheme.error
- )
- }
}
}
}
@Composable
private fun GuideMessageState(
+ modifier: Modifier = Modifier,
title: String,
subtitle: String?,
actionLabel: String?,
onAction: (() -> Unit)?
) {
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
@@ -1194,6 +1213,7 @@ private fun GuideMessageState(
@Composable
fun EpgGrid(
+ modifier: Modifier = Modifier,
channels: List<Channel>,
favoriteChannelIds: Set<Long>,
programsByChannel: Map<String, List<Program>>,
@@ -1211,7 +1231,7 @@ fun EpgGrid(
}
BoxWithConstraints(
- modifier = Modifier
+ modifier = modifier
.fillMaxSize()
.padding(horizontal = 24.dp, vertical = 16.dp)
) {
@@ -1233,7 +1253,10 @@ fun EpgGrid(
markerStepMs = markerStepMs
)
}
- items(channels, key = { it.id }) { channel ->
+ itemsIndexed(
+ items = channels,
+ key = { index, channel -> epgChannelKey(channel, index) }
+ ) { _, channel ->
val programs = channel.epgChannelId?.let { programsByChannel[it] } ?: emptyList()
EpgRow(
channel = channel,
@@ -1642,6 +1665,357 @@ private fun startOfDay(timestamp: Long): Long {
return calendar.timeInMillis
}
+@Composable
+private fun GuideHeaderDeck(
+ uiState: EpgUiState,
+ showSearchBar: Boolean,
+ showAdvancedOptions: Boolean,
+ onToggleSearch: () -> Unit,
+ onOpenCategoryPicker: () -> Unit,
+ onToggleAdvancedOptions: () -> Unit,
+ onProgramSearchQueryChange: (String) -> Unit,
+ onClearProgramSearch: () -> Unit,
+ onJumpToPreviousDay: () -> Unit,
+ onJumpBackward: () -> Unit,
+ onJumpToNow: () -> Unit,
+ onJumpForward: () -> Unit,
+ onJumpToPrimeTime: () -> Unit,
+ onJumpToNextDay: () -> Unit,
+ onPageBackward: () -> Unit,
+ onJumpBackwardHalfHour: () -> Unit,
+ onJumpForwardHalfHour: () -> Unit,
+ onPageForward: () -> Unit,
+ onJumpToTomorrow: () -> Unit,
+ onDaySelected: (Long) -> Unit,
+ onModeSelected: (GuideChannelMode) -> Unit,
+ onDensitySelected: (GuideDensity) -> Unit,
+ onToggleScheduledOnly: () -> Unit,
+ onToggleFavoritesOnly: () -> Unit
+) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 12.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ GuideSummaryCard(uiState = uiState)
+
+ GuideCategoryLauncherRow(
+ categories = uiState.categories,
+ selectedCategoryId = uiState.selectedCategoryId,
+ onOpenCategoryPicker = onOpenCategoryPicker
+ )
+
+ GuidePrimaryControlsRow(
+ showSearchBar = showSearchBar,
+ showAdvancedOptions = showAdvancedOptions,
+ onJumpToPreviousDay = onJumpToPreviousDay,
+ onJumpBackward = onJumpBackward,
+ onJumpToNow = onJumpToNow,
+ onJumpForward = onJumpForward,
+ onJumpToPrimeTime = onJumpToPrimeTime,
+ onJumpToNextDay = onJumpToNextDay,
+ onOpenCategoryPicker = onOpenCategoryPicker,
+ onToggleSearch = onToggleSearch,
+ onToggleAdvancedOptions = onToggleAdvancedOptions
+ )
+
+ if (showSearchBar) {
+ GuideProgramSearchRow(
+ query = uiState.programSearchQuery,
+ onQueryChange = onProgramSearchQueryChange,
+ onClear = onClearProgramSearch,
+ contentPadding = PaddingValues(0.dp),
+ showLabel = false
+ )
+ }
+
+ if (showAdvancedOptions) {
+ GuideTimeControlsRow(
+ onJumpToPreviousDay = onJumpToPreviousDay,
+ onPageBackward = onPageBackward,
+ onJumpBackwardHalfHour = onJumpBackwardHalfHour,
+ onJumpBackward = onJumpBackward,
+ onJumpToNow = onJumpToNow,
+ onJumpForwardHalfHour = onJumpForwardHalfHour,
+ onJumpForward = onJumpForward,
+ onPageForward = onPageForward,
+ onJumpToPrimeTime = onJumpToPrimeTime,
+ onJumpToTomorrow = onJumpToTomorrow,
+ onJumpToNextDay = onJumpToNextDay,
+ contentPadding = PaddingValues(0.dp),
+ showLabel = false
+ )
+
+ GuideDayRow(
+ selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),
+ onDaySelected = onDaySelected,
+ contentPadding = PaddingValues(0.dp),
+ showLabel = false
+ )
+
+ GuideModeRow(
+ selectedMode = uiState.selectedChannelMode,
+ onModeSelected = onModeSelected
+ )
+
+ GuideDensityRow(
+ selectedDensity = uiState.selectedDensity,
+ onDensitySelected = onDensitySelected
+ )
+
+ GuideViewOptionsRow(
+ showScheduledOnly = uiState.showScheduledOnly,
+ onToggleScheduledOnly = onToggleScheduledOnly
+ )
+
+ GuideFavoritesRow(
+ showFavoritesOnly = uiState.showFavoritesOnly,
+ onToggleFavoritesOnly = onToggleFavoritesOnly
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuidePrimaryControlsRow(
+ showSearchBar: Boolean,
+ showAdvancedOptions: Boolean,
+ onJumpToPreviousDay: () -> Unit,
+ onJumpBackward: () -> Unit,
+ onJumpToNow: () -> Unit,
+ onJumpForward: () -> Unit,
+ onJumpToPrimeTime: () -> Unit,
+ onJumpToNextDay: () -> Unit,
+ onOpenCategoryPicker: () -> Unit,
+ onToggleSearch: () -> Unit,
+ onToggleAdvancedOptions: () -> Unit
+) {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ item { GuideShortcutChip(label = stringResource(R.string.epg_filter_label), onClick = onOpenCategoryPicker) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_previous_day), onClick = onJumpToPreviousDay) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_back), onClick = onJumpBackward) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_now), onClick = onJumpToNow) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_forward), onClick = onJumpForward) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_jump_prime_time), onClick = onJumpToPrimeTime) }
+ item { GuideShortcutChip(label = stringResource(R.string.epg_next_day), onClick = onJumpToNextDay) }
+ item {
+ GuideShortcutChip(
+ label = if (showSearchBar) stringResource(R.string.epg_clear_search) else stringResource(R.string.epg_search_label),
+ onClick = onToggleSearch
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(if (showAdvancedOptions) R.string.epg_hide_options else R.string.epg_show_options),
+ onClick = onToggleAdvancedOptions
+ )
+ }
+ }
+}
+
+@Composable
+private fun GuideCategoryLauncherRow(
+ categories: List<Category>,
+ selectedCategoryId: Long,
+ onOpenCategoryPicker: () -> Unit
+) {
+ val selectedCategory = remember(categories, selectedCategoryId) {
+ categories.firstOrNull { it.id == selectedCategoryId }
+ }
+ Surface(
+ onClick = onOpenCategoryPicker,
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceHighlight,
+ focusedContainerColor = SurfaceElevated,
+ contentColor = OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(16.dp)
+ )
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = selectedCategory?.name ?: stringResource(R.string.epg_filter_label),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurface
+ )
+ Text(
+ text = "${categories.size} categories",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ Text(
+ text = stringResource(R.string.epg_filter_label),
+ style = MaterialTheme.typography.labelLarge,
+ color = Primary
+ )
+ }
+ }
+}
+
+@Composable
+private fun GuideCategoryPickerDialog(
+ categories: List<Category>,
+ selectedCategoryId: Long,
+ onDismiss: () -> Unit,
+ onCategorySelected: (Long) -> Unit
+) {
+ var query by rememberSaveable { mutableStateOf("") }
+ val filteredCategories = remember(categories, query) {
+ val trimmed = query.trim()
+ if (trimmed.isBlank()) {
+ categories
+ } else {
+ categories.filter { it.name.contains(trimmed, ignoreCase = true) }
+ }
+ }
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.65f))
+ .clickable(
+ onClick = onDismiss,
+ indication = null,
+ interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
+ ),
+ contentAlignment = Alignment.Center
+ ) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth(0.58f)
+ .fillMaxHeight(0.78f),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(22.dp)
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = stringResource(R.string.epg_filter_label),
+ style = MaterialTheme.typography.headlineSmall,
+ color = OnSurface
+ )
+ Text(
+ text = "${filteredCategories.size} matches",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_hide_options),
+ onClick = onDismiss
+ )
+ }
+
+ GuideProgramSearchRow(
+ query = query,
+ onQueryChange = { query = it },
+ onClear = { query = "" },
+ contentPadding = PaddingValues(0.dp),
+ showLabel = false
+ )
+
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ itemsIndexed(
+ items = filteredCategories,
+ key = { index, category -> epgCategoryKey(category, index) }
+ ) { _, category ->
+ val isSelected = category.id == selectedCategoryId
+ Surface(
+ onClick = { onCategorySelected(category.id) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceHighlight,
+ focusedContainerColor = SurfaceElevated,
+ contentColor = if (isSelected) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(14.dp)
+ )
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = category.name,
+ style = MaterialTheme.typography.titleMedium,
+ color = if (isSelected) Primary else OnSurface
+ )
+ if (category.count > 0) {
+ Text(
+ text = "${category.count} channels",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ if (isSelected) {
+ Text(
+ text = stringResource(R.string.epg_jump_now),
+ style = MaterialTheme.typography.labelLarge,
+ color = Primary
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+private fun epgCategoryKey(category: Category, index: Int): String {
+ return "category:${category.id}:${category.name.trim()}:$index"
+}
+
+private fun epgChannelKey(channel: Channel, index: Int): String {
+ val epgId = channel.epgChannelId?.trim().orEmpty()
+ return "channel:${channel.id}:${channel.streamId}:${epgId}:${channel.name.trim()}:$index"
+}
+
@Composable
private fun dayRelativeLabel(dayStart: Long): String {
val todayStart = remember { startOfDay(System.currentTimeMillis()) }
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.kt
index d72d9aeb..7e673179 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
@@ -12,6 +12,9 @@ import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.data.preferences.PreferencesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -81,6 +84,7 @@ class EpgViewModel @Inject constructor(
companion object {
const val MAX_CHANNELS = 60
+ private const val MAX_XTREAM_GUIDE_FALLBACK_CHANNELS = 12
const val LOOKBACK_MS = 60 * 60 * 1000L
const val LOOKAHEAD_MS = 6 * 60 * 60 * 1000L
const val HALF_HOUR_SHIFT_MS = 30 * 60 * 1000L
@@ -358,6 +362,7 @@ class EpgViewModel @Inject constructor(
val windowStart = anchorTime - LOOKBACK_MS
val windowEnd = anchorTime + LOOKAHEAD_MS
val guideResult = loadGuidePrograms(
+ provider = provider,
providerId = provider.id,
channels = visibleChannels,
categoryId = resolvedCategoryId,
@@ -454,6 +459,7 @@ class EpgViewModel @Inject constructor(
}
private suspend fun loadGuidePrograms(
+ provider: com.streamvault.domain.model.Provider,
providerId: Long,
channels: List<Channel>,
categoryId: Long,
@@ -494,12 +500,73 @@ class EpgViewModel @Inject constructor(
}
}.getOrElse { emptyMap() }
+ val fallbackProgramsByChannel = fetchXtreamGuideFallback(
+ provider = provider,
+ providerId = providerId,
+ channels = channels,
+ searchQuery = searchQuery,
+ existingProgramsByChannel = programsByChannel,
+ windowStart = windowStart,
+ windowEnd = windowEnd
+ )
+ val mergedProgramsByChannel = programsByChannel + fallbackProgramsByChannel
+
return GuideProgramsResult(
- programsByChannel = programsByChannel,
- failedCount = epgIds.count { epgId -> programsByChannel[epgId].isNullOrEmpty() }
+ programsByChannel = mergedProgramsByChannel,
+ failedCount = epgIds.count { epgId -> mergedProgramsByChannel[epgId].isNullOrEmpty() }
)
}
+ private suspend fun fetchXtreamGuideFallback(
+ provider: com.streamvault.domain.model.Provider,
+ providerId: Long,
+ channels: List<Channel>,
+ searchQuery: String,
+ existingProgramsByChannel: Map<String, List<Program>>,
+ windowStart: Long,
+ windowEnd: Long
+ ): Map<String, List<Program>> {
+ if (provider.type != com.streamvault.domain.model.ProviderType.XTREAM_CODES) {
+ return emptyMap()
+ }
+ if (searchQuery.isNotBlank()) {
+ return emptyMap()
+ }
+
+ val missingChannels = channels.filter { channel ->
+ !channel.epgChannelId.isNullOrBlank() &&
+ channel.streamId > 0L &&
+ existingProgramsByChannel[channel.epgChannelId].isNullOrEmpty()
+ }
+ if (missingChannels.isEmpty()) {
+ return emptyMap()
+ }
+
+ return coroutineScope {
+ missingChannels
+ .take(MAX_XTREAM_GUIDE_FALLBACK_CHANNELS)
+ .map { channel ->
+ async {
+ val result = providerRepository.getProgramsForLiveStream(
+ providerId = providerId,
+ streamId = channel.streamId,
+ epgChannelId = channel.epgChannelId,
+ limit = 12
+ )
+ val programs = (result as? com.streamvault.domain.model.Result.Success)?.data
+ .orEmpty()
+ .filter { program -> program.endTime > windowStart && program.startTime < windowEnd }
+ .sortedBy { program -> program.startTime }
+ val epgId = channel.epgChannelId ?: return@async null
+ if (programs.isEmpty()) null else epgId to programs
+ }
+ }
+ .awaitAll()
+ .mapNotNull { it }
+ .toMap()
+ }
+ }
+
}
private data class GuideRequest(
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.kt
index 257c2185..760560a6 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
@@ -35,6 +35,9 @@ import java.util.concurrent.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.Job
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -551,14 +554,20 @@ class HomeViewModel @Inject constructor(
} else {
emptyMap()
}
+ val fallbackProgramMap = fetchXtreamNowPlayingFallback(
+ providerId = providerId,
+ channels = channels,
+ existingPrograms = freshProgramMap
+ )
+ val mergedProgramMap = freshProgramMap + fallbackProgramMap
val channelEpgIds = channels.mapNotNull { it.epgChannelId }.toSet()
_epgProgramMap.update { existing ->
buildMap {
putAll(existing)
channelEpgIds.forEach { epgId ->
- if (freshProgramMap.containsKey(epgId)) {
- put(epgId, freshProgramMap.getValue(epgId))
+ if (mergedProgramMap.containsKey(epgId)) {
+ put(epgId, mergedProgramMap.getValue(epgId))
} else {
remove(epgId)
}
@@ -568,6 +577,49 @@ class HomeViewModel @Inject constructor(
}
}
+ private suspend fun fetchXtreamNowPlayingFallback(
+ providerId: Long,
+ channels: List<Channel>,
+ existingPrograms: Map<String, Program>
+ ): Map<String, Program> {
+ if (_uiState.value.provider?.type != com.streamvault.domain.model.ProviderType.XTREAM_CODES) {
+ return emptyMap()
+ }
+
+ val missingChannels = channels.filter { channel ->
+ !channel.epgChannelId.isNullOrBlank() &&
+ channel.streamId > 0L &&
+ !existingPrograms.containsKey(channel.epgChannelId)
+ }
+ if (missingChannels.isEmpty()) {
+ return emptyMap()
+ }
+
+ val now = System.currentTimeMillis()
+ return coroutineScope {
+ missingChannels
+ .take(10)
+ .map { channel ->
+ async {
+ val result = providerRepository.getProgramsForLiveStream(
+ providerId = providerId,
+ streamId = channel.streamId,
+ epgChannelId = channel.epgChannelId,
+ limit = 6
+ )
+ val programs = (result as? Result.Success)?.data.orEmpty()
+ val currentProgram = programs.firstOrNull { it.startTime <= now && it.endTime > now }
+ ?: programs.firstOrNull()
+ val epgId = channel.epgChannelId ?: return@async null
+ currentProgram?.let { epgId to it }
+ }
+ }
+ .awaitAll()
+ .mapNotNull { it }
+ .toMap()
+ }
+ }
+
fun updateVisibleChannelWindow(channelIds: List<Long>, focusedChannelId: Long? = null) {
val combinedIds = buildSet {
addAll(channelIds)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt
new file mode 100644
index 00000000..9b86bd01
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailScreen.kt
@@ -0,0 +1,297 @@
+package com.streamvault.app.ui.screens.movies
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.tv.material3.Border
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import coil3.compose.AsyncImage
+import com.streamvault.app.R
+import com.streamvault.app.device.rememberIsTelevisionDevice
+import com.streamvault.app.ui.components.rememberCrossfadeImageModel
+import com.streamvault.app.ui.components.shell.ContentMetadataStrip
+import com.streamvault.app.ui.components.shell.StatusPill
+import com.streamvault.app.ui.design.AppColors
+import com.streamvault.domain.model.Movie
+
+@Composable
+fun MovieDetailScreen(
+ onPlay: (Movie) -> Unit,
+ onBack: () -> Unit,
+ viewModel: MovieDetailViewModel = hiltViewModel()
+) {
+ val uiState by viewModel.uiState.collectAsStateWithLifecycle()
+ val movie = uiState.movie
+
+ when {
+ uiState.isLoading -> {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(AppColors.Canvas),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(stringResource(R.string.movie_loading_details), color = AppColors.TextSecondary)
+ }
+ }
+
+ movie == null -> {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(AppColors.Canvas),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = uiState.error ?: stringResource(R.string.movie_not_found),
+ color = AppColors.Live
+ )
+ }
+ }
+
+ else -> {
+ MovieDetailContent(
+ movie = movie,
+ onPlay = { onPlay(movie) },
+ onBack = onBack
+ )
+ }
+ }
+}
+
+@Composable
+private fun MovieDetailContent(
+ movie: Movie,
+ onPlay: () -> Unit,
+ onBack: () -> Unit
+) {
+ val isTelevisionDevice = rememberIsTelevisionDevice()
+ BoxWithConstraints(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(AppColors.Canvas)
+ ) {
+ val compactLayout = !isTelevisionDevice && maxWidth < 900.dp
+ val heroHeight = when {
+ maxWidth < 700.dp -> 240.dp
+ !isTelevisionDevice && maxWidth < 900.dp -> 300.dp
+ else -> 440.dp
+ }
+ val contentPadding = if (compactLayout) {
+ PaddingValues(horizontal = 16.dp, vertical = 20.dp)
+ } else {
+ PaddingValues(horizontal = 56.dp, vertical = 36.dp)
+ }
+ val posterWidth = if (compactLayout) 148.dp else 240.dp
+
+ AsyncImage(
+ model = rememberCrossfadeImageModel(movie.backdropUrl ?: movie.posterUrl),
+ contentDescription = movie.name,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(heroHeight)
+ .align(Alignment.TopCenter),
+ contentScale = ContentScale.Crop
+ )
+
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(heroHeight)
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(Color.Transparent, AppColors.HeroTop, AppColors.HeroBottom)
+ )
+ )
+ )
+
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = contentPadding,
+ verticalArrangement = Arrangement.spacedBy(24.dp)
+ ) {
+ item {
+ Button(
+ onClick = onBack,
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.Surface.copy(alpha = 0.72f),
+ contentColor = AppColors.TextPrimary
+ ),
+ border = ButtonDefaults.border(
+ border = Border(border = androidx.compose.foundation.BorderStroke(1.dp, AppColors.Outline))
+ )
+ ) {
+ Text(stringResource(R.string.movie_detail_back))
+ }
+ }
+
+ item {
+ if (compactLayout) {
+ Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
+ MoviePoster(movie = movie, posterWidth = posterWidth)
+ MovieDetailHeroText(movie = movie, onPlay = onPlay)
+ }
+ } else {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(28.dp),
+ verticalAlignment = Alignment.Bottom
+ ) {
+ MoviePoster(movie = movie, posterWidth = posterWidth)
+ MovieDetailHeroText(
+ movie = movie,
+ onPlay = onPlay,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun MoviePoster(
+ movie: Movie,
+ posterWidth: androidx.compose.ui.unit.Dp
+) {
+ Box(
+ modifier = Modifier
+ .width(posterWidth)
+ .aspectRatio(2f / 3f)
+ .clip(RoundedCornerShape(24.dp))
+ .background(AppColors.SurfaceElevated)
+ ) {
+ AsyncImage(
+ model = rememberCrossfadeImageModel(movie.posterUrl ?: movie.backdropUrl),
+ contentDescription = movie.name,
+ modifier = Modifier.fillMaxSize(),
+ contentScale = ContentScale.Crop
+ )
+ }
+}
+
+@Composable
+private fun MovieDetailHeroText(
+ movie: Movie,
+ onPlay: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Column(
+ modifier = modifier,
+ verticalArrangement = Arrangement.spacedBy(18.dp)
+ ) {
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ StatusPill(label = stringResource(R.string.nav_movies), containerColor = AppColors.BrandMuted)
+ movie.rating.takeIf { it > 0f }?.let {
+ StatusPill(
+ label = "RTG ${String.format("%.1f", it)}",
+ containerColor = AppColors.Warning,
+ contentColor = Color.Black
+ )
+ }
+ movie.year?.takeIf { it.isNotBlank() }?.let {
+ StatusPill(label = it, containerColor = AppColors.SurfaceEmphasis)
+ }
+ }
+
+ Text(
+ text = movie.name,
+ style = MaterialTheme.typography.displayMedium,
+ color = AppColors.TextPrimary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+
+ ContentMetadataStrip(
+ values = listOf(
+ movie.releaseDate.orEmpty(),
+ movie.duration.orEmpty(),
+ movie.genre.orEmpty()
+ )
+ )
+
+ MovieFactGrid(movie = movie)
+
+ Button(
+ onClick = onPlay,
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.Brand,
+ contentColor = Color.White
+ )
+ ) {
+ Text(stringResource(R.string.movie_detail_play))
+ }
+
+ Text(
+ text = movie.plot?.ifBlank { stringResource(R.string.movie_plot_fallback) }
+ ?: stringResource(R.string.movie_plot_fallback),
+ style = MaterialTheme.typography.bodyLarge,
+ color = AppColors.TextSecondary,
+ maxLines = 6,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+}
+
+@Composable
+private fun MovieFactGrid(movie: Movie) {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ MovieFactRow(label = stringResource(R.string.movie_detail_director), value = movie.director)
+ MovieFactRow(label = stringResource(R.string.movie_detail_release_date), value = movie.releaseDate)
+ MovieFactRow(label = stringResource(R.string.movie_detail_duration), value = movie.duration)
+ MovieFactRow(label = stringResource(R.string.movie_detail_genre), value = movie.genre)
+ MovieFactRow(label = stringResource(R.string.movie_detail_cast), value = movie.cast)
+ }
+}
+
+@Composable
+private fun MovieFactRow(
+ label: String,
+ value: String?
+) {
+ val resolvedValue = value?.takeIf { it.isNotBlank() } ?: stringResource(R.string.movie_detail_unknown)
+ Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextPrimary,
+ modifier = Modifier.width(180.dp)
+ )
+ Text(
+ text = resolvedValue,
+ style = MaterialTheme.typography.bodyLarge,
+ color = AppColors.TextSecondary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt
new file mode 100644
index 00000000..c5a7bb1f
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MovieDetailViewModel.kt
@@ -0,0 +1,64 @@
+package com.streamvault.app.ui.screens.movies
+
+import androidx.lifecycle.SavedStateHandle
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.ProviderRepository
+import dagger.hilt.android.lifecycle.HiltViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+@HiltViewModel
+class MovieDetailViewModel @Inject constructor(
+ savedStateHandle: SavedStateHandle,
+ private val movieRepository: MovieRepository,
+ private val providerRepository: ProviderRepository
+) : ViewModel() {
+
+ private val movieId: Long = checkNotNull(savedStateHandle.get<String>("movieId")?.toLongOrNull())
+
+ private val _uiState = MutableStateFlow(MovieDetailUiState())
+ val uiState: StateFlow<MovieDetailUiState> = _uiState.asStateFlow()
+
+ init {
+ loadMovieDetails()
+ }
+
+ private fun loadMovieDetails() {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isLoading = true) }
+
+ val provider = providerRepository.getActiveProvider().first()
+ if (provider == null) {
+ _uiState.update { it.copy(isLoading = false, error = "No active provider") }
+ return@launch
+ }
+
+ when (val result = movieRepository.getMovieDetails(provider.id, movieId)) {
+ is Result.Success -> _uiState.update {
+ it.copy(isLoading = false, movie = result.data, error = null)
+ }
+ is Result.Error -> _uiState.update {
+ it.copy(isLoading = false, error = result.message)
+ }
+ is Result.Loading -> _uiState.update {
+ it.copy(isLoading = true)
+ }
+ }
+ }
+ }
+}
+
+data class MovieDetailUiState(
+ val isLoading: Boolean = false,
+ val movie: Movie? = null,
+ val error: String? = null
+)
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.kt
index efaebead..e782d692 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
@@ -537,172 +537,168 @@ private fun MoviesVodContent(
}
var draggingMovie by remember { mutableStateOf<Movie?>(null) }
- Column(modifier = Modifier.fillMaxSize()) {
- VodActionChipRow(
- actions = buildList {
- add(
- VodActionChip(
- key = "back_home",
- label = stringResource(R.string.nav_movies),
- detail = stringResource(R.string.category_see_all),
- onClick = { onSelectCategory(null) }
- )
- )
- add(
- VodActionChip(
- key = uiState.fullLibraryCategoryName,
- label = stringResource(R.string.library_full_browse_title_movies),
- detail = "${uiState.libraryCount} titles",
- onClick = onSelectFullLibraryBrowse
- )
- )
- add(
- VodActionChip(
- key = "categories",
- label = stringResource(R.string.movies_categories_title),
- detail = "${uiState.categoryNames.size} groups",
- onClick = { showCategoryPicker = true }
- )
- )
- if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
- add(
- VodActionChip(
- key = uiState.selectedCategory ?: "",
- label = uiState.selectedCategory ?: stringResource(R.string.nav_movies),
- detail = "${uiState.selectedCategoryTotalCount} titles",
- onClick = { showCategoryPicker = true }
- )
- )
- }
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(minSize = 148.dp),
+ modifier = Modifier
+ .fillMaxSize()
+ .onPreviewKeyEvent { event ->
+ if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
+ if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
+ draggingMovie = null
+ onDismissReorder()
+ true
+ } else false
+ } else false
},
- selectedKey = uiState.selectedCategory,
- modifier = Modifier.padding(vertical = 8.dp)
- )
+ contentPadding = PaddingValues(horizontal = 20.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ VodSectionHeader(
+ title = when (uiState.selectedCategory) {
+ uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_movies)
+ else -> uiState.selectedCategory ?: stringResource(R.string.nav_movies)
+ }
+ )
+ }
if (!uiState.isReorderMode) {
- SearchInput(
- value = searchQuery,
- onValueChange = onSearchQueryChange,
- placeholder = stringResource(R.string.movies_search_placeholder),
- onSearch = {},
- modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)
- )
- SelectionChipRow(
- title = stringResource(R.string.library_filter_title),
- chips = movieFilterChips(),
- selectedKey = selectedFilterType.name,
- onChipSelected = { key ->
- LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
- },
- modifier = Modifier.padding(horizontal = 16.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- SelectionChipRow(
- title = stringResource(R.string.library_sort_title),
- chips = LibrarySortBy.entries.map { sort ->
- SelectionChip(
- key = sort.name,
- label = when (sort) {
- LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
- LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
- LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
- LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
- LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
- LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ VodActionChipRow(
+ actions = buildList {
+ add(
+ VodActionChip(
+ key = "back_home",
+ label = stringResource(R.string.nav_movies),
+ onClick = { onSelectCategory(null) }
+ )
+ )
+ add(
+ VodActionChip(
+ key = "categories",
+ label = stringResource(R.string.movies_categories_title),
+ onClick = { showCategoryPicker = true }
+ )
+ )
+ if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
+ add(
+ VodActionChip(
+ key = uiState.fullLibraryCategoryName,
+ label = stringResource(R.string.library_full_browse_title_movies),
+ onClick = onSelectFullLibraryBrowse
+ )
+ )
}
- )
- },
- selectedKey = selectedSortBy.name,
- onChipSelected = { key ->
- LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
- },
- modifier = Modifier.padding(horizontal = 16.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- }
+ },
+ modifier = Modifier.padding(top = 2.dp, bottom = 2.dp)
+ )
+ }
- LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
- modifier = Modifier
- .fillMaxSize()
- .onPreviewKeyEvent { event ->
- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
- draggingMovie = null
- onDismissReorder()
- true
- } else false
- } else false
- },
- contentPadding = PaddingValues(horizontal = 20.dp, vertical = 12.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp),
- verticalArrangement = Arrangement.spacedBy(14.dp)
- ) {
item(span = { GridItemSpan(maxLineSpan) }) {
- VodSectionHeader(
- title = when (uiState.selectedCategory) {
- uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_movies)
- else -> uiState.selectedCategory ?: stringResource(R.string.nav_movies)
- }
+ SearchInput(
+ value = searchQuery,
+ onValueChange = onSearchQueryChange,
+ placeholder = stringResource(R.string.movies_search_placeholder),
+ onSearch = {},
+ modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
- if (uiState.isLoadingSelectedCategory) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(loadingSectionHeight),
- contentAlignment = Alignment.Center
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SelectionChipRow(
+ title = "",
+ chips = movieFilterChips(),
+ selectedKey = selectedFilterType.name,
+ onChipSelected = { key ->
+ LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
+ },
+ modifier = Modifier.padding(horizontal = 0.dp),
+ contentPadding = PaddingValues(horizontal = 4.dp)
+ )
+ }
+
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SelectionChipRow(
+ title = "",
+ chips = LibrarySortBy.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
+ LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
+ LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
+ LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
+ LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ }
+ )
+ },
+ selectedKey = selectedSortBy.name,
+ onChipSelected = { key ->
+ LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
+ },
+ modifier = Modifier.padding(horizontal = 0.dp),
+ contentPadding = PaddingValues(horizontal = 4.dp)
+ )
+ }
+ }
+
+ if (uiState.isLoadingSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(loadingSectionHeight),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- CircularProgressIndicator(color = Color.White)
- Text(
- text = stringResource(R.string.movies_loading),
- color = Color.White.copy(alpha = 0.7f)
- )
- }
+ CircularProgressIndicator(color = Color.White)
+ Text(
+ text = stringResource(R.string.movies_loading),
+ color = Color.White.copy(alpha = 0.7f)
+ )
}
}
- } else {
- gridItems(filteredGridMovies, key = { it.id }) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
- val isDraggingThis = draggingMovie == movie
- MovieCard(
- movie = movie,
- isLocked = isLocked,
- isReorderMode = uiState.isReorderMode,
- isDragging = isDraggingThis,
- onClick = {
- if (uiState.isReorderMode) {
- draggingMovie = if (isDraggingThis) null else movie
- } else if (isLocked) {
- onProtectedMovieClick(movie)
- } else {
- onMovieClick(movie)
- }
- },
- onLongClick = {
- if (!uiState.isReorderMode) onShowDialog(movie)
+ }
+ } else {
+ gridItems(filteredGridMovies, key = { it.id }) { movie ->
+ val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isDraggingThis = draggingMovie == movie
+ MovieCard(
+ movie = movie,
+ isLocked = isLocked,
+ isReorderMode = uiState.isReorderMode,
+ isDragging = isDraggingThis,
+ onClick = {
+ if (uiState.isReorderMode) {
+ draggingMovie = if (isDraggingThis) null else movie
+ } else if (isLocked) {
+ onProtectedMovieClick(movie)
+ } else {
+ onMovieClick(movie)
}
- )
- }
-
- if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- LoadMoreCard(
- label = stringResource(
- R.string.library_load_more,
- uiState.selectedCategoryLoadedCount,
- uiState.selectedCategoryTotalCount
- ),
- onClick = onLoadMore,
- modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
- )
+ },
+ onLongClick = {
+ if (!uiState.isReorderMode) onShowDialog(movie)
}
+ )
+ }
+
+ if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
+ )
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index e458071b..e82d0c66 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
@@ -853,6 +853,10 @@ fun PlayerScreen(
preferredFocusedProgramToken = lastFocusedEpgProgramToken,
onFocusedProgramChange = { token -> lastFocusedEpgProgramToken = token },
onDismiss = { viewModel.closeOverlays() },
+ onOpenArchiveBrowser = {
+ showProgramHistory = true
+ viewModel.closeOverlays()
+ },
onPlayCatchUp = { program ->
viewModel.playCatchUp(program)
viewModel.closeOverlays()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index f4f51384..b0844c94 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -61,7 +61,8 @@ data class NumericChannelInputState(
data class PlayerNoticeState(
val message: String = "",
val recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
- val actions: List<PlayerNoticeAction> = emptyList()
+ val actions: List<PlayerNoticeAction> = emptyList(),
+ val isRetryNotice: Boolean = false
)
data class SeekPreviewState(
@@ -210,6 +211,7 @@ class PlayerViewModel @Inject constructor(
private var channelInfoHideJob: Job? = null
private var liveOverlayHideJob: Job? = null
private var diagnosticsHideJob: Job? = null
+ private var remoteEpgFallbackJob: Job? = null
private var numericInputCommitJob: Job? = null
private var numericInputFeedbackJob: Job? = null
private var playerNoticeHideJob: Job? = null
@@ -222,6 +224,7 @@ class PlayerViewModel @Inject constructor(
private var prepareRequestVersion: Long = 0L
private var currentArtworkUrl: String? = null
private var currentResolvedPlaybackUrl: String = ""
+ private var pendingCatchUpUrls: List<String> = emptyList()
val castConnectionState: StateFlow<CastConnectionState> = castManager.connectionState
@@ -244,6 +247,7 @@ class PlayerViewModel @Inject constructor(
_playerDiagnostics.update { it.copy(playbackStateLabel = state.name.replace('_', ' ')) }
if (state == PlaybackState.READY && currentContentType == ContentType.LIVE) {
zapBufferWatchdogJob?.cancel()
+ dismissRetryNoticeIfPresent()
_currentChannel.value?.let { channel ->
if (channel.errorCount > 0) {
logRepositoryFailure(
@@ -255,6 +259,12 @@ class PlayerViewModel @Inject constructor(
}
}
}
+ viewModelScope.launch {
+ playerEngine.retryStatus.collect { status ->
+ status ?: return@collect
+ showRetryNotice(status)
+ }
+ }
viewModelScope.launch {
recordingManager.observeRecordingItems().collect { items ->
_recordingItems.value = items
@@ -305,6 +315,40 @@ class PlayerViewModel @Inject constructor(
}
viewModelScope.launch {
+ if (isCatchUpPlayback()) {
+ markStreamFailure(currentStreamUrl)
+ setLastFailureReason(error.message)
+
+ val switched = when (recoveryType) {
+ PlayerRecoveryType.NETWORK,
+ PlayerRecoveryType.SOURCE,
+ PlayerRecoveryType.BUFFER_TIMEOUT -> tryNextCatchUpVariantInternal()
+ else -> false
+ }
+
+ if (switched) {
+ appendRecoveryAction("Trying alternate catch-up URL")
+ showPlayerNotice(
+ message = "Trying another replay path for ${channel.name}.",
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP),
+ isRetryNotice = true
+ )
+ return@launch
+ }
+
+ showPlayerNotice(
+ message = resolveCatchUpFailureMessage(
+ channel = channel,
+ archiveRequested = true,
+ programHasArchive = _currentProgram.value?.hasArchive == true
+ ),
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ return@launch
+ }
+
markStreamFailure(currentStreamUrl)
setLastFailureReason(error.message)
logRepositoryFailure(
@@ -324,7 +368,8 @@ class PlayerViewModel @Inject constructor(
showPlayerNotice(
message = "Trying an alternate stream for ${channel.name}.",
recoveryType = recoveryType,
- actions = buildRecoveryActions(recoveryType)
+ actions = buildRecoveryActions(recoveryType),
+ isRetryNotice = true
)
return@launch
}
@@ -595,6 +640,11 @@ class PlayerViewModel @Inject constructor(
archiveEndMs: Long? = null,
archiveTitle: String? = null
) {
+ val hasArchiveRequest = archiveStartMs != null &&
+ archiveEndMs != null &&
+ archiveStartMs > 0L &&
+ archiveEndMs > archiveStartMs &&
+ try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE } == ContentType.LIVE
val requestVersion = ++prepareRequestVersion
val previousProviderId = currentProviderId
val previousCategoryId = currentCategoryId
@@ -608,7 +658,10 @@ class PlayerViewModel @Inject constructor(
currentArtworkUrl = artworkUrl
currentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }
currentProviderId = providerId
- currentStreamClassLabel = if (archiveStartMs != null && archiveEndMs != null) "Catch-up" else "Primary"
+ currentStreamClassLabel = if (hasArchiveRequest) "Catch-up" else "Primary"
+ if (!hasArchiveRequest) {
+ pendingCatchUpUrls = emptyList()
+ }
if (currentContentType != ContentType.LIVE) {
lastRecordedLivePlaybackKey = null
recentChannelsJob?.cancel()
@@ -623,21 +676,25 @@ class PlayerViewModel @Inject constructor(
// Reset tried streams for manual switch
triedAlternativeStreams.clear()
- triedAlternativeStreams.add(streamUrl)
+ if (!hasArchiveRequest) {
+ triedAlternativeStreams.add(streamUrl)
+ }
- viewModelScope.launch {
- val resolvedUrl = resolvePlaybackUrl(streamUrl, internalChannelId, providerId, currentContentType)
- if (requestVersion != prepareRequestVersion) return@launch
- if (resolvedUrl.isNullOrBlank()) {
- showPlayerNotice(message = "No playable stream URL was available.", recoveryType = PlayerRecoveryType.SOURCE)
- return@launch
+ if (!hasArchiveRequest) {
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(streamUrl, internalChannelId, providerId, currentContentType)
+ if (requestVersion != prepareRequestVersion) return@launch
+ if (resolvedUrl.isNullOrBlank()) {
+ showPlayerNotice(message = "No playable stream URL was available.", recoveryType = PlayerRecoveryType.SOURCE)
+ return@launch
+ }
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ preparePlayer(streamInfo)
}
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = resolvedUrl,
- title = currentTitle,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- preparePlayer(streamInfo)
}
// Show context info on entry for both Live and VOD
@@ -692,16 +749,10 @@ class PlayerViewModel @Inject constructor(
}
}
- if (
- currentContentType == ContentType.LIVE &&
- archiveStartMs != null &&
- archiveEndMs != null &&
- archiveStartMs > 0L &&
- archiveEndMs > archiveStartMs
- ) {
+ if (currentContentType == ContentType.LIVE && hasArchiveRequest) {
viewModelScope.launch {
- val catchUpUrl = try {
- providerRepository.buildCatchUpUrl(
+ val catchUpUrls = try {
+ providerRepository.buildCatchUpUrls(
providerId = currentProviderId,
streamId = currentContentId,
start = archiveStartMs / 1000L,
@@ -715,19 +766,12 @@ class PlayerViewModel @Inject constructor(
)
return@launch
}
- if (catchUpUrl != null) {
- currentTitle = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle
- currentStreamUrl = catchUpUrl
- updateStreamClass("Catch-up")
- appendRecoveryAction("Opened catch-up stream")
- val catchupStream = com.streamvault.domain.model.StreamInfo(
- url = catchUpUrl,
- title = currentTitle,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ if (catchUpUrls.isNotEmpty()) {
+ startCatchUpPlayback(
+ urls = catchUpUrls,
+ title = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle,
+ recoveryAction = "Opened catch-up stream"
)
- preparePlayer(catchupStream)
- playerEngine.play()
- _showControls.value = true
} else {
val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = true)
setLastFailureReason(reason)
@@ -777,6 +821,7 @@ class PlayerViewModel @Inject constructor(
)
if (currentContentType == ContentType.LIVE) {
recordLivePlayback(channel)
+ fetchEpg(currentProviderId, channel.epgChannelId, channel.streamId)
}
updateChannelDiagnostics(channel)
}
@@ -902,33 +947,74 @@ class PlayerViewModel @Inject constructor(
)
}
- private fun fetchEpg(providerId: Long, epgChannelId: String?) {
+ private fun fetchEpg(providerId: Long, epgChannelId: String?, streamId: Long = 0L) {
epgJob?.cancel()
- if (providerId > 0 && epgChannelId != null) {
+ remoteEpgFallbackJob?.cancel()
+ if (providerId > 0 && (epgChannelId != null || streamId > 0L)) {
epgJob = viewModelScope.launch {
- launch {
- epgRepository.getNowAndNext(providerId, epgChannelId).collect { (now, next) ->
- _currentProgram.value = now
- _nextProgram.value = next
+ if (epgChannelId != null) {
+ launch {
+ epgRepository.getNowAndNext(providerId, epgChannelId).collect { (now, next) ->
+ _currentProgram.value = now
+ _nextProgram.value = next
+ }
}
- }
- launch {
- // Fetch last 24 hours.
- val now = System.currentTimeMillis()
- val start = now - (24 * 60 * 60 * 1000L)
- epgRepository.getProgramsForChannel(providerId, epgChannelId, start, now).collect { programs ->
- _programHistory.value = programs
- .filter { it.hasArchive }
- .sortedByDescending { it.startTime }
+ launch {
+ // Fetch last 24 hours.
+ val now = System.currentTimeMillis()
+ val start = now - (24 * 60 * 60 * 1000L)
+ epgRepository.getProgramsForChannel(providerId, epgChannelId, start, now).collect { programs ->
+ val catchUpSupported = _currentChannel.value?.catchUpSupported == true
+ _programHistory.value = programs
+ .filter { it.hasArchive || catchUpSupported }
+ .sortedByDescending { it.startTime }
+ }
+ }
+ launch {
+ // Fetch next 6 hours.
+ val now = System.currentTimeMillis()
+ val end = now + (6 * 60 * 60 * 1000L)
+ epgRepository.getProgramsForChannel(providerId, epgChannelId, now, end).collect { programs ->
+ _upcomingPrograms.value = programs.sortedBy { it.startTime }
+ }
}
}
- launch {
- // Fetch next 6 hours.
- val now = System.currentTimeMillis()
- val end = now + (6 * 60 * 60 * 1000L)
- epgRepository.getProgramsForChannel(providerId, epgChannelId, now, end).collect { programs ->
- _upcomingPrograms.value = programs.sortedBy { it.startTime }
+ }
+ if (streamId > 0L) {
+ remoteEpgFallbackJob = viewModelScope.launch {
+ delay(250)
+ if (
+ _currentProgram.value != null ||
+ _nextProgram.value != null ||
+ _programHistory.value.isNotEmpty() ||
+ _upcomingPrograms.value.isNotEmpty()
+ ) {
+ return@launch
}
+
+ val result = providerRepository.getProgramsForLiveStream(
+ providerId = providerId,
+ streamId = streamId,
+ epgChannelId = epgChannelId,
+ limit = 12
+ )
+ val programs = (result as? com.streamvault.domain.model.Result.Success)?.data
+ ?.sortedBy { it.startTime }
+ .orEmpty()
+ if (programs.isEmpty()) {
+ return@launch
+ }
+
+ val now = System.currentTimeMillis()
+ val catchUpSupported = _currentChannel.value?.catchUpSupported == true
+ _currentProgram.value = programs.firstOrNull { it.startTime <= now && it.endTime > now }
+ _nextProgram.value = programs.firstOrNull { it.startTime > now }
+ _programHistory.value = programs
+ .filter { it.endTime <= now && (it.hasArchive || catchUpSupported) }
+ .sortedByDescending { it.startTime }
+ _upcomingPrograms.value = programs
+ .filter { it.endTime > now || it == _currentProgram.value }
+ .sortedBy { it.startTime }
}
}
} else {
@@ -1198,6 +1284,7 @@ class PlayerViewModel @Inject constructor(
currentContentId = channel.id
currentTitle = channel.name
currentStreamUrl = channel.streamUrl
+ pendingCatchUpUrls = emptyList()
updateStreamClass("Primary")
_currentChannel.value = channel
refreshCurrentChannelRecording()
@@ -1228,7 +1315,7 @@ class PlayerViewModel @Inject constructor(
// Pre-warm the next channel in sequence so the subsequent zap is near-instant
preloadAdjacentChannel(index)
- fetchEpg(currentProviderId, channel.epgChannelId)
+ fetchEpg(currentProviderId, channel.epgChannelId, channel.streamId)
// Show bottom live info overlay
_showZapOverlay.value = false
@@ -1312,11 +1399,11 @@ class PlayerViewModel @Inject constructor(
}
private fun resolvePlaybackErrorMessage(error: PlayerError): String = when (classifyPlaybackError(error)) {
- PlayerRecoveryType.NETWORK -> "The stream stopped responding. Check the network or try another source."
- PlayerRecoveryType.SOURCE -> "This stream is unavailable from the provider right now."
+ PlayerRecoveryType.NETWORK -> "The stream stopped responding after retries. Check the network or try another source."
+ PlayerRecoveryType.SOURCE -> "This stream failed after retries on the available paths."
PlayerRecoveryType.DECODER -> "Playback failed in the current decoder path."
PlayerRecoveryType.DRM -> "Playback requires valid DRM credentials or a supported device security level."
- PlayerRecoveryType.BUFFER_TIMEOUT -> "Playback stalled for too long on this stream."
+ PlayerRecoveryType.BUFFER_TIMEOUT -> "Playback stalled for too long after retries on this stream."
PlayerRecoveryType.CATCH_UP -> "Replay is unavailable for the selected program."
PlayerRecoveryType.UNKNOWN -> error.message.ifBlank { "Playback failed for an unknown reason." }
}
@@ -1350,8 +1437,10 @@ class PlayerViewModel @Inject constructor(
private fun updateChannelDiagnostics(channel: com.streamvault.domain.model.Channel) {
val archiveLabel = when {
- channel.catchUpSupported && channel.catchUpSource.isNullOrBlank() -> "Provider advertises catch-up, but replay metadata is incomplete."
- channel.catchUpSupported -> "Catch-up supported (${channel.catchUpDays} days)"
+ channel.catchUpSupported && (channel.streamId > 0L || !channel.catchUpSource.isNullOrBlank()) ->
+ "Catch-up supported (${channel.catchUpDays} days)"
+ channel.catchUpSupported ->
+ "Provider advertises catch-up, but replay metadata is incomplete."
else -> "No archive support advertised"
}
val hints = buildList {
@@ -1361,7 +1450,7 @@ class PlayerViewModel @Inject constructor(
if (channel.alternativeStreams.isNotEmpty()) {
add("${channel.alternativeStreams.size} alternate stream path(s) available.")
}
- if (channel.catchUpSupported && channel.catchUpSource.isNullOrBlank()) {
+ if (channel.catchUpSupported && channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank()) {
add("Replay may fail because this provider did not expose a catch-up template.")
}
}
@@ -1387,6 +1476,13 @@ class PlayerViewModel @Inject constructor(
}
fun hasAlternateStream(): Boolean {
+ if (isCatchUpPlayback()) {
+ return pendingCatchUpUrls.any { altUrl ->
+ altUrl != currentStreamUrl &&
+ altUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[altUrl] ?: 0) == 0
+ }
+ }
val channel = _currentChannel.value ?: return false
return channel.alternativeStreams.any { altUrl ->
altUrl != currentStreamUrl &&
@@ -1396,6 +1492,9 @@ class PlayerViewModel @Inject constructor(
}
fun tryAlternateStream(): Boolean {
+ if (isCatchUpPlayback()) {
+ return tryNextCatchUpVariantInternal()
+ }
val channel = _currentChannel.value ?: return false
return tryAlternateStreamInternal(channel)
}
@@ -1426,6 +1525,37 @@ class PlayerViewModel @Inject constructor(
return true
}
+ private fun isCatchUpPlayback(): Boolean = currentStreamClassLabel == "Catch-up"
+
+ private fun nextCatchUpVariant(): String? {
+ return pendingCatchUpUrls.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl &&
+ altUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[altUrl] ?: 0) == 0
+ } ?: pendingCatchUpUrls.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
+ }
+ }
+
+ private fun tryNextCatchUpVariantInternal(): Boolean {
+ val nextStream = nextCatchUpVariant() ?: return false
+ triedAlternativeStreams.add(nextStream)
+ currentStreamUrl = nextStream
+ updateStreamClass("Catch-up")
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(nextStream, currentContentId, currentProviderId, ContentType.LIVE)
+ ?: return@launch
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ preparePlayer(streamInfo)
+ playerEngine.play()
+ }
+ return true
+ }
+
private fun scheduleZapBufferWatchdog(targetIndex: Int) {
zapBufferWatchdogJob?.cancel()
zapBufferWatchdogJob = viewModelScope.launch {
@@ -1533,6 +1663,37 @@ class PlayerViewModel @Inject constructor(
}
}
+ private suspend fun startCatchUpPlayback(
+ urls: List<String>,
+ title: String,
+ recoveryAction: String
+ ) {
+ val candidates = urls
+ .asSequence()
+ .map { it.trim() }
+ .filter { it.isNotBlank() }
+ .distinct()
+ .toList()
+ val primaryUrl = candidates.firstOrNull() ?: return
+
+ currentTitle = title
+ pendingCatchUpUrls = candidates
+ triedAlternativeStreams.clear()
+ triedAlternativeStreams.add(primaryUrl)
+ currentStreamUrl = primaryUrl
+ updateStreamClass("Catch-up")
+ appendRecoveryAction(recoveryAction)
+
+ val catchupStream = com.streamvault.domain.model.StreamInfo(
+ url = primaryUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ preparePlayer(catchupStream)
+ playerEngine.play()
+ _showControls.value = true
+ }
+
fun playCatchUp(program: Program) {
viewModelScope.launch {
val start = program.startTime / 1000L
@@ -1550,8 +1711,8 @@ class PlayerViewModel @Inject constructor(
return@launch
}
- val catchUpUrl = try {
- providerRepository.buildCatchUpUrl(providerId, streamId, start, end)
+ val catchUpUrls = try {
+ providerRepository.buildCatchUpUrls(providerId, streamId, start, end)
} catch (e: CredentialDecryptionException) {
setLastFailureReason(e.message ?: CredentialDecryptionException.MESSAGE)
showPlayerNotice(
@@ -1561,21 +1722,12 @@ class PlayerViewModel @Inject constructor(
)
return@launch
}
- if (catchUpUrl != null) {
- // Update metadata for player
- currentTitle = "${_currentChannel.value?.name ?: ""}: ${program.title}"
- currentStreamUrl = catchUpUrl
- updateStreamClass("Catch-up")
- appendRecoveryAction("Started program replay")
-
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = catchUpUrl,
- title = currentTitle,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ if (catchUpUrls.isNotEmpty()) {
+ startCatchUpPlayback(
+ urls = catchUpUrls,
+ title = "${_currentChannel.value?.name ?: ""}: ${program.title}",
+ recoveryAction = "Started program replay"
)
- preparePlayer(streamInfo)
- playerEngine.play()
- _showControls.value = true
} else {
val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = program.hasArchive)
setLastFailureReason(reason)
@@ -1599,12 +1751,10 @@ class PlayerViewModel @Inject constructor(
return when {
!channel.catchUpSupported && !programHasArchive ->
"This channel does not advertise archive support on the current provider."
- channel.catchUpSupported && channel.catchUpSource.isNullOrBlank() ->
- "The provider marks this channel as catch-up capable, but no replay template was supplied."
- channel.streamId <= 0L ->
- "The provider did not expose a replay stream identifier for this channel."
+ channel.streamId <= 0L && channel.catchUpSource.isNullOrBlank() ->
+ "The provider advertises catch-up, but did not expose replay metadata for this channel."
else ->
- "The provider did not return a replay stream for the selected program."
+ "Replay is unavailable for the selected program right now."
}
}
@@ -1692,6 +1842,12 @@ class PlayerViewModel @Inject constructor(
_playerNotice.value = null
}
+ private fun dismissRetryNoticeIfPresent() {
+ if (_playerNotice.value?.isRetryNotice == true) {
+ dismissPlayerNotice()
+ }
+ }
+
fun runPlayerNoticeAction(action: PlayerNoticeAction) {
when (action) {
PlayerNoticeAction.RETRY -> {
@@ -1718,13 +1874,15 @@ class PlayerViewModel @Inject constructor(
message: String,
recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
actions: List<PlayerNoticeAction> = emptyList(),
- durationMs: Long = if (actions.isNotEmpty()) 8000L else 3600L
+ durationMs: Long = if (actions.isNotEmpty()) 8000L else 3600L,
+ isRetryNotice: Boolean = false
) {
playerNoticeHideJob?.cancel()
_playerNotice.value = PlayerNoticeState(
message = message,
recoveryType = recoveryType,
- actions = actions.distinct()
+ actions = actions.distinct(),
+ isRetryNotice = isRetryNotice
)
playerNoticeHideJob = viewModelScope.launch {
delay(durationMs)
@@ -1734,6 +1892,26 @@ class PlayerViewModel @Inject constructor(
}
}
+ private fun showRetryNotice(status: com.streamvault.player.PlayerRetryStatus) {
+ val formatLabel = currentPlaybackFormatLabel()
+ val message = "Retrying $formatLabel ${status.attempt}/${status.maxAttempts} in ${status.delayMs / 1000}s..."
+ showPlayerNotice(
+ message = message,
+ recoveryType = PlayerRecoveryType.NETWORK,
+ durationMs = status.delayMs + 1500L,
+ isRetryNotice = true
+ )
+ }
+
+ private fun currentPlaybackFormatLabel(): String {
+ val url = currentResolvedPlaybackUrl.ifBlank { currentStreamUrl }.lowercase(Locale.ROOT)
+ return when {
+ url.contains("ext=m3u8") || url.endsWith(".m3u8") -> "HLS"
+ url.contains("ext=ts") || url.endsWith(".ts") -> "TS"
+ else -> "stream"
+ }
+ }
+
fun restartCurrentProgram() {
val program = _currentProgram.value ?: return
if (program.hasArchive || (_currentChannel.value?.catchUpSupported == true)) {
@@ -1800,6 +1978,20 @@ class PlayerViewModel @Inject constructor(
}
fun retryStream(streamUrl: String, epgChannelId: String?) {
+ if (isCatchUpPlayback()) {
+ viewModelScope.launch {
+ val resolvedUrl = resolvePlaybackUrl(streamUrl, currentContentId, currentProviderId, currentContentType)
+ ?: return@launch
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = resolvedUrl,
+ title = currentTitle,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ preparePlayer(streamInfo)
+ playerEngine.play()
+ }
+ return
+ }
val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L
prepare(streamUrl, epgChannelId, currentId, currentCategoryId, currentProviderId, isVirtualCategory, currentContentType.name, currentTitle)
}
@@ -1941,6 +2133,7 @@ class PlayerViewModel @Inject constructor(
numericInputFeedbackJob?.cancel()
playerNoticeHideJob?.cancel()
epgJob?.cancel()
+ remoteEpgFallbackJob?.cancel()
playlistJob?.cancel()
controlsHideJob?.cancel()
zapOverlayJob?.cancel()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
index d41a5d19..b73e532a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerOverlays.kt
@@ -393,6 +393,20 @@ fun ChannelInfoOverlay(
onInteraction = onOverlayInteracted
)
}
+ if (currentChannel?.catchUpSupported == true) {
+ item {
+ QuickActionButton(
+ icon = stringResource(R.string.player_catchup_badge),
+ label = stringResource(R.string.player_archive),
+ onClick = {
+ onOverlayInteracted()
+ onDismiss()
+ onOpenFullEpg()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ }
+ }
if (currentChannel?.catchUpSupported == true && currentProgram?.hasArchive == true) {
item {
QuickActionButton(
@@ -751,7 +765,12 @@ fun ChannelListOverlay(
horizontalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
) {
- itemsIndexed(recentChannels, key = { _, channel -> channel.id }) { index, channel ->
+ itemsIndexed(
+ recentChannels,
+ key = { index, channel ->
+ "recent:${channel.id}:${channel.streamId}:${channel.epgChannelId.orEmpty()}:${index}"
+ }
+ ) { index, channel ->
Surface(
onClick = {
onOverlayInteracted()
@@ -990,6 +1009,7 @@ fun EpgOverlay(
preferredFocusedProgramToken: Long? = null,
onFocusedProgramChange: (Long) -> Unit = {},
onDismiss: () -> Unit,
+ onOpenArchiveBrowser: (() -> Unit)? = null,
onPlayCatchUp: (Program) -> Unit,
onOverlayInteracted: () -> Unit = {}
) {
@@ -1052,10 +1072,22 @@ fun EpgOverlay(
)
if (currentChannel.catchUpSupported) {
Spacer(Modifier.height(8.dp))
- StatusPill(
- label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
- containerColor = AppColors.BrandMuted
- )
+ if (onOpenArchiveBrowser != null) {
+ QuickActionButton(
+ icon = stringResource(R.string.player_catchup_badge),
+ label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
+ onClick = {
+ onOverlayInteracted()
+ onOpenArchiveBrowser()
+ },
+ onInteraction = onOverlayInteracted
+ )
+ } else {
+ StatusPill(
+ label = stringResource(R.string.epg_catchup_available, currentChannel.catchUpDays),
+ containerColor = AppColors.BrandMuted
+ )
+ }
}
}
Spacer(Modifier.height(8.dp))
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.kt
index f1c841c2..a63aa831 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
@@ -523,172 +523,168 @@ private fun SeriesVodContent(
}
var draggingSeries by remember { mutableStateOf<Series?>(null) }
- Column(modifier = Modifier.fillMaxSize()) {
- VodActionChipRow(
- actions = buildList {
- add(
- VodActionChip(
- key = "back_home",
- label = stringResource(R.string.nav_series),
- detail = stringResource(R.string.category_see_all),
- onClick = { onSelectCategory(null) }
- )
- )
- add(
- VodActionChip(
- key = uiState.fullLibraryCategoryName,
- label = stringResource(R.string.library_full_browse_title_series),
- detail = "${uiState.libraryCount} titles",
- onClick = onSelectFullLibraryBrowse
- )
- )
- add(
- VodActionChip(
- key = "categories",
- label = stringResource(R.string.series_categories_title),
- detail = "${uiState.categoryNames.size} groups",
- onClick = { showCategoryPicker = true }
- )
- )
- if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
- add(
- VodActionChip(
- key = uiState.selectedCategory ?: "",
- label = uiState.selectedCategory ?: stringResource(R.string.nav_series),
- detail = "${uiState.selectedCategoryTotalCount} titles",
- onClick = { showCategoryPicker = true }
- )
- )
- }
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(minSize = 148.dp),
+ modifier = Modifier
+ .fillMaxSize()
+ .onPreviewKeyEvent { event ->
+ if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
+ if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
+ draggingSeries = null
+ onDismissReorder()
+ true
+ } else false
+ } else false
},
- selectedKey = uiState.selectedCategory,
- modifier = Modifier.padding(vertical = 8.dp)
- )
+ contentPadding = PaddingValues(horizontal = 20.dp, vertical = 12.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ VodSectionHeader(
+ title = when (uiState.selectedCategory) {
+ uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_series)
+ else -> uiState.selectedCategory ?: stringResource(R.string.nav_series)
+ }
+ )
+ }
if (!uiState.isReorderMode) {
- SearchInput(
- value = searchQuery,
- onValueChange = onSearchQueryChange,
- placeholder = stringResource(R.string.series_search_placeholder),
- onSearch = {},
- modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp)
- )
- SelectionChipRow(
- title = stringResource(R.string.library_filter_title),
- chips = seriesFilterChips(),
- selectedKey = selectedFilterType.name,
- onChipSelected = { key ->
- LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
- },
- modifier = Modifier.padding(horizontal = 16.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- SelectionChipRow(
- title = stringResource(R.string.library_sort_title),
- chips = LibrarySortBy.entries.map { sort ->
- SelectionChip(
- key = sort.name,
- label = when (sort) {
- LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
- LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
- LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
- LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
- LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
- LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ VodActionChipRow(
+ actions = buildList {
+ add(
+ VodActionChip(
+ key = "back_home",
+ label = stringResource(R.string.nav_series),
+ onClick = { onSelectCategory(null) }
+ )
+ )
+ add(
+ VodActionChip(
+ key = "categories",
+ label = stringResource(R.string.series_categories_title),
+ onClick = { showCategoryPicker = true }
+ )
+ )
+ if (uiState.selectedCategory != uiState.fullLibraryCategoryName) {
+ add(
+ VodActionChip(
+ key = uiState.fullLibraryCategoryName,
+ label = stringResource(R.string.library_full_browse_title_series),
+ onClick = onSelectFullLibraryBrowse
+ )
+ )
}
- )
- },
- selectedKey = selectedSortBy.name,
- onChipSelected = { key ->
- LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
- },
- modifier = Modifier.padding(horizontal = 16.dp),
- contentPadding = PaddingValues(horizontal = 4.dp)
- )
- }
+ },
+ modifier = Modifier.padding(top = 2.dp, bottom = 2.dp)
+ )
+ }
- LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 148.dp),
- modifier = Modifier
- .fillMaxSize()
- .onPreviewKeyEvent { event ->
- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
- draggingSeries = null
- onDismissReorder()
- true
- } else false
- } else false
- },
- contentPadding = PaddingValues(horizontal = 20.dp, vertical = 12.dp),
- horizontalArrangement = Arrangement.spacedBy(12.dp),
- verticalArrangement = Arrangement.spacedBy(14.dp)
- ) {
item(span = { GridItemSpan(maxLineSpan) }) {
- VodSectionHeader(
- title = when (uiState.selectedCategory) {
- uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_series)
- else -> uiState.selectedCategory ?: stringResource(R.string.nav_series)
- }
+ SearchInput(
+ value = searchQuery,
+ onValueChange = onSearchQueryChange,
+ placeholder = stringResource(R.string.series_search_placeholder),
+ onSearch = {},
+ modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
- if (uiState.isLoadingSelectedCategory) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- Box(
- modifier = Modifier
- .fillMaxWidth()
- .height(loadingSectionHeight),
- contentAlignment = Alignment.Center
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SelectionChipRow(
+ title = "",
+ chips = seriesFilterChips(),
+ selectedKey = selectedFilterType.name,
+ onChipSelected = { key ->
+ LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onSelectedFilterTypeChange)
+ },
+ modifier = Modifier.padding(horizontal = 0.dp),
+ contentPadding = PaddingValues(horizontal = 4.dp)
+ )
+ }
+
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ SelectionChipRow(
+ title = "",
+ chips = LibrarySortBy.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ LibrarySortBy.LIBRARY -> stringResource(R.string.library_sort_library)
+ LibrarySortBy.TITLE -> stringResource(R.string.library_sort_az)
+ LibrarySortBy.RELEASE -> stringResource(R.string.library_sort_release)
+ LibrarySortBy.UPDATED -> stringResource(R.string.library_sort_updated)
+ LibrarySortBy.RATING -> stringResource(R.string.library_sort_rating)
+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"
+ }
+ )
+ },
+ selectedKey = selectedSortBy.name,
+ onChipSelected = { key ->
+ LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSelectedSortByChange)
+ },
+ modifier = Modifier.padding(horizontal = 0.dp),
+ contentPadding = PaddingValues(horizontal = 4.dp)
+ )
+ }
+ }
+
+ if (uiState.isLoadingSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(loadingSectionHeight),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(16.dp)
- ) {
- CircularProgressIndicator(color = Color.White)
- Text(
- text = stringResource(R.string.series_loading),
- color = Color.White.copy(alpha = 0.7f)
- )
- }
+ CircularProgressIndicator(color = Color.White)
+ Text(
+ text = stringResource(R.string.series_loading),
+ color = Color.White.copy(alpha = 0.7f)
+ )
}
}
- } else {
- gridItems(filteredGridSeries, key = { it.id }) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
- val isDraggingThis = draggingSeries == series
- SeriesCard(
- series = series,
- isLocked = isLocked,
- isReorderMode = uiState.isReorderMode,
- isDragging = isDraggingThis,
- onClick = {
- if (uiState.isReorderMode) {
- draggingSeries = if (isDraggingThis) null else series
- } else if (isLocked) {
- onProtectedSeriesClick(series.id)
- } else {
- onSeriesClick(series.id)
- }
- },
- onLongClick = {
- if (!uiState.isReorderMode) onShowDialog(series)
+ }
+ } else {
+ gridItems(filteredGridSeries, key = { it.id }) { series ->
+ val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ val isDraggingThis = draggingSeries == series
+ SeriesCard(
+ series = series,
+ isLocked = isLocked,
+ isReorderMode = uiState.isReorderMode,
+ isDragging = isDraggingThis,
+ onClick = {
+ if (uiState.isReorderMode) {
+ draggingSeries = if (isDraggingThis) null else series
+ } else if (isLocked) {
+ onProtectedSeriesClick(series.id)
+ } else {
+ onSeriesClick(series.id)
}
- )
- }
-
- if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- LoadMoreCard(
- label = stringResource(
- R.string.library_load_more,
- uiState.selectedCategoryLoadedCount,
- uiState.selectedCategoryTotalCount
- ),
- onClick = onLoadMore,
- modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
- )
+ },
+ onLongClick = {
+ if (!uiState.isReorderMode) onShowDialog(series)
}
+ )
+ }
+
+ if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
+ )
}
}
}
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.kt
index bf4ecfeb..b38a5886 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
@@ -20,6 +20,7 @@ import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.RecordingItem
import com.streamvault.domain.model.RecordingStorageState
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.VodSyncMode
import com.streamvault.domain.usecase.ExportBackup
import com.streamvault.domain.usecase.ExportBackupCommand
import com.streamvault.domain.usecase.ExportBackupResult
@@ -192,12 +193,18 @@ class SettingsViewModel @Inject constructor(
lastSyncStatus = metadata?.lastSyncStatus ?: "NONE",
lastLiveSync = metadata?.lastLiveSync ?: 0L,
lastMovieSync = metadata?.lastMovieSync ?: 0L,
+ lastMovieAttempt = metadata?.lastMovieAttempt ?: 0L,
+ lastMovieSuccess = metadata?.lastMovieSuccess ?: 0L,
+ lastMoviePartial = metadata?.lastMoviePartial ?: 0L,
lastSeriesSync = metadata?.lastSeriesSync ?: 0L,
lastEpgSync = metadata?.lastEpgSync ?: 0L,
liveCount = metadata?.liveCount ?: 0,
movieCount = metadata?.movieCount ?: 0,
seriesCount = metadata?.seriesCount ?: 0,
epgCount = metadata?.epgCount ?: 0,
+ movieSyncMode = metadata?.movieSyncMode ?: VodSyncMode.UNKNOWN,
+ movieWarningsCount = metadata?.movieWarningsCount ?: 0,
+ movieCatalogStale = metadata?.movieCatalogStale ?: false,
capabilitySummary = buildCapabilitySummary(provider),
sourceLabel = when (provider.type) {
ProviderType.XTREAM_CODES -> "Xtream Codes"
@@ -615,9 +622,9 @@ class SettingsViewModel @Inject constructor(
return when (provider.type) {
ProviderType.XTREAM_CODES -> {
if (provider.epgUrl.isNotBlank()) {
- "Xtream source with guide support. Catch-up is available when the provider exposes replay streams."
+ "Xtream source with XMLTV guide support and on-demand guide fallback. Catch-up is available when the provider exposes replay streams."
} else {
- "Xtream source. Catch-up depends on provider replay support."
+ "Xtream source with on-demand guide fallback. Catch-up depends on provider replay support."
}
}
ProviderType.M3U -> {
@@ -635,12 +642,18 @@ data class ProviderDiagnosticsUiModel(
val lastSyncStatus: String = "NONE",
val lastLiveSync: Long = 0L,
val lastMovieSync: Long = 0L,
+ val lastMovieAttempt: Long = 0L,
+ val lastMovieSuccess: Long = 0L,
+ val lastMoviePartial: Long = 0L,
val lastSeriesSync: Long = 0L,
val lastEpgSync: Long = 0L,
val liveCount: Int = 0,
val movieCount: Int = 0,
val seriesCount: Int = 0,
val epgCount: Int = 0,
+ val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,
+ val movieWarningsCount: Int = 0,
+ val movieCatalogStale: Boolean = false,
val capabilitySummary: String = "",
val sourceLabel: String = "",
val expirySummary: String = "",
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
index e3f2240d..0c6add37 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodCatalogBuilders.kt
@@ -85,10 +85,8 @@ suspend fun <Item> buildVodPreviewCatalog(
.forEach { category ->
val preview = providerPreviews[category.id].orEmpty()
.let { items -> markVodFavorites(items, globalFavoriteIds, itemId, copyWithFavorite) }
- if (preview.isNotEmpty()) {
- previewRows[category.name] = preview
- countMap[category.name] = providerCategoryCounts[category.id] ?: preview.size
- }
+ previewRows[category.name] = preview
+ countMap[category.name] = providerCategoryCounts[category.id] ?: preview.size
}
return VodCatalogSnapshot(
@@ -159,4 +157,4 @@ fun <Item> markVodFavorites(
copyWithFavorite: (Item, Boolean) -> Item
): List<Item> = items.map { item ->
copyWithFavorite(item, itemId(item) in globalFavoriteIds)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 8c504b66..c8885030 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -565,7 +565,7 @@
<string name="player_error_back">Or press Back to return</string>
<string name="player_error_live_hint">Retry, jump back to the last channel, or press Back to leave playback.</string>
<string name="player_channel_list_hint">Select a channel to tune instantly. Back closes the list.</string>
- <string name="player_epg_overlay_hint">Browse upcoming programs here. Select an archive-ready item to start catch-up.</string>
+ <string name="player_epg_overlay_hint">Browse guide details here. Select the catch-up pill to open archive history.</string>
<string name="player_type_movie">Movie</string>
<string name="player_type_series">Series</string>
<string name="player_close">Close</string>
@@ -781,6 +781,17 @@
<string name="series_seasons">Seasons</string>
<string name="series_episodes">Episodes (%1$d)</string>
<string name="series_unwatched_badge">%1$d left to finish</string>
+ <string name="movie_loading_details">Loading details...</string>
+ <string name="movie_not_found">Movie not found</string>
+ <string name="movie_detail_back">Back to library</string>
+ <string name="movie_detail_play">Play</string>
+ <string name="movie_plot_fallback">No plot available</string>
+ <string name="movie_detail_director">Directed By:</string>
+ <string name="movie_detail_release_date">Release Date:</string>
+ <string name="movie_detail_duration">Duration:</string>
+ <string name="movie_detail_genre">Genre:</string>
+ <string name="movie_detail_cast">Cast:</string>
+ <string name="movie_detail_unknown">Unknown</string>
<string name="epg_now_playing">Now Playing</string>
<string name="epg_no_data">No EPG data</string>
<string name="epg_up_next">Up Next</string>
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/17.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/17.json
new file mode 100644
index 00000000..3f08700e
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/17.json
@@ -0,0 +1,1644 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 17,
+ "identityHash": "20f246541ad32a2862c45296c5af46ca",
+ "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, `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": "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, 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"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `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, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '20f246541ad32a2862c45296c5af46ca')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/18.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/18.json
new file mode 100644
index 00000000..b71106d9
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/18.json
@@ -0,0 +1,1686 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 18,
+ "identityHash": "80c8edd0ed4c7a77bb202a4462ec8eb7",
+ "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, `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": "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, 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"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '80c8edd0ed4c7a77bb202a4462ec8eb7')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/19.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/19.json
new file mode 100644
index 00000000..3223f5d2
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/19.json
@@ -0,0 +1,1692 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 19,
+ "identityHash": "2f86328d260146ff68cbd1c6fcf1130c",
+ "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, `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": "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, 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"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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, 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
+ }
+ ],
+ "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": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_content_id_content_type_group_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_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"
+ ]
+ }
+ ]
+ }
+ ],
+ "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, '2f86328d260146ff68cbd1c6fcf1130c')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
index 7b5a423a..1e29c49b 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -26,7 +26,7 @@ import com.streamvault.data.local.entity.*
PlaybackHistoryEntity::class,
SyncMetadataEntity::class
],
- version = 16,
+ version = 19,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
@TypeConverters(RoomEnumConverters::class)
@@ -968,5 +968,31 @@ abstract class StreamVaultDatabase : RoomDatabase() {
)
}
}
+
+ val MIGRATION_16_17 = object : Migration(16, 17) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL(
+ "ALTER TABLE providers ADD COLUMN allowed_output_formats_json TEXT NOT NULL DEFAULT '[]'"
+ )
+ }
+ }
+
+ val MIGRATION_17_18 = object : Migration(17, 18) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_attempt INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_success INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN last_movie_partial INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_sync_mode TEXT NOT NULL DEFAULT 'UNKNOWN'")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_warnings_count INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_catalog_stale INTEGER NOT NULL DEFAULT 0")
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_parallel_failures_remembered INTEGER NOT NULL DEFAULT 0")
+ }
+ }
+
+ val MIGRATION_18_19 = object : Migration(18, 19) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ database.execSQL("ALTER TABLE sync_metadata ADD COLUMN movie_healthy_sync_streak INTEGER NOT NULL DEFAULT 0")
+ }
+ }
}
}
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.kt
index ce118e73..18354bb2 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
@@ -229,6 +229,9 @@ interface MovieDao {
@Query("SELECT id, stream_id AS remote_id FROM movies WHERE provider_id = :providerId")
suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>
+ @Query("SELECT id, stream_id AS remote_id FROM movies WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun getIdMappingsByCategory(providerId: Long, categoryId: Long): List<RemoteIdMapping>
+
@Update
suspend fun update(movie: MovieEntity)
@@ -297,9 +300,15 @@ interface MovieDao {
@Query("DELETE FROM movies WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
+ @Query("DELETE FROM movies WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun deleteByProviderAndCategory(providerId: Long, categoryId: Long)
+
@Query("DELETE FROM movies WHERE id IN (:ids)")
suspend fun deleteByIds(ids: List<Long>)
+ @Query("DELETE FROM movies WHERE provider_id = :providerId AND category_id = :categoryId AND stream_id NOT IN (:remoteIds)")
+ suspend fun deleteMissingByCategory(providerId: Long, categoryId: Long, remoteIds: List<Long>)
+
@Query("""
UPDATE movies
SET watch_progress = (
@@ -328,6 +337,23 @@ interface MovieDao {
restoreWatchProgress(providerId)
}
+ @Transaction
+ suspend fun replaceCategory(providerId: Long, categoryId: Long, movies: List<MovieEntity>) {
+ val existingByRemoteId = getIdMappingsByCategory(providerId, categoryId).associate { it.remoteId to it.id }
+ val remapped = movies
+ .distinctBy { it.streamId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.streamId] ?: 0L) }
+
+ if (remapped.isEmpty()) {
+ deleteByProviderAndCategory(providerId, categoryId)
+ } else {
+ insertAll(remapped)
+ deleteMissingByCategory(providerId, categoryId, remapped.map { it.streamId })
+ }
+
+ restoreWatchProgress(providerId)
+ }
+
@Query("SELECT category_id, COUNT(*) as item_count FROM movies WHERE provider_id = :providerId AND category_id IS NOT NULL GROUP BY category_id")
fun getCategoryCounts(providerId: Long): Flow<List<CategoryCount>>
@@ -394,9 +420,15 @@ interface SeriesDao {
@Query("SELECT id, series_id AS remote_id FROM series WHERE provider_id = :providerId")
suspend fun getIdMappings(providerId: Long): List<RemoteIdMapping>
+ @Query("SELECT id, series_id AS remote_id FROM series WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun getIdMappingsByCategory(providerId: Long, categoryId: Long): List<RemoteIdMapping>
+
@Query("DELETE FROM series WHERE provider_id = :providerId")
suspend fun deleteByProvider(providerId: Long)
+ @Query("DELETE FROM series WHERE provider_id = :providerId AND category_id = :categoryId")
+ suspend fun deleteByProviderAndCategory(providerId: Long, categoryId: Long)
+
@Transaction
suspend fun replaceAll(providerId: Long, series: List<SeriesEntity>) {
val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }
@@ -407,6 +439,24 @@ interface SeriesDao {
insertAll(remapped)
}
+ @Query("DELETE FROM series WHERE provider_id = :providerId AND category_id = :categoryId AND series_id NOT IN (:remoteIds)")
+ suspend fun deleteMissingByCategory(providerId: Long, categoryId: Long, remoteIds: List<Long>)
+
+ @Transaction
+ suspend fun replaceCategory(providerId: Long, categoryId: Long, series: List<SeriesEntity>) {
+ val existingByRemoteId = getIdMappingsByCategory(providerId, categoryId).associate { it.remoteId to it.id }
+ val remapped = series
+ .distinctBy { it.seriesId }
+ .map { entity -> entity.copy(id = existingByRemoteId[entity.seriesId] ?: 0L) }
+
+ if (remapped.isEmpty()) {
+ deleteByProviderAndCategory(providerId, categoryId)
+ } else {
+ insertAll(remapped)
+ deleteMissingByCategory(providerId, categoryId, remapped.map { it.seriesId })
+ }
+ }
+
@Query("SELECT category_id, COUNT(*) as item_count FROM series WHERE provider_id = :providerId AND category_id IS NOT NULL GROUP BY category_id")
fun getCategoryCounts(providerId: Long): Flow<List<CategoryCount>>
@@ -655,6 +705,9 @@ interface ProgramDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(programs: List<ProgramEntity>)
+ @Query("SELECT COUNT(*) FROM programs WHERE provider_id = :providerId")
+ suspend fun countByProvider(providerId: Long): Int
+
@Query("DELETE FROM programs WHERE end_time < :beforeTime")
suspend fun deleteOld(beforeTime: Long): Int
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index cbe6556c..76de65ee 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
@@ -28,6 +28,7 @@ data class ProviderEntity(
@ColumnInfo(name = "max_connections") val maxConnections: Int = 1,
@ColumnInfo(name = "expiration_date") val expirationDate: Long? = null,
@ColumnInfo(name = "api_version") val apiVersion: String? = null,
+ @ColumnInfo(name = "allowed_output_formats_json") val allowedOutputFormatsJson: String = "[]",
val status: ProviderStatus = ProviderStatus.UNKNOWN,
@ColumnInfo(name = "last_synced_at") val lastSyncedAt: Long = 0,
@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()
@@ -383,9 +384,17 @@ data class SyncMetadataEntity(
@ColumnInfo(name = "last_movie_sync") val lastMovieSync: Long = 0,
@ColumnInfo(name = "last_series_sync") val lastSeriesSync: Long = 0,
@ColumnInfo(name = "last_epg_sync") val lastEpgSync: Long = 0,
+ @ColumnInfo(name = "last_movie_attempt") val lastMovieAttempt: Long = 0,
+ @ColumnInfo(name = "last_movie_success") val lastMovieSuccess: Long = 0,
+ @ColumnInfo(name = "last_movie_partial") val lastMoviePartial: Long = 0,
@ColumnInfo(name = "live_count") val liveCount: Int = 0,
@ColumnInfo(name = "movie_count") val movieCount: Int = 0,
@ColumnInfo(name = "series_count") val seriesCount: Int = 0,
@ColumnInfo(name = "epg_count") val epgCount: Int = 0,
- @ColumnInfo(name = "last_sync_status") val lastSyncStatus: String = "NONE"
+ @ColumnInfo(name = "last_sync_status") val lastSyncStatus: String = "NONE",
+ @ColumnInfo(name = "movie_sync_mode") val movieSyncMode: String = "UNKNOWN",
+ @ColumnInfo(name = "movie_warnings_count") val movieWarningsCount: Int = 0,
+ @ColumnInfo(name = "movie_catalog_stale") val movieCatalogStale: Boolean = false,
+ @ColumnInfo(name = "movie_parallel_failures_remembered") val movieParallelFailuresRemembered: Boolean = false,
+ @ColumnInfo(name = "movie_healthy_sync_streak") val movieHealthySyncStreak: Int = 0
)
diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index df73156d..2aad7393 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -7,6 +7,7 @@ import com.streamvault.domain.model.*
private val qualityOptionsGson = Gson()
private val channelQualityOptionsType = object : TypeToken<List<ChannelQualityOption>>() {}.type
+private val providerAllowedOutputFormatsType = object : TypeToken<List<String>>() {}.type
// ── Provider ───────────────────────────────────────────────────────
@@ -23,6 +24,7 @@ fun ProviderEntity.toDomain() = Provider(
maxConnections = maxConnections,
expirationDate = expirationDate,
apiVersion = apiVersion,
+ allowedOutputFormats = decodeAllowedOutputFormats(allowedOutputFormatsJson),
status = status,
lastSyncedAt = lastSyncedAt,
createdAt = createdAt
@@ -41,6 +43,7 @@ fun Provider.toEntity() = ProviderEntity(
maxConnections = maxConnections,
expirationDate = expirationDate,
apiVersion = apiVersion,
+ allowedOutputFormatsJson = encodeAllowedOutputFormats(allowedOutputFormats),
status = status,
lastSyncedAt = lastSyncedAt,
createdAt = createdAt
@@ -48,27 +51,31 @@ fun Provider.toEntity() = ProviderEntity(
// ── Channel ────────────────────────────────────────────────────────
-fun ChannelEntity.toDomain() = Channel(
- id = id,
- name = name,
- logoUrl = logoUrl,
- groupTitle = groupTitle,
- categoryId = categoryId,
- categoryName = categoryName,
- streamUrl = streamUrl,
- epgChannelId = epgChannelId,
- number = number,
- catchUpSupported = catchUpSupported,
- catchUpDays = catchUpDays,
- catchUpSource = catchUpSource,
- providerId = providerId,
- isAdult = isAdult,
- isUserProtected = isUserProtected,
- logicalGroupId = logicalGroupId,
- errorCount = errorCount,
- qualityOptions = decodeQualityOptions(qualityOptionsJson),
- streamId = streamId
-)
+fun ChannelEntity.toDomain(): Channel {
+ val qualityOptions = decodeQualityOptions(qualityOptionsJson)
+ return Channel(
+ id = id,
+ name = name,
+ logoUrl = logoUrl,
+ groupTitle = groupTitle,
+ categoryId = categoryId,
+ categoryName = categoryName,
+ streamUrl = streamUrl,
+ epgChannelId = epgChannelId,
+ number = number,
+ catchUpSupported = catchUpSupported,
+ catchUpDays = catchUpDays,
+ catchUpSource = catchUpSource,
+ providerId = providerId,
+ isAdult = isAdult,
+ isUserProtected = isUserProtected,
+ logicalGroupId = logicalGroupId,
+ errorCount = errorCount,
+ qualityOptions = qualityOptions,
+ alternativeStreams = qualityOptions.mapNotNull { it.url }.filter { it != streamUrl }.distinct(),
+ streamId = streamId
+ )
+}
fun Channel.toEntity() = ChannelEntity(
id = id,
@@ -386,11 +393,20 @@ fun SyncMetadataEntity.toDomain() = SyncMetadata(
lastMovieSync = lastMovieSync,
lastSeriesSync = lastSeriesSync,
lastEpgSync = lastEpgSync,
+ lastMovieAttempt = lastMovieAttempt,
+ lastMovieSuccess = lastMovieSuccess,
+ lastMoviePartial = lastMoviePartial,
liveCount = liveCount,
movieCount = movieCount,
seriesCount = seriesCount,
epgCount = epgCount,
- lastSyncStatus = lastSyncStatus
+ lastSyncStatus = lastSyncStatus,
+ movieSyncMode = runCatching { com.streamvault.domain.model.VodSyncMode.valueOf(movieSyncMode) }
+ .getOrDefault(com.streamvault.domain.model.VodSyncMode.UNKNOWN),
+ movieWarningsCount = movieWarningsCount,
+ movieCatalogStale = movieCatalogStale,
+ movieParallelFailuresRemembered = movieParallelFailuresRemembered,
+ movieHealthySyncStreak = movieHealthySyncStreak
)
fun SyncMetadata.toEntity() = SyncMetadataEntity(
@@ -399,11 +415,19 @@ fun SyncMetadata.toEntity() = SyncMetadataEntity(
lastMovieSync = lastMovieSync,
lastSeriesSync = lastSeriesSync,
lastEpgSync = lastEpgSync,
+ lastMovieAttempt = lastMovieAttempt,
+ lastMovieSuccess = lastMovieSuccess,
+ lastMoviePartial = lastMoviePartial,
liveCount = liveCount,
movieCount = movieCount,
seriesCount = seriesCount,
epgCount = epgCount,
- lastSyncStatus = lastSyncStatus
+ lastSyncStatus = lastSyncStatus,
+ movieSyncMode = movieSyncMode.name,
+ movieWarningsCount = movieWarningsCount,
+ movieCatalogStale = movieCatalogStale,
+ movieParallelFailuresRemembered = movieParallelFailuresRemembered,
+ movieHealthySyncStreak = movieHealthySyncStreak
)
private fun encodeQualityOptions(options: List<ChannelQualityOption>): String? {
@@ -422,6 +446,25 @@ private fun decodeQualityOptions(encoded: String?): List<ChannelQualityOption> {
}.getOrDefault(emptyList())
}
+private fun decodeAllowedOutputFormats(encoded: String?): List<String> {
+ if (encoded.isNullOrBlank()) {
+ return emptyList()
+ }
+ return runCatching {
+ qualityOptionsGson.fromJson<List<String>>(encoded, providerAllowedOutputFormatsType)
+ .orEmpty()
+ .mapNotNull { value -> value.trim().lowercase().takeIf { it.isNotEmpty() } }
+ .distinct()
+ }.getOrDefault(emptyList())
+}
+
+private fun encodeAllowedOutputFormats(formats: List<String>): String {
+ val normalized = formats
+ .mapNotNull { value -> value.trim().lowercase().takeIf { it.isNotEmpty() } }
+ .distinct()
+ return qualityOptionsGson.toJson(normalized, providerAllowedOutputFormatsType)
+}
+
private fun String?.toPlaybackWatchedStatus(): PlaybackWatchedStatus =
runCatching {
this?.let(PlaybackWatchedStatus::valueOf)
diff --git a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt
index 7cd40efc..6055f1bf 100644
--- a/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt
+++ b/data/src/main/java/com/streamvault/data/remote/NetworkTimeoutConfig.kt
@@ -4,4 +4,7 @@ object NetworkTimeoutConfig {
const val CONNECT_TIMEOUT_SECONDS = 30L
const val READ_TIMEOUT_SECONDS = 30L
const val WRITE_TIMEOUT_SECONDS = 30L
-}
\ No newline at end of file
+ const val XTREAM_HEAVY_READ_TIMEOUT_SECONDS = 300L
+ const val XTREAM_HEAVY_WRITE_TIMEOUT_SECONDS = 60L
+ const val XTREAM_HEAVY_CALL_TIMEOUT_SECONDS = 330L
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
index eb2eef28..9fcf21a1 100644
--- a/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
+++ b/data/src/main/java/com/streamvault/data/remote/dto/LenientJsonSerializers.kt
@@ -8,9 +8,11 @@ import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
+import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
@OptIn(ExperimentalSerializationApi::class)
@@ -65,6 +67,81 @@ object LenientNullableLongSerializer : KSerializer<Long?> {
}
}
+@OptIn(ExperimentalSerializationApi::class)
+object LenientNullableBooleanSerializer : KSerializer<Boolean?> {
+ override val descriptor: SerialDescriptor =
+ PrimitiveSerialDescriptor("LenientNullableBoolean", PrimitiveKind.BOOLEAN)
+
+ override fun deserialize(decoder: Decoder): Boolean? {
+ return when (decodePrimitive(decoder)?.trim()?.lowercase()) {
+ null, "" -> null
+ "1", "true", "yes", "y", "on" -> true
+ "0", "false", "no", "n", "off" -> false
+ else -> null
+ }
+ }
+
+ override fun serialize(encoder: Encoder, value: Boolean?) {
+ if (value == null) {
+ encoder.encodeNull()
+ } else {
+ encoder.encodeBoolean(value)
+ }
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientStringSerializer : KSerializer<String> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientString", PrimitiveKind.STRING)
+
+ override fun deserialize(decoder: Decoder): String = decodePrimitive(decoder)?.trim().orEmpty()
+
+ override fun serialize(encoder: Encoder, value: String) {
+ encoder.encodeString(value)
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientNullableStringSerializer : KSerializer<String?> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientNullableString", PrimitiveKind.STRING)
+
+ override fun deserialize(decoder: Decoder): String? = decodePrimitive(decoder)?.trim()?.takeIf { it.isNotEmpty() }
+
+ override fun serialize(encoder: Encoder, value: String?) {
+ if (value == null) {
+ encoder.encodeNull()
+ } else {
+ encoder.encodeString(value)
+ }
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientStringListSerializer : KSerializer<List<String>> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientStringList", PrimitiveKind.STRING)
+
+ override fun deserialize(decoder: Decoder): List<String> = decodeStringList(decoder).orEmpty()
+
+ override fun serialize(encoder: Encoder, value: List<String>) {
+ encoder.encodeString(value.joinToString(","))
+ }
+}
+
+@OptIn(ExperimentalSerializationApi::class)
+object LenientNullableStringListSerializer : KSerializer<List<String>?> {
+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LenientNullableStringList", PrimitiveKind.STRING)
+
+ override fun deserialize(decoder: Decoder): List<String>? = decodeStringList(decoder)
+
+ override fun serialize(encoder: Encoder, value: List<String>?) {
+ if (value == null) {
+ encoder.encodeNull()
+ } else {
+ encoder.encodeString(value.joinToString(","))
+ }
+ }
+}
+
private fun decodePrimitive(decoder: Decoder): String? {
return when (decoder) {
is JsonDecoder -> decoder.decodeJsonElement().primitiveContentOrNull()
@@ -74,6 +151,41 @@ private fun decodePrimitive(decoder: Decoder): String? {
private fun JsonElement.primitiveContentOrNull(): String? {
if (this == JsonNull) return null
- val primitive = this as? JsonPrimitive ?: throw SerializationException("Expected JSON primitive")
+ val primitive = this as? JsonPrimitive ?: return null
return if (primitive.isString) primitive.content else primitive.toString()
-}
\ No newline at end of file
+}
+
+private fun decodeStringList(decoder: Decoder): List<String>? {
+ return when (decoder) {
+ is JsonDecoder -> decoder.decodeJsonElement().stringListOrNull()
+ else -> runCatching { decoder.decodeString() }.getOrNull()?.toLenientStringList()
+ }
+}
+
+private fun JsonElement.stringListOrNull(): List<String>? {
+ return when (this) {
+ JsonNull -> null
+ is JsonPrimitive -> this.primitiveContentOrNull()?.toLenientStringList()
+ is JsonArray -> this.flatMap { element -> element.stringListOrNull().orEmpty() }.normalizeStringList()
+ is JsonObject -> this.values.flatMap { element -> element.stringListOrNull().orEmpty() }.normalizeStringList()
+ else -> null
+ }
+}
+
+private fun String.toLenientStringList(): List<String> {
+ val normalized = trim()
+ if (normalized.isEmpty() || normalized.equals("null", ignoreCase = true)) {
+ return emptyList()
+ }
+ val unwrapped = normalized.removePrefix("[").removeSuffix("]")
+ val splitRegex = Regex("""\s*(?:,|\|)\s*""")
+ return unwrapped
+ .split(splitRegex)
+ .map { token -> token.trim().trim('"', '\'') }
+ .filter { token -> token.isNotEmpty() && !token.equals("null", ignoreCase = true) }
+ .ifEmpty { listOf(normalized.trim('"', '\'')) }
+}
+
+private fun List<String>.normalizeStringList(): List<String> =
+ map { it.trim().trim('"', '\'') }
+ .filter { it.isNotEmpty() && !it.equals("null", ignoreCase = true) }
diff --git a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
index 7384351c..fea8f5f2 100644
--- a/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
+++ b/data/src/main/java/com/streamvault/data/remote/dto/XtreamDtos.kt
@@ -21,7 +21,7 @@ data class XtreamUserInfo(
@SerialName("active_cons") val activeConnections: String = "0",
@SerialName("created_at") val createdAt: String = "",
@SerialName("max_connections") val maxConnections: String = "1",
- @SerialName("allowed_output_formats") val allowedOutputFormats: List<String> = emptyList()
+ @SerialName("allowed_output_formats") @Serializable(with = LenientStringListSerializer::class) val allowedOutputFormats: List<String> = emptyList()
)
@Serializable
@@ -40,48 +40,58 @@ data class XtreamServerInfo(
@Serializable
data class XtreamCategory(
- @SerialName("category_id") val categoryId: String = "0",
- @SerialName("category_name") val categoryName: String = "",
+ @SerialName("category_id") @Serializable(with = LenientStringSerializer::class) val categoryId: String = "0",
+ @SerialName("category_name") @Serializable(with = LenientStringSerializer::class) val categoryName: String = "",
@SerialName("parent_id") @Serializable(with = LenientIntSerializer::class) val parentId: Int = 0
)
@Serializable
data class XtreamStream(
@SerialName("num") @Serializable(with = LenientIntSerializer::class) val num: Int = 0,
- @SerialName("name") val name: String = "",
- @SerialName("stream_type") val streamType: String = "",
+ @SerialName("name") @Serializable(with = LenientStringSerializer::class) val name: String = "",
+ @SerialName("stream_type") @Serializable(with = LenientStringSerializer::class) val streamType: String = "",
@SerialName("stream_id") @Serializable(with = LenientLongSerializer::class) val streamId: Long = 0,
- @SerialName("stream_icon") val streamIcon: String? = null,
- @SerialName("epg_channel_id") val epgChannelId: String? = null,
- @SerialName("added") val added: String? = null,
- @SerialName("category_id") val categoryId: String? = null,
- @SerialName("category_name") val categoryName: String? = null,
- @SerialName("custom_sid") val customSid: String? = null,
+ @SerialName("stream_icon") @Serializable(with = LenientNullableStringSerializer::class) val streamIcon: String? = null,
+ @SerialName("cover_big") @Serializable(with = LenientNullableStringSerializer::class) val coverBig: String? = null,
+ @SerialName("epg_channel_id") @Serializable(with = LenientNullableStringSerializer::class) val epgChannelId: String? = null,
+ @SerialName("added") @Serializable(with = LenientNullableStringSerializer::class) val added: String? = null,
+ @SerialName("category_id") @Serializable(with = LenientNullableStringSerializer::class) val categoryId: String? = null,
+ @SerialName("category_name") @Serializable(with = LenientNullableStringSerializer::class) val categoryName: String? = null,
+ @SerialName("category_ids") @Serializable(with = LenientNullableStringListSerializer::class) val categoryIds: List<String>? = null,
+ @SerialName("custom_sid") @Serializable(with = LenientNullableStringSerializer::class) val customSid: String? = null,
@SerialName("tv_archive") @Serializable(with = LenientIntSerializer::class) val tvArchive: Int = 0,
- @SerialName("direct_source") val directSource: String? = null,
+ @SerialName("direct_source") @Serializable(with = LenientNullableStringSerializer::class) val directSource: String? = null,
@SerialName("tv_archive_duration") @Serializable(with = LenientNullableIntSerializer::class) val tvArchiveDuration: Int? = null,
- @SerialName("container_extension") val containerExtension: String? = null,
- @SerialName("rating") val rating: String? = null,
- @SerialName("rating_5based") val rating5based: String? = null
+ @SerialName("container_extension") @Serializable(with = LenientNullableStringSerializer::class) val containerExtension: String? = null,
+ @SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
+ @SerialName("rating_5based") @Serializable(with = LenientNullableStringSerializer::class) val rating5based: String? = null,
+ @SerialName("tmdb") @Serializable(with = LenientNullableStringSerializer::class) val tmdb: String? = null,
+ @SerialName("trailer") @Serializable(with = LenientNullableStringSerializer::class) val trailer: String? = null,
+ @SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
+ @SerialName("is_adult") @Serializable(with = LenientNullableBooleanSerializer::class) val isAdult: Boolean? = null
)
@Serializable
data class XtreamSeriesItem(
@SerialName("series_id") @Serializable(with = LenientLongSerializer::class) val seriesId: Long = 0,
- @SerialName("name") val name: String = "",
- @SerialName("cover") val cover: String? = null,
- @SerialName("plot") val plot: String? = null,
- @SerialName("cast") val cast: String? = null,
- @SerialName("director") val director: String? = null,
- @SerialName("genre") val genre: String? = null,
- @SerialName("releaseDate") val releaseDate: String? = null,
- @SerialName("rating") val rating: String? = null,
- @SerialName("rating_5based") val rating5based: String? = null,
- @SerialName("backdrop_path") val backdropPath: List<String>? = null,
- @SerialName("youtube_trailer") val youtubeTrailer: String? = null,
- @SerialName("episode_run_time") val episodeRunTime: String? = null,
- @SerialName("category_id") val categoryId: String? = null,
- @SerialName("last_modified") val lastModified: String? = null
+ @SerialName("name") @Serializable(with = LenientStringSerializer::class) val name: String = "",
+ @SerialName("cover") @Serializable(with = LenientNullableStringSerializer::class) val cover: String? = null,
+ @SerialName("cover_big") @Serializable(with = LenientNullableStringSerializer::class) val coverBig: String? = null,
+ @SerialName("plot") @Serializable(with = LenientNullableStringSerializer::class) val plot: String? = null,
+ @SerialName("cast") @Serializable(with = LenientNullableStringSerializer::class) val cast: String? = null,
+ @SerialName("director") @Serializable(with = LenientNullableStringSerializer::class) val director: String? = null,
+ @SerialName("genre") @Serializable(with = LenientNullableStringSerializer::class) val genre: String? = null,
+ @SerialName("releaseDate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDate: String? = null,
+ @SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
+ @SerialName("rating_5based") @Serializable(with = LenientNullableStringSerializer::class) val rating5based: String? = null,
+ @SerialName("backdrop_path") @Serializable(with = LenientNullableStringListSerializer::class) val backdropPath: List<String>? = null,
+ @SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
+ @SerialName("trailer") @Serializable(with = LenientNullableStringSerializer::class) val trailer: String? = null,
+ @SerialName("tmdb") @Serializable(with = LenientNullableStringSerializer::class) val tmdb: String? = null,
+ @SerialName("episode_run_time") @Serializable(with = LenientNullableStringSerializer::class) val episodeRunTime: String? = null,
+ @SerialName("category_id") @Serializable(with = LenientNullableStringSerializer::class) val categoryId: String? = null,
+ @SerialName("last_modified") @Serializable(with = LenientNullableStringSerializer::class) val lastModified: String? = null,
+ @SerialName("is_adult") @Serializable(with = LenientNullableBooleanSerializer::class) val isAdult: Boolean? = null
)
@Serializable
@@ -94,34 +104,34 @@ data class XtreamSeriesInfoResponse(
@Serializable
data class XtreamSeason(
@SerialName("season_number") @Serializable(with = LenientIntSerializer::class) val seasonNumber: Int = 0,
- @SerialName("name") val name: String = "",
- @SerialName("cover") val cover: String? = null,
- @SerialName("air_date") val airDate: String? = null,
+ @SerialName("name") @Serializable(with = LenientStringSerializer::class) val name: String = "",
+ @SerialName("cover") @Serializable(with = LenientNullableStringSerializer::class) val cover: String? = null,
+ @SerialName("air_date") @Serializable(with = LenientNullableStringSerializer::class) val airDate: String? = null,
@SerialName("episode_count") @Serializable(with = LenientIntSerializer::class) val episodeCount: Int = 0
)
@Serializable
data class XtreamEpisode(
- @SerialName("id") val id: String = "",
+ @SerialName("id") @Serializable(with = LenientStringSerializer::class) val id: String = "",
@SerialName("episode_num") @Serializable(with = LenientIntSerializer::class) val episodeNum: Int = 0,
- @SerialName("title") val title: String = "",
- @SerialName("container_extension") val containerExtension: String? = null,
- @SerialName("custom_sid") val customSid: String? = null,
- @SerialName("added") val added: String? = null,
+ @SerialName("title") @Serializable(with = LenientStringSerializer::class) val title: String = "",
+ @SerialName("container_extension") @Serializable(with = LenientNullableStringSerializer::class) val containerExtension: String? = null,
+ @SerialName("custom_sid") @Serializable(with = LenientNullableStringSerializer::class) val customSid: String? = null,
+ @SerialName("added") @Serializable(with = LenientNullableStringSerializer::class) val added: String? = null,
@SerialName("season") @Serializable(with = LenientIntSerializer::class) val season: Int = 0,
- @SerialName("direct_source") val directSource: String? = null,
+ @SerialName("direct_source") @Serializable(with = LenientNullableStringSerializer::class) val directSource: String? = null,
@SerialName("info") val info: XtreamEpisodeInfo? = null
)
@Serializable
data class XtreamEpisodeInfo(
- @SerialName("movie_image") val movieImage: String? = null,
- @SerialName("plot") val plot: String? = null,
- @SerialName("releasedate") val releaseDate: String? = null,
- @SerialName("rating") val rating: String? = null,
+ @SerialName("movie_image") @Serializable(with = LenientNullableStringSerializer::class) val movieImage: String? = null,
+ @SerialName("plot") @Serializable(with = LenientNullableStringSerializer::class) val plot: String? = null,
+ @SerialName("releasedate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDate: String? = null,
+ @SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
@SerialName("duration_secs") @Serializable(with = LenientIntSerializer::class) val durationSecs: Int = 0,
- @SerialName("duration") val duration: String? = null,
- @SerialName("name") val name: String? = null,
+ @SerialName("duration") @Serializable(with = LenientNullableStringSerializer::class) val duration: String? = null,
+ @SerialName("name") @Serializable(with = LenientNullableStringSerializer::class) val name: String? = null,
@SerialName("bitrate") @Serializable(with = LenientIntSerializer::class) val bitrate: Int = 0
)
@@ -133,30 +143,34 @@ data class XtreamVodInfoResponse(
@Serializable
data class XtreamVodInfo(
- @SerialName("movie_image") val movieImage: String? = null,
+ @SerialName("movie_image") @Serializable(with = LenientNullableStringSerializer::class) val movieImage: String? = null,
@SerialName("tmdb_id") @Serializable(with = LenientNullableLongSerializer::class) val tmdbId: Long? = null,
- @SerialName("plot") val plot: String? = null,
- @SerialName("cast") val cast: String? = null,
- @SerialName("director") val director: String? = null,
- @SerialName("genre") val genre: String? = null,
- @SerialName("releasedate") val releaseDate: String? = null,
- @SerialName("rating") val rating: String? = null,
- @SerialName("youtube_trailer") val youtubeTrailer: String? = null,
+ @SerialName("plot") @Serializable(with = LenientNullableStringSerializer::class) val plot: String? = null,
+ @SerialName("cast") @Serializable(with = LenientNullableStringSerializer::class) val cast: String? = null,
+ @SerialName("director") @Serializable(with = LenientNullableStringSerializer::class) val director: String? = null,
+ @SerialName("genre") @Serializable(with = LenientNullableStringSerializer::class) val genre: String? = null,
+ @SerialName("releasedate") @Serializable(with = LenientNullableStringSerializer::class) val releaseDate: String? = null,
+ @SerialName("rating") @Serializable(with = LenientNullableStringSerializer::class) val rating: String? = null,
+ @SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
@SerialName("duration_secs") @Serializable(with = LenientIntSerializer::class) val durationSecs: Int = 0,
- @SerialName("duration") val duration: String? = null,
- @SerialName("backdrop_path") val backdropPath: List<String>? = null,
+ @SerialName("duration") @Serializable(with = LenientNullableStringSerializer::class) val duration: String? = null,
+ @SerialName("backdrop_path") @Serializable(with = LenientNullableStringListSerializer::class) val backdropPath: List<String>? = null,
@SerialName("bitrate") @Serializable(with = LenientIntSerializer::class) val bitrate: Int = 0
)
@Serializable
data class XtreamVodMovieData(
@SerialName("stream_id") @Serializable(with = LenientLongSerializer::class) val streamId: Long = 0,
- @SerialName("name") val name: String = "",
- @SerialName("added") val added: String? = null,
- @SerialName("category_id") val categoryId: String? = null,
- @SerialName("container_extension") val containerExtension: String? = null,
- @SerialName("custom_sid") val customSid: String? = null,
- @SerialName("direct_source") val directSource: String? = null
+ @SerialName("name") @Serializable(with = LenientStringSerializer::class) val name: String = "",
+ @SerialName("added") @Serializable(with = LenientNullableStringSerializer::class) val added: String? = null,
+ @SerialName("category_id") @Serializable(with = LenientNullableStringSerializer::class) val categoryId: String? = null,
+ @SerialName("container_extension") @Serializable(with = LenientNullableStringSerializer::class) val containerExtension: String? = null,
+ @SerialName("custom_sid") @Serializable(with = LenientNullableStringSerializer::class) val customSid: String? = null,
+ @SerialName("direct_source") @Serializable(with = LenientNullableStringSerializer::class) val directSource: String? = null,
+ @SerialName("tmdb") @Serializable(with = LenientNullableStringSerializer::class) val tmdb: String? = null,
+ @SerialName("trailer") @Serializable(with = LenientNullableStringSerializer::class) val trailer: String? = null,
+ @SerialName("youtube_trailer") @Serializable(with = LenientNullableStringSerializer::class) val youtubeTrailer: String? = null,
+ @SerialName("is_adult") @Serializable(with = LenientNullableBooleanSerializer::class) val isAdult: Boolean? = null
)
@Serializable
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
index 61447bc7..3213f757 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/OkHttpXtreamApiService.kt
@@ -7,6 +7,7 @@ import com.streamvault.data.remote.dto.XtreamSeriesInfoResponse
import com.streamvault.data.remote.dto.XtreamSeriesItem
import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.data.remote.dto.XtreamVodInfoResponse
+import com.streamvault.data.remote.NetworkTimeoutConfig
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -14,11 +15,32 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.SerializationException
import okhttp3.OkHttpClient
import okhttp3.Request
+import java.net.URI
+import java.util.concurrent.TimeUnit.SECONDS
class OkHttpXtreamApiService(
private val client: OkHttpClient,
private val json: Json
) : XtreamApiService {
+ private enum class RequestProfile {
+ STANDARD,
+ HEAVY_CATALOG
+ }
+
+ private data class EndpointDescriptor(
+ val action: String?,
+ val host: String?,
+ val path: String?,
+ val hint: String
+ )
+
+ private val heavyCatalogClient: OkHttpClient by lazy {
+ client.newBuilder()
+ .readTimeout(NetworkTimeoutConfig.XTREAM_HEAVY_READ_TIMEOUT_SECONDS, SECONDS)
+ .writeTimeout(NetworkTimeoutConfig.XTREAM_HEAVY_WRITE_TIMEOUT_SECONDS, SECONDS)
+ .callTimeout(NetworkTimeoutConfig.XTREAM_HEAVY_CALL_TIMEOUT_SECONDS, SECONDS)
+ .build()
+ }
override suspend fun authenticate(endpoint: String): XtreamAuthResponse = get(endpoint)
@@ -28,13 +50,13 @@ class OkHttpXtreamApiService(
override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
- override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = get(endpoint)
+ override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = get(endpoint, RequestProfile.HEAVY_CATALOG)
override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = get(endpoint)
override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = get(endpoint)
- override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = get(endpoint)
+ override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = get(endpoint, RequestProfile.HEAVY_CATALOG)
override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = get(endpoint)
@@ -42,13 +64,18 @@ class OkHttpXtreamApiService(
override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = get(endpoint)
- private suspend inline fun <reified T> get(endpoint: String): T = withContext(Dispatchers.IO) {
+ private suspend inline fun <reified T> get(
+ endpoint: String,
+ profile: RequestProfile = RequestProfile.STANDARD
+ ): T = withContext(Dispatchers.IO) {
+ val descriptor = describeEndpoint(endpoint)
val request = Request.Builder()
.url(endpoint)
.get()
.build()
try {
- client.newCall(request).execute().use { response ->
+ val call = clientFor(profile).newCall(request)
+ call.execute().use { response ->
if (!response.isSuccessful) {
val message = "HTTP ${response.code}"
when (response.code) {
@@ -58,17 +85,88 @@ class OkHttpXtreamApiService(
}
}
val body = response.body?.string()?.takeIf { it.isNotBlank() }
- ?: throw XtreamParsingException("Empty response body")
+ ?: throw XtreamParsingException("Empty response body from ${descriptor.hint}")
+ inspectResponseShape(
+ body = body,
+ contentType = response.header("Content-Type"),
+ descriptor = descriptor
+ )?.let { throw it }
try {
json.decodeFromString<T>(body)
} catch (e: SerializationException) {
- throw XtreamParsingException("Server returned malformed data", e)
+ val preview = sanitizedPreview(body)
+ throw XtreamParsingException(
+ "Malformed JSON from ${descriptor.hint}${if (preview != null) " (preview=$preview)" else ""}",
+ e
+ )
}
}
} catch (e: XtreamApiException) {
throw e
} catch (e: IOException) {
- throw XtreamNetworkException(e.message ?: "Network request failed", e)
+ throw XtreamNetworkException(XtreamUrlFactory.sanitizeLogMessage(e.message ?: "Network request failed"), e)
}
}
-}
\ No newline at end of file
+
+ private fun clientFor(profile: RequestProfile): OkHttpClient = when (profile) {
+ RequestProfile.STANDARD -> client
+ RequestProfile.HEAVY_CATALOG -> heavyCatalogClient
+ }
+
+ private fun describeEndpoint(endpoint: String): EndpointDescriptor {
+ val uri = runCatching { URI(endpoint) }.getOrNull()
+ val action = uri?.rawQuery
+ ?.split('&')
+ ?.firstOrNull { it.startsWith("action=", ignoreCase = true) }
+ ?.substringAfter('=')
+ ?.takeIf { it.isNotBlank() }
+ val host = uri?.host
+ val path = uri?.path?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
+ val hint = buildString {
+ append(host ?: "<unknown-host>")
+ if (!path.isNullOrBlank()) append("/").append(path)
+ if (!action.isNullOrBlank()) append("?action=").append(action)
+ }
+ return EndpointDescriptor(
+ action = action,
+ host = host,
+ path = path,
+ hint = XtreamUrlFactory.sanitizeLogMessage(hint)
+ )
+ }
+
+ private fun inspectResponseShape(
+ body: String,
+ contentType: String?,
+ descriptor: EndpointDescriptor
+ ): XtreamParsingException? {
+ val trimmed = body.trimStart()
+ val normalizedContentType = contentType?.lowercase().orEmpty()
+ val preview = sanitizedPreview(body)
+ val previewSuffix = if (preview != null) " (preview=$preview)" else ""
+ return when {
+ trimmed.isBlank() ->
+ XtreamParsingException("Blank response body from ${descriptor.hint}")
+ normalizedContentType.contains("html") ||
+ trimmed.startsWith("<!doctype html", ignoreCase = true) ||
+ trimmed.startsWith("<html", ignoreCase = true) ||
+ trimmed.contains("<body", ignoreCase = true) ||
+ trimmed.contains("</html>", ignoreCase = true) ->
+ XtreamParsingException("HTML error page returned from ${descriptor.hint}$previewSuffix")
+ trimmed.startsWith("<") ->
+ XtreamParsingException("Markup/non-JSON response returned from ${descriptor.hint}$previewSuffix")
+ !trimmed.startsWith("{") && !trimmed.startsWith("[") ->
+ XtreamParsingException("Non-JSON text response returned from ${descriptor.hint}$previewSuffix")
+ else -> null
+ }
+ }
+
+ private fun sanitizedPreview(body: String): String? {
+ return body
+ .replace(Regex("\\s+"), " ")
+ .trim()
+ .takeIf { it.isNotEmpty() }
+ ?.take(140)
+ ?.let(XtreamUrlFactory::sanitizeLogMessage)
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt
index 509f2fe2..e4f0f2c3 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamErrorFormatter.kt
@@ -6,14 +6,15 @@ import javax.net.ssl.SSLPeerUnverifiedException
internal object XtreamErrorFormatter {
fun message(prefix: String, throwable: Throwable): String {
- return when {
+ val formatted = when {
throwable is CredentialDecryptionException -> "$prefix: ${throwable.message}"
throwable.isCertificateTrustFailure() -> "$prefix: Server TLS certificate is not trusted by this device. Verify the HTTPS URL or ask the provider for a valid certificate."
throwable is XtreamAuthenticationException -> "$prefix: Authentication failed. Please check your username, password, and server URL."
- throwable is XtreamParsingException -> "$prefix: Server returned malformed or unsupported data."
+ throwable is XtreamParsingException -> "$prefix: ${throwable.message ?: "Server returned malformed or unsupported data."}"
throwable is XtreamRequestException -> "$prefix: Request failed with HTTP ${throwable.statusCode}."
else -> "$prefix: ${throwable.message ?: "Unexpected network error"}"
}
+ return XtreamUrlFactory.sanitizeLogMessage(formatted)
}
private fun Throwable.isCertificateTrustFailure(): Boolean {
@@ -25,4 +26,4 @@ internal object XtreamErrorFormatter {
current.message?.contains("hostname", ignoreCase = true) == true
}
}
-}
\ No newline at end of file
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
index 29f2e4ba..b67868bb 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamProvider.kt
@@ -28,10 +28,20 @@ class XtreamProvider(
private val api: XtreamApiService,
private val serverUrl: String,
private val username: String,
- private val password: String
+ private val password: String,
+ private val allowedOutputFormats: List<String> = emptyList()
) : IptvProvider {
+ companion object {
+ private const val TAG = "XtreamProvider"
+ }
+
+ private data class ResolvedXtreamCategory(
+ val id: Long?,
+ val name: String?
+ )
private var serverInfo: XtreamServerInfo? = null
+ private var liveOutputFormats: List<String> = normalizeAllowedOutputFormats(allowedOutputFormats)
private val adultCategoryCache = mutableMapOf<ContentType, Set<Long>>()
private val adultCategoryCacheMutex = Mutex()
@@ -40,6 +50,8 @@ class XtreamProvider(
XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password)
)
serverInfo = response.serverInfo
+ liveOutputFormats = normalizeAllowedOutputFormats(response.userInfo.allowedOutputFormats)
+ .ifEmpty { liveOutputFormats }
if (response.userInfo.auth != 1) {
Result.error("Authentication failed: ${response.userInfo.message}")
@@ -60,12 +72,13 @@ class XtreamProvider(
expirationDate = expDate,
apiVersion = response.serverInfo.apiVersion?.takeIf { it.isNotBlank() }
?: response.serverInfo.version?.takeIf { it.isNotBlank() },
+ allowedOutputFormats = liveOutputFormats,
status = when (response.userInfo.status) {
"Active" -> ProviderStatus.ACTIVE
"Expired" -> ProviderStatus.EXPIRED
"Disabled" -> ProviderStatus.DISABLED
else -> {
- Log.w("XtreamProvider", "Unknown account status: ${response.userInfo.status}")
+ Log.w(TAG, "Unknown account status: ${response.userInfo.status}")
ProviderStatus.UNKNOWN
}
}
@@ -99,7 +112,19 @@ class XtreamProvider(
extraQueryParams = mapOf("category_id" to categoryId?.toString())
)
)
- Result.success(streams.map { it.toChannel(adultCategoryIds) })
+ Result.success(
+ streams.mapNotNull { stream ->
+ runCatching { stream.toChannel(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed live item ${stream.streamId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ )
} catch (e: Exception) {
Result.error(XtreamErrorFormatter.message("Failed to load live streams", e), e)
}
@@ -127,7 +152,19 @@ class XtreamProvider(
extraQueryParams = mapOf("category_id" to categoryId?.toString())
)
)
- Result.success(streams.map { it.toMovie(adultCategoryIds) })
+ Result.success(
+ streams.mapNotNull { stream ->
+ runCatching { stream.toMovie(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed VOD item ${stream.streamId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ )
} catch (e: Exception) {
Result.error(XtreamErrorFormatter.message("Failed to load VOD", e), e)
}
@@ -147,15 +184,22 @@ class XtreamProvider(
if (movieData == null) {
Result.error("Movie not found")
+ } else if (movieData.streamId <= 0) {
+ Result.error("Movie stream is invalid")
} else {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
+ val category = resolveXtreamCategory(ContentType.MOVIE, movieData.categoryId, null)
+ val normalizedContainerExtension = normalizeContainerExtension(movieData.containerExtension)
+ val sanitizedDirectSource = sanitizeAssetValue(movieData.directSource)
Result.success(
Movie(
id = movieData.streamId,
- name = decodeXtreamText(movieData.name),
- posterUrl = info?.movieImage,
- backdropUrl = info?.backdropPath?.firstOrNull(),
- categoryId = movieData.categoryId?.toLongOrNull(),
- containerExtension = movieData.containerExtension,
+ name = decodeXtreamNullableText(movieData.name)?.ifBlank { null } ?: "Movie ${movieData.streamId}",
+ posterUrl = sanitizeAssetValue(info?.movieImage),
+ backdropUrl = firstUsableAsset(info?.backdropPath),
+ categoryId = category.id,
+ categoryName = category.name,
+ containerExtension = normalizedContainerExtension,
plot = decodeXtreamNullableText(info?.plot),
cast = decodeXtreamNullableText(info?.cast),
director = decodeXtreamNullableText(info?.director),
@@ -164,21 +208,22 @@ class XtreamProvider(
duration = info?.duration,
durationSeconds = info?.durationSecs ?: 0,
rating = info?.rating?.toFloatOrNull() ?: 0f,
- tmdbId = info?.tmdbId,
- youtubeTrailer = info?.youtubeTrailer,
+ tmdbId = info?.tmdbId ?: movieData.tmdb?.trim()?.toLongOrNull(),
+ youtubeTrailer = info?.youtubeTrailer ?: movieData.youtubeTrailer ?: movieData.trailer,
providerId = providerId,
streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
providerId = providerId,
kind = XtreamStreamKind.MOVIE,
streamId = movieData.streamId,
- containerExtension = movieData.containerExtension,
- directSource = movieData.directSource
+ containerExtension = normalizedContainerExtension,
+ directSource = sanitizedDirectSource
),
streamId = movieData.streamId,
isAdult = resolveAdultFlag(
- categoryId = movieData.categoryId?.toLongOrNull(),
- categoryName = null,
- adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
+ explicitAdult = movieData.isAdult,
+ categoryId = category.id,
+ categoryName = category.name,
+ adultCategoryIds = adultCategoryIds
)
)
)
@@ -210,7 +255,19 @@ class XtreamProvider(
extraQueryParams = mapOf("category_id" to categoryId?.toString())
)
)
- Result.success(items.map { it.toDomain(adultCategoryIds) })
+ Result.success(
+ items.mapNotNull { item ->
+ runCatching { item.toDomain(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed series item ${item.seriesId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ )
} catch (e: Exception) {
Result.error(XtreamErrorFormatter.message("Failed to load series", e), e)
}
@@ -231,53 +288,59 @@ class XtreamProvider(
Result.error("Series not found")
} else {
val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
+ val baseSeries = info.toDomain(adultCategoryIds)
+ ?: return Result.error("Series payload is invalid")
val isAdult = resolveAdultFlag(
+ explicitAdult = info.isAdult,
categoryId = info.categoryId?.toLongOrNull(),
categoryName = null,
adultCategoryIds = adultCategoryIds
)
val seasons = response.episodes.map { (seasonNum, episodes) ->
+ val mappedEpisodes = episodes.mapNotNull { ep ->
+ val episodeId = ep.id.toLongOrNull()?.takeIf { it > 0 } ?: return@mapNotNull null
+ val normalizedExtension = normalizeContainerExtension(ep.containerExtension)
+ Episode(
+ id = episodeId,
+ title = decodeXtreamText(
+ ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name) ?: "Episode ${ep.episodeNum}" }
+ ),
+ episodeNumber = ep.episodeNum,
+ seasonNumber = ep.season,
+ containerExtension = normalizedExtension,
+ coverUrl = sanitizeAssetValue(ep.info?.movieImage),
+ plot = decodeXtreamNullableText(ep.info?.plot),
+ duration = ep.info?.duration,
+ durationSeconds = ep.info?.durationSecs ?: 0,
+ rating = ep.info?.rating?.toFloatOrNull() ?: 0f,
+ releaseDate = ep.info?.releaseDate,
+ seriesId = seriesId,
+ providerId = providerId,
+ streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.SERIES,
+ streamId = episodeId,
+ containerExtension = normalizedExtension,
+ directSource = sanitizeAssetValue(ep.directSource)
+ ),
+ isAdult = isAdult,
+ isUserProtected = false,
+ episodeId = episodeId
+ )
+ }
Season(
seasonNumber = seasonNum.toIntOrNull() ?: 0,
name = "Season $seasonNum",
coverUrl = response.seasons.find {
it.seasonNumber == (seasonNum.toIntOrNull() ?: 0)
}?.cover,
- episodes = episodes.map { ep ->
- Episode(
- id = ep.id.toLongOrNull() ?: 0,
- title = decodeXtreamText(
- ep.title.ifBlank { decodeXtreamNullableText(ep.info?.name) ?: "Episode ${ep.episodeNum}" }
- ),
- episodeNumber = ep.episodeNum,
- seasonNumber = ep.season,
- containerExtension = ep.containerExtension,
- coverUrl = ep.info?.movieImage,
- plot = decodeXtreamNullableText(ep.info?.plot),
- duration = ep.info?.duration,
- durationSeconds = ep.info?.durationSecs ?: 0,
- rating = ep.info?.rating?.toFloatOrNull() ?: 0f,
- releaseDate = ep.info?.releaseDate,
- seriesId = seriesId,
- providerId = providerId,
- streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
- providerId = providerId,
- kind = XtreamStreamKind.SERIES,
- streamId = ep.id.toLongOrNull() ?: 0,
- containerExtension = ep.containerExtension,
- directSource = ep.directSource
- ),
- isAdult = isAdult,
- isUserProtected = false,
- episodeId = ep.id.toLongOrNull() ?: 0
- )
- },
- episodeCount = episodes.size
+ episodes = mappedEpisodes,
+ episodeCount = mappedEpisodes.size
)
}.sortedBy { it.seasonNumber }
Result.success(
- info.toDomain(adultCategoryIds).copy(
+ baseSeries.copy(
seasons = seasons,
providerId = providerId,
isAdult = isAdult
@@ -334,7 +397,7 @@ class XtreamProvider(
password = password,
kind = XtreamStreamKind.LIVE,
streamId = streamId,
- containerExtension = containerExtension
+ containerExtension = preferredLiveContainerExtension(containerExtension)
)
}
@@ -361,40 +424,106 @@ class XtreamProvider(
}
override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? {
+ return buildCatchUpUrls(streamId, start, end).firstOrNull()
+ }
+
+ override suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> {
val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd:HH-mm", java.util.Locale.ROOT)
dateFormat.timeZone = java.util.TimeZone.getTimeZone("UTC") // Xtream servers typically use UTC for EPG timeshifts
val formattedStart = dateFormat.format(java.util.Date(start * 1000L))
- val durationMinutes = (end - start) / 60
- return XtreamUrlFactory.buildCatchUpUrl(
+ val durationMinutes = ((end - start) / 60).coerceAtLeast(1L)
+ return XtreamUrlFactory.buildCatchUpUrls(
serverUrl = serverUrl,
username = username,
password = password,
durationMinutes = durationMinutes,
formattedStart = formattedStart,
- streamId = streamId
+ streamId = streamId,
+ containerExtensions = candidateCatchUpExtensions()
)
}
+ suspend fun mapCategories(type: ContentType, categories: List<XtreamCategory>): List<Category> {
+ if (type != ContentType.SERIES_EPISODE) {
+ cacheAdultCategoryIds(type, categories)
+ }
+ return categories.map { it.toDomain(type) }
+ }
+
+ suspend fun mapVodStreamsResponse(streams: List<XtreamStream>): List<Movie> {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.MOVIE)
+ return streams.mapNotNull { stream ->
+ runCatching { stream.toMovie(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed VOD item ${stream.streamId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ }
+
+ suspend fun mapLiveStreamsResponse(streams: List<XtreamStream>): List<Channel> {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.LIVE)
+ return streams.mapNotNull { stream ->
+ runCatching { stream.toChannel(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed live item ${stream.streamId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ }
+
+ suspend fun mapSeriesListResponse(items: List<XtreamSeriesItem>): List<Series> {
+ val adultCategoryIds = loadAdultCategoryIds(ContentType.SERIES)
+ return items.mapNotNull { item ->
+ runCatching { item.toDomain(adultCategoryIds) }
+ .onFailure {
+ Log.w(
+ TAG,
+ "Skipping malformed series item ${item.seriesId}: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "mapping failed")
+ )
+ }
+ .getOrNull()
+ }
+ }
+
// ── Mappers ────────────────────────────────────────────────────
private suspend fun loadAdultCategoryIds(type: ContentType): Set<Long> {
adultCategoryCacheMutex.withLock {
adultCategoryCache[type]?.let { return it }
- val categories = when (type) {
- ContentType.LIVE -> api.getLiveCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
- )
- ContentType.MOVIE -> api.getVodCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
- )
- ContentType.SERIES -> api.getSeriesCategories(
- XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ val categories = runCatching {
+ when (type) {
+ ContentType.LIVE -> api.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_live_categories")
+ )
+ ContentType.MOVIE -> api.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories")
+ )
+ ContentType.SERIES -> api.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories")
+ )
+ ContentType.SERIES_EPISODE -> emptyList()
+ }
+ }.getOrElse {
+ Log.w(
+ TAG,
+ "Failed to prefetch $type categories for adult tagging: " +
+ XtreamUrlFactory.sanitizeLogMessage(it.message ?: "unknown error")
)
- ContentType.SERIES_EPISODE -> emptyList()
+ emptyList()
}
return categories
.filter { AdultContentClassifier.isAdultCategoryName(it.categoryName) }
- .mapNotNull { it.categoryId.toLongOrNull() }
+ .mapNotNull { resolveXtreamCategory(type, it.categoryId, it.categoryName).id }
.toSet()
.also { adultCategoryCache[type] = it }
}
@@ -403,7 +532,7 @@ class XtreamProvider(
private suspend fun cacheAdultCategoryIds(type: ContentType, categories: List<XtreamCategory>) {
val ids = categories
.filter { AdultContentClassifier.isAdultCategoryName(it.categoryName) }
- .mapNotNull { it.categoryId.toLongOrNull() }
+ .mapNotNull { resolveXtreamCategory(type, it.categoryId, it.categoryName).id }
.toSet()
adultCategoryCacheMutex.withLock {
adultCategoryCache[type] = ids
@@ -411,101 +540,221 @@ class XtreamProvider(
}
private fun resolveAdultFlag(
+ explicitAdult: Boolean?,
categoryId: Long?,
categoryName: String?,
adultCategoryIds: Set<Long>
): Boolean {
- return (categoryId != null && categoryId in adultCategoryIds) ||
+ return explicitAdult == true ||
+ (categoryId != null && categoryId in adultCategoryIds) ||
AdultContentClassifier.isAdultCategoryName(categoryName)
}
- private fun XtreamCategory.toDomain(type: ContentType) = Category(
- id = categoryId.toLongOrNull() ?: 0,
- name = categoryName,
- parentId = if (parentId > 0) parentId.toLong() else null,
- type = type,
- isAdult = AdultContentClassifier.isAdultCategoryName(categoryName)
- )
+ private fun normalizeAllowedOutputFormats(formats: List<String>): List<String> {
+ return formats
+ .mapNotNull { format ->
+ normalizeContainerExtension(format)
+ ?.takeIf(::isRecognizedLiveFormat)
+ }
+ .distinct()
+ }
+
+ private fun preferredLiveContainerExtension(containerExtension: String?): String? {
+ normalizeContainerExtension(containerExtension)?.let { return it }
+ return when {
+ "m3u8" in liveOutputFormats -> "m3u8"
+ "ts" in liveOutputFormats -> "ts"
+ else -> null
+ }
+ }
+
+ private fun candidateCatchUpExtensions(): List<String> {
+ return liveOutputFormats
+ .filter(::isRecognizedLiveFormat)
+ .ifEmpty { listOf("ts", "m3u8") }
+ .distinct()
+ }
+
+ private fun buildInternalLiveStreamUrl(
+ streamId: Long,
+ containerExtension: String?,
+ directSource: String?
+ ): String {
+ return XtreamUrlFactory.buildInternalStreamUrl(
+ providerId = providerId,
+ kind = XtreamStreamKind.LIVE,
+ streamId = streamId,
+ containerExtension = containerExtension,
+ directSource = directSource
+ )
+ }
+
+ private fun buildLiveQualityOptions(
+ streamId: Long,
+ primaryContainerExtension: String?,
+ directSource: String?
+ ): List<ChannelQualityOption> {
+ val extensions = buildList {
+ primaryContainerExtension?.let(::add)
+ if (directSource == null) {
+ liveOutputFormats
+ .filter(::isRecognizedLiveFormat)
+ .filter { it != primaryContainerExtension }
+ .forEach(::add)
+ }
+ }.distinct()
+
+ return extensions.map { extension ->
+ ChannelQualityOption(
+ label = liveFormatLabel(extension),
+ url = buildInternalLiveStreamUrl(
+ streamId = streamId,
+ containerExtension = extension,
+ directSource = if (extension == primaryContainerExtension) directSource else null
+ )
+ )
+ }
+ }
+
+ private fun liveFormatLabel(extension: String): String = when (extension.lowercase(Locale.ROOT)) {
+ "m3u8" -> "HLS"
+ "ts" -> "MPEG-TS"
+ else -> extension.uppercase(Locale.ROOT)
+ }
+
+ private fun isRecognizedLiveFormat(extension: String): Boolean =
+ extension == "m3u8" || extension == "ts"
- private fun XtreamStream.toChannel(adultCategoryIds: Set<Long>): Channel {
+ private fun normalizeContainerExtension(containerExtension: String?): String? {
+ return containerExtension
+ ?.trim()
+ ?.removePrefix(".")
+ ?.lowercase(Locale.ROOT)
+ ?.takeIf { it.isNotEmpty() }
+ }
+
+ private fun XtreamCategory.toDomain(type: ContentType): Category {
+ val category = resolveXtreamCategory(type, categoryId, categoryName)
+ return Category(
+ id = category.id ?: 0,
+ name = category.name ?: "Uncategorized",
+ parentId = if (parentId > 0) parentId.toLong() else null,
+ type = type,
+ isAdult = AdultContentClassifier.isAdultCategoryName(category.name)
+ )
+ }
+
+ private fun XtreamStream.toChannel(adultCategoryIds: Set<Long>): Channel? {
+ if (streamId <= 0) return null
+ val category = resolveXtreamCategory(ContentType.LIVE, categoryId, categoryName)
+ val primaryContainerExtension = preferredLiveContainerExtension(containerExtension)
+ val resolvedName = decodeXtreamNullableText(name)?.ifBlank { null } ?: "Channel $streamId"
+ val sanitizedLogoUrl = sanitizeAssetValue(streamIcon)
+ val sanitizedEpgChannelId = decodeXtreamNullableText(epgChannelId)
+ val sanitizedDirectSource = sanitizeAssetValue(directSource)
+ val streamUrl = buildInternalLiveStreamUrl(
+ streamId = streamId,
+ containerExtension = primaryContainerExtension,
+ directSource = sanitizedDirectSource
+ )
+ val qualityOptions = buildLiveQualityOptions(
+ streamId = streamId,
+ primaryContainerExtension = primaryContainerExtension,
+ directSource = sanitizedDirectSource
+ )
return Channel(
id = 0,
- name = decodeXtreamText(name),
- logoUrl = streamIcon,
- categoryId = categoryId?.toLongOrNull(),
- categoryName = decodeXtreamNullableText(categoryName),
- epgChannelId = epgChannelId,
+ name = resolvedName,
+ logoUrl = sanitizedLogoUrl,
+ categoryId = category.id,
+ categoryName = category.name,
+ epgChannelId = sanitizedEpgChannelId,
number = num,
catchUpSupported = tvArchive == 1,
catchUpDays = tvArchiveDuration ?: 0,
providerId = providerId,
+ streamUrl = streamUrl,
+ isAdult = resolveAdultFlag(
+ explicitAdult = isAdult,
+ categoryId = category.id,
+ categoryName = category.name,
+ adultCategoryIds = adultCategoryIds
+ ),
+ isUserProtected = false,
+ logicalGroupId = ChannelNormalizer.getLogicalGroupId(resolvedName, providerId),
+ qualityOptions = qualityOptions,
+ alternativeStreams = qualityOptions.mapNotNull { it.url }.filter { it != streamUrl },
+ streamId = streamId
+ )
+ }
+
+ private fun XtreamStream.toMovie(adultCategoryIds: Set<Long>): Movie? {
+ if (streamId <= 0) return null
+ val category = resolveXtreamCategory(ContentType.MOVIE, categoryId, categoryName)
+ val resolvedName = decodeXtreamNullableText(name)?.ifBlank { null } ?: "Movie $streamId"
+ val normalizedContainerExtension = normalizeContainerExtension(containerExtension)
+ val sanitizedDirectSource = sanitizeAssetValue(directSource)
+ return Movie(
+ id = 0,
+ name = resolvedName,
+ posterUrl = sanitizeAssetValue(coverBig) ?: sanitizeAssetValue(streamIcon),
+ categoryId = category.id,
+ categoryName = category.name,
+ containerExtension = normalizedContainerExtension,
+ rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
+ tmdbId = tmdb?.trim()?.toLongOrNull(),
+ youtubeTrailer = youtubeTrailer ?: trailer,
+ providerId = providerId,
streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
providerId = providerId,
- kind = XtreamStreamKind.LIVE,
+ kind = XtreamStreamKind.MOVIE,
streamId = streamId,
- containerExtension = containerExtension,
- directSource = directSource
+ containerExtension = normalizedContainerExtension,
+ directSource = sanitizedDirectSource
),
isAdult = resolveAdultFlag(
- categoryId = categoryId?.toLongOrNull(),
- categoryName = categoryName,
+ explicitAdult = isAdult,
+ categoryId = category.id,
+ categoryName = category.name,
adultCategoryIds = adultCategoryIds
),
isUserProtected = false,
- logicalGroupId = ChannelNormalizer.getLogicalGroupId(name, providerId),
streamId = streamId
)
}
- private fun XtreamStream.toMovie(adultCategoryIds: Set<Long>) = Movie(
- id = 0,
- name = decodeXtreamText(name),
- posterUrl = streamIcon,
- categoryId = categoryId?.toLongOrNull(),
- categoryName = decodeXtreamNullableText(categoryName),
- containerExtension = containerExtension,
- rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
- providerId = providerId,
- streamUrl = XtreamUrlFactory.buildInternalStreamUrl(
+ private fun XtreamSeriesItem.toDomain(adultCategoryIds: Set<Long>): Series? {
+ if (seriesId <= 0) return null
+ val category = resolveXtreamCategory(ContentType.SERIES, categoryId, null)
+ val resolvedName = decodeXtreamNullableText(name)?.ifBlank { null } ?: "Series $seriesId"
+ return Series(
+ id = 0,
+ name = resolvedName,
+ posterUrl = sanitizeAssetValue(coverBig) ?: sanitizeAssetValue(cover),
+ backdropUrl = firstUsableAsset(backdropPath),
+ categoryId = category.id,
+ categoryName = category.name,
+ plot = decodeXtreamNullableText(plot),
+ cast = decodeXtreamNullableText(cast),
+ director = decodeXtreamNullableText(director),
+ genre = decodeXtreamNullableText(genre),
+ releaseDate = releaseDate,
+ rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
+ tmdbId = tmdb?.trim()?.toLongOrNull(),
+ youtubeTrailer = youtubeTrailer ?: trailer,
+ episodeRunTime = episodeRunTime,
+ lastModified = lastModified?.toLongOrNull() ?: 0L,
providerId = providerId,
- kind = XtreamStreamKind.MOVIE,
- streamId = streamId,
- containerExtension = containerExtension,
- directSource = directSource
- ),
- isAdult = resolveAdultFlag(
- categoryId = categoryId?.toLongOrNull(),
- categoryName = categoryName,
- adultCategoryIds = adultCategoryIds
- ),
- isUserProtected = false,
- streamId = streamId
- )
-
- private fun XtreamSeriesItem.toDomain(adultCategoryIds: Set<Long>) = Series(
- id = 0,
- name = decodeXtreamText(name),
- posterUrl = cover,
- backdropUrl = backdropPath?.firstOrNull(),
- categoryId = categoryId?.toLongOrNull(),
- plot = decodeXtreamNullableText(plot),
- cast = decodeXtreamNullableText(cast),
- director = decodeXtreamNullableText(director),
- genre = decodeXtreamNullableText(genre),
- releaseDate = releaseDate,
- rating = rating5based?.toFloatOrNull() ?: rating?.toFloatOrNull() ?: 0f,
- youtubeTrailer = youtubeTrailer,
- episodeRunTime = episodeRunTime,
- lastModified = lastModified?.toLongOrNull() ?: 0L,
- providerId = providerId,
- isAdult = resolveAdultFlag(
- categoryId = categoryId?.toLongOrNull(),
- categoryName = null,
- adultCategoryIds = adultCategoryIds
- ),
- isUserProtected = false,
- seriesId = seriesId
- )
+ isAdult = resolveAdultFlag(
+ explicitAdult = isAdult,
+ categoryId = category.id,
+ categoryName = category.name,
+ adultCategoryIds = adultCategoryIds
+ ),
+ isUserProtected = false,
+ seriesId = seriesId
+ )
+ }
private fun XtreamEpgListing.toDomain(): Program {
// Xtream sometimes base64-encodes title and description
@@ -531,12 +780,58 @@ class XtreamProvider(
return value?.let(::decodeXtreamText)?.takeIf { it.isNotBlank() }
}
+ private fun sanitizeAssetValue(value: String?): String? {
+ return value
+ ?.trim()
+ ?.takeIf { it.isNotEmpty() && !it.equals("null", ignoreCase = true) }
+ }
+
+ private fun firstUsableAsset(values: List<String>?): String? {
+ return values.orEmpty().firstNotNullOfOrNull(::sanitizeAssetValue)
+ }
+
private fun decodeXtreamText(value: String): String = tryBase64Decode(value).trim()
+ private fun resolveXtreamCategory(
+ type: ContentType,
+ rawCategoryId: String?,
+ rawCategoryName: String?
+ ): ResolvedXtreamCategory {
+ val decodedName = decodeXtreamNullableText(rawCategoryName)
+ val parsedId = rawCategoryId?.trim()?.toLongOrNull()
+ if (parsedId != null) {
+ return ResolvedXtreamCategory(
+ id = parsedId,
+ name = decodedName ?: "Category $parsedId"
+ )
+ }
+
+ val fallbackSeed = decodedName ?: rawCategoryId?.trim()?.takeIf { it.isNotBlank() }
+ return if (fallbackSeed != null) {
+ ResolvedXtreamCategory(
+ id = syntheticCategoryId(type, fallbackSeed),
+ name = decodedName ?: "Category ${rawCategoryId?.trim()}"
+ )
+ } else {
+ ResolvedXtreamCategory(id = null, name = null)
+ }
+ }
+
+ private fun syntheticCategoryId(type: ContentType, seed: String): Long {
+ val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"
+ return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)
+ }
+
private fun tryBase64Decode(value: String): String = try {
- if (value.isBlank()) value
- else {
- val decoded = String(Base64.getDecoder().decode(value), Charsets.UTF_8)
+ val normalized = value.trim()
+ if (
+ normalized.isBlank() ||
+ normalized.length % 4 != 0 ||
+ !XTREAM_BASE64_REGEX.matches(normalized)
+ ) {
+ value
+ } else {
+ val decoded = String(Base64.getDecoder().decode(normalized), Charsets.UTF_8)
if (decoded.any { it.isLetterOrDigit() }) decoded else value
}
} catch (_: Exception) {
@@ -604,3 +899,5 @@ private val XTREAM_LOCAL_DATE_FORMATTERS: List<DateTimeFormatter> = listOf(
.toFormatter(Locale.ROOT)
.withResolverStyle(ResolverStyle.SMART)
)
+
+private val XTREAM_BASE64_REGEX = Regex("^[A-Za-z0-9+/]+={0,2}$")
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt
index a5fc7e94..7b256ac3 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt
@@ -32,6 +32,10 @@ object XtreamUrlFactory {
"""(https?://[^\s/]+(?:/[^\s/?#]+)*)/timeshift/[^/\s?]+/[^/\s?]+(/[^\s?#]*)?""",
RegexOption.IGNORE_CASE
)
+ private val timeshiftsPathRegex = Regex(
+ """(https?://[^\s/]+(?:/[^\s/?#]+)*)/timeshifts/[^/\s?]+/[^/\s?]+(/[^\s?#]*)?""",
+ RegexOption.IGNORE_CASE
+ )
fun buildPlayerApiUrl(
serverUrl: String,
@@ -88,14 +92,144 @@ object XtreamUrlFactory {
password: String,
durationMinutes: Long,
formattedStart: String,
- streamId: Long
+ streamId: Long,
+ containerExtension: String? = null
): String {
+ val ext = normalizeContainerExtension(containerExtension) ?: "ts"
return serverUrl.trimEnd('/') + "/timeshift/" +
encodePathSegment(username) + "/" +
encodePathSegment(password) + "/" +
encodePathSegment(durationMinutes.toString()) + "/" +
encodePathSegment(formattedStart) + "/" +
- encodePathSegment(streamId.toString()) + ".ts"
+ encodePathSegment(streamId.toString()) + "." + encodePathSegment(ext)
+ }
+
+ fun buildCatchUpShiftUrl(
+ serverUrl: String,
+ username: String,
+ password: String,
+ durationMinutes: Long,
+ formattedStart: String,
+ streamId: Long,
+ containerExtension: String? = null
+ ): String {
+ val ext = normalizeContainerExtension(containerExtension) ?: "ts"
+ return serverUrl.trimEnd('/') + "/timeshifts/" +
+ encodePathSegment(username) + "/" +
+ encodePathSegment(password) + "/" +
+ encodePathSegment(durationMinutes.toString()) + "/" +
+ encodePathSegment(streamId.toString()) + "/" +
+ encodePathSegment(formattedStart) + "." + encodePathSegment(ext)
+ }
+
+ fun buildCatchUpPhpUrl(
+ serverUrl: String,
+ username: String,
+ password: String,
+ durationMinutes: Long,
+ formattedStart: String,
+ streamId: Long,
+ containerExtension: String? = null,
+ includeExtension: Boolean = true,
+ path: String = "streaming/timeshift.php"
+ ): String {
+ val normalizedExtension = normalizeContainerExtension(containerExtension)
+ return buildUrl(
+ serverUrl = serverUrl,
+ path = path,
+ queryParams = buildList {
+ add("username" to username)
+ add("password" to password)
+ add("stream" to streamId.toString())
+ add("start" to formattedStart)
+ add("duration" to durationMinutes.toString())
+ if (includeExtension) {
+ normalizedExtension?.let { add("extension" to it) }
+ }
+ }
+ )
+ }
+
+ fun buildCatchUpUrls(
+ serverUrl: String,
+ username: String,
+ password: String,
+ durationMinutes: Long,
+ formattedStart: String,
+ streamId: Long,
+ containerExtensions: List<String>
+ ): List<String> {
+ val extensions = containerExtensions
+ .mapNotNull(::normalizeContainerExtension)
+ .ifEmpty { listOf("ts") }
+ .distinct()
+
+ return extensions.flatMap { extension ->
+ listOf(
+ buildCatchUpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension
+ ),
+ buildCatchUpShiftUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension
+ ),
+ buildCatchUpPhpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension,
+ includeExtension = true,
+ path = "streaming/timeshift.php"
+ ),
+ buildCatchUpPhpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension,
+ includeExtension = false,
+ path = "streaming/timeshift.php"
+ ),
+ buildCatchUpPhpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension,
+ includeExtension = true,
+ path = "timeshift.php"
+ ),
+ buildCatchUpPhpUrl(
+ serverUrl = serverUrl,
+ username = username,
+ password = password,
+ durationMinutes = durationMinutes,
+ formattedStart = formattedStart,
+ streamId = streamId,
+ containerExtension = extension,
+ includeExtension = false,
+ path = "timeshift.php"
+ )
+ )
+ }.distinct()
}
fun buildInternalStreamUrl(
@@ -170,6 +304,13 @@ object XtreamUrlFactory {
val suffix = match.groupValues[2]
"$prefix/timeshift/<redacted>/<redacted>$suffix"
}
+ .let { redacted ->
+ timeshiftsPathRegex.replace(redacted) { match ->
+ val prefix = match.groupValues[1]
+ val suffix = match.groupValues[2]
+ "$prefix/timeshifts/<redacted>/<redacted>$suffix"
+ }
+ }
}
private fun parseCredentialedStreamUrl(url: String, providerId: Long): XtreamStreamToken? {
@@ -246,4 +387,4 @@ object XtreamUrlFactory {
?.trim()
?.takeIf { it.isNotEmpty() }
}
-}
\ No newline at end of file
+}
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
index 853433e0..c4aad00e 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -219,11 +219,12 @@ class ChannelRepositoryImpl @Inject constructor(
return grouped.values.map { group ->
val primaryEntity = group.primary
- val alternativeStreams = group.alternatives
+ val primaryDomain = primaryEntity.toDomain()
+ val alternativeStreams = (group.alternatives
.sortedWith(channelPriorityComparator)
.map { it.streamUrl }
-
- val primaryDomain = primaryEntity.toDomain()
+ + primaryDomain.qualityOptions.mapNotNull { it.url }.filter { it != primaryEntity.streamUrl })
+ .distinct()
val mergedQualityOptions = buildMergedQualityOptions(
baseOptions = primaryDomain.qualityOptions,
primaryStreamUrl = primaryEntity.streamUrl,
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index 0698e907..f19d2f1b 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -4,9 +4,14 @@ import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.FavoriteDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.PlaybackHistoryDao
+import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.CategoryEntity
+import com.streamvault.data.mapper.toEntity
import com.streamvault.data.mapper.toDomain
+import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LibraryFilterType
@@ -14,21 +19,30 @@ import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.LibrarySortBy
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.PagedResult
+import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.util.isPlaybackComplete
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import com.streamvault.data.util.toFtsPrefixQuery
import com.streamvault.data.util.rankSearchResults
+import com.streamvault.data.security.CredentialCrypto
+import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import javax.inject.Singleton
@Singleton
@@ -36,6 +50,8 @@ import javax.inject.Singleton
class MovieRepositoryImpl @Inject constructor(
private val movieDao: MovieDao,
private val categoryDao: CategoryDao,
+ private val providerDao: ProviderDao,
+ private val xtreamApiService: XtreamApiService,
private val preferencesRepository: PreferencesRepository,
private val favoriteDao: FavoriteDao,
private val playbackHistoryDao: PlaybackHistoryDao,
@@ -45,6 +61,15 @@ class MovieRepositoryImpl @Inject constructor(
const val SEARCH_RESULT_LIMIT = 320
}
+ private data class CachedXtreamProvider(
+ val signature: String,
+ val provider: XtreamProvider
+ )
+
+ private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()
+ private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()
+ private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()
+
override fun getMovies(providerId: Long): Flow<List<Movie>> =
preferencesRepository.parentalControlLevel.flatMapLatest { level ->
if (level == 2) movieDao.getByProviderUnprotected(providerId)
@@ -52,39 +77,53 @@ class MovieRepositoryImpl @Inject constructor(
}.map { list -> list.map { it.toDomain() } }
override fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>> =
- preferencesRepository.parentalControlLevel.flatMapLatest { level ->
- if (level == 2) movieDao.getByCategoryUnprotected(providerId, categoryId)
- else movieDao.getByCategory(providerId, categoryId)
- }.map { list -> list.map { it.toDomain() } }
+ flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ preferencesRepository.parentalControlLevel.flatMapLatest { level ->
+ if (level == 2) movieDao.getByCategoryUnprotected(providerId, categoryId)
+ else movieDao.getByCategory(providerId, categoryId)
+ }.map { list -> list.map { it.toDomain() } }
+ )
+ }
override fun getMoviesByCategoryPage(
providerId: Long,
categoryId: Long,
limit: Int,
offset: Int
- ): Flow<List<Movie>> =
- combine(
- movieDao.getByCategoryPage(providerId, categoryId, limit, offset),
- preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list -> list.map { it.toDomain() } }
+ ): Flow<List<Movie>> = flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getByCategoryPage(providerId, categoryId, limit, offset),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+ )
+ }
override fun getMoviesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Movie>> =
- combine(
- movieDao.getByCategoryPreview(providerId, categoryId, limit),
- preferencesRepository.parentalControlLevel
- ) { entities: List<MovieEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list -> list.map { it.toDomain() } }
+ flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ combine(
+ movieDao.getByCategoryPreview(providerId, categoryId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+ )
+ }
override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Movie>>> =
combine(
@@ -187,40 +226,45 @@ class MovieRepositoryImpl @Inject constructor(
movieDao.getCount(providerId)
override fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>> {
- return combine(
- movieBrowseSource(query.providerId, query.categoryId),
- favoriteDao.getAllByType(ContentType.MOVIE.name),
- playbackHistoryDao.getByProvider(query.providerId)
- ) { movies, favorites, history ->
- val favoriteIds = favorites
- .asSequence()
- .filter { it.groupId == null }
- .map { it.contentId }
- .toSet()
- val inProgressIds = history
- .asSequence()
- .filter { it.contentType == ContentType.MOVIE }
- .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !isPlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
- .map { it.contentId }
- .toSet()
- val watchCounts = history
- .asSequence()
- .filter { it.contentType == ContentType.MOVIE }
- .associate { it.contentId to it.watchCount }
-
- val browsed = applyMovieBrowseQuery(
- movies = movies,
- query = query,
- favoriteIds = favoriteIds,
- inProgressIds = inProgressIds,
- watchCounts = watchCounts
- )
-
- PagedResult(
- items = browsed.drop(query.offset).take(query.limit),
- totalCount = browsed.size,
- offset = query.offset,
- limit = query.limit
+ return flow {
+ query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it) }
+ emitAll(
+ combine(
+ movieBrowseSource(query.providerId, query.categoryId),
+ favoriteDao.getAllByType(ContentType.MOVIE.name),
+ playbackHistoryDao.getByProvider(query.providerId)
+ ) { movies, favorites, history ->
+ val favoriteIds = favorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val inProgressIds = history
+ .asSequence()
+ .filter { it.contentType == ContentType.MOVIE }
+ .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !isPlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
+ .map { it.contentId }
+ .toSet()
+ val watchCounts = history
+ .asSequence()
+ .filter { it.contentType == ContentType.MOVIE }
+ .associate { it.contentId to it.watchCount }
+
+ val browsed = applyMovieBrowseQuery(
+ movies = movies,
+ query = query,
+ favoriteIds = favoriteIds,
+ inProgressIds = inProgressIds,
+ watchCounts = watchCounts
+ )
+
+ PagedResult(
+ items = browsed.drop(query.offset).take(query.limit),
+ totalCount = browsed.size,
+ offset = query.offset,
+ limit = query.limit
+ )
+ }
)
}
}
@@ -441,6 +485,42 @@ class MovieRepositoryImpl @Inject constructor(
.any { value -> value.lowercase().contains(normalizedQuery) }
}
+ private suspend fun ensureXtreamCategoryLoaded(providerId: Long, categoryId: Long) {
+ val key = "$providerId:$categoryId"
+ if (loadedXtreamCategories.contains(key)) return
+ if (movieDao.getCountByCategory(providerId, categoryId).first() > 0) {
+ loadedXtreamCategories.add(key)
+ return
+ }
+
+ val provider = providerDao.getById(providerId) ?: return
+ if (provider.type != ProviderType.XTREAM_CODES) return
+
+ val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
+ lock.withLock {
+ if (loadedXtreamCategories.contains(key)) return
+ if (movieDao.getCountByCategory(providerId, categoryId).first() > 0) {
+ loadedXtreamCategories.add(key)
+ return
+ }
+
+ runCatching {
+ val xtreamProvider = getOrCreateXtreamProvider(providerId, provider)
+ when (val result = xtreamProvider.getVodStreams(categoryId)) {
+ is Success -> {
+ movieDao.replaceCategory(
+ providerId,
+ categoryId,
+ result.data.map { movie -> movie.toEntity() }
+ )
+ loadedXtreamCategories.add(key)
+ }
+ else -> Unit
+ }
+ }
+ }
+ }
+
private fun movieIsInProgress(movie: Movie): Boolean {
if (movie.watchProgress <= 0L) return false
val totalDurationMs = movie.durationSeconds.takeIf { it > 0 }?.times(1000L) ?: 0L
@@ -453,4 +533,26 @@ class MovieRepositoryImpl @Inject constructor(
?.toLongOrNull()
?: movie.year?.toLongOrNull()
?: 0L
+
+ private fun getOrCreateXtreamProvider(providerId: Long, provider: ProviderEntity): XtreamProvider {
+ val signature = listOf(provider.serverUrl, provider.username, provider.password).joinToString("\u0000")
+ return xtreamProviderCache.compute(providerId) { _, cached ->
+ if (cached != null && cached.signature == signature) {
+ cached
+ } else {
+ val decryptedPassword = CredentialCrypto.decryptIfNeeded(provider.password)
+ CachedXtreamProvider(
+ signature = signature,
+ provider = XtreamProvider(
+ providerId = providerId,
+ api = xtreamApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = decryptedPassword,
+ allowedOutputFormats = provider.toDomain().allowedOutputFormats
+ )
+ )
+ }
+ }!!.provider
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index 336a89ba..f0fb94b2 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -12,8 +12,8 @@ import com.streamvault.data.util.ProviderInputSanitizer
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.*
import com.streamvault.domain.provider.IptvProvider
-import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.SyncMetadataRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
@@ -25,7 +25,8 @@ class ProviderRepositoryImpl @Inject constructor(
private val channelDao: ChannelDao,
private val programDao: ProgramDao,
private val xtreamApiService: XtreamApiService,
- private val syncManager: SyncManager
+ private val syncManager: SyncManager,
+ private val syncMetadataRepository: SyncMetadataRepository
) : ProviderRepository {
override fun getProviders(): Flow<List<Provider>> =
@@ -101,21 +102,20 @@ class ProviderRepositoryImpl @Inject constructor(
val provider = createXtreamProvider(0, normalizedServerUrl, normalizedUsername, effectivePassword)
return when (val authResult = provider.authenticate()) {
is Result.Success -> {
-
val providerData = if (existingProvider != null) {
onProgress?.invoke("Updating existing provider...")
- val updated = existingProvider.copy(
+ val updated = authResult.data.copy(
+ id = existingProvider.id,
name = normalizedName.ifBlank { existingProvider.name },
serverUrl = normalizedServerUrl,
username = normalizedUsername,
password = effectivePassword,
isActive = true,
- lastSyncedAt = 0
- )
- providerDao.update(
- updated.copy(password = CredentialCrypto.encryptIfNeeded(updated.password))
+ lastSyncedAt = 0,
+ createdAt = existingProvider.createdAt
)
- updated.toPublicDomain()
+ providerDao.update(updated.toSecureEntity())
+ updated.copy(password = "")
} else {
val newData = authResult.data.copy(name = normalizedName.ifBlank { authResult.data.name })
val newId = providerDao.insert(newData.toSecureEntity())
@@ -257,27 +257,114 @@ class ProviderRepositoryImpl @Inject constructor(
}
}
+ override suspend fun getProgramsForLiveStream(
+ providerId: Long,
+ streamId: Long,
+ epgChannelId: String?,
+ limit: Int
+ ): Result<List<Program>> {
+ if (providerId <= 0L || streamId <= 0L) {
+ return Result.error("Live stream context is unavailable.")
+ }
+
+ val providerEntity = providerDao.getById(providerId)
+ ?: return Result.error("Provider $providerId not found")
+ val provider = providerEntity.toPublicDomain()
+ if (provider.type != ProviderType.XTREAM_CODES) {
+ return Result.error("On-demand guide lookup is available only for Xtream providers.")
+ }
+
+ val providerPassword = try {
+ CredentialCrypto.decryptIfNeeded(providerEntity.password)
+ } catch (e: CredentialDecryptionException) {
+ return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e)
+ }
+
+ val xtreamProvider = createXtreamProvider(
+ providerId = providerId,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = providerPassword,
+ allowedOutputFormats = provider.allowedOutputFormats
+ )
+
+ val shortProgramsResult = xtreamProvider.getShortEpg(
+ channelId = streamId.toString(),
+ limit = limit.coerceAtLeast(1)
+ )
+ val shortPrograms = (shortProgramsResult as? Result.Success)?.data
+ ?.sortedBy { it.startTime }
+ .orEmpty()
+ if (shortPrograms.isNotEmpty()) {
+ val normalizedPrograms = normalizeXtreamPrograms(
+ providerId = providerId,
+ channelId = epgChannelId ?: streamId.toString(),
+ programs = shortPrograms
+ )
+ cacheProgramsForChannel(providerId, normalizedPrograms)
+ refreshCachedEpgMetadata(providerId)
+ return Result.success(normalizedPrograms)
+ }
+
+ return when (val fullProgramsResult = xtreamProvider.getEpg(streamId.toString())) {
+ is Result.Success -> {
+ val normalizedPrograms = normalizeXtreamPrograms(
+ providerId = providerId,
+ channelId = epgChannelId ?: streamId.toString(),
+ programs = fullProgramsResult.data.sortedBy { it.startTime }
+ )
+ cacheProgramsForChannel(providerId, normalizedPrograms)
+ refreshCachedEpgMetadata(providerId)
+ Result.success(normalizedPrograms)
+ }
+ is Result.Error -> {
+ val shortError = shortProgramsResult as? Result.Error
+ val combinedMessage = listOfNotNull(
+ shortError?.message?.takeIf { it.isNotBlank() },
+ fullProgramsResult.message.takeIf { it.isNotBlank() }
+ )
+ .distinct()
+ .joinToString(separator = " / ")
+ .ifBlank { "Failed to load on-demand guide" }
+ Result.error(combinedMessage, fullProgramsResult.exception ?: shortError?.exception)
+ }
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
+ }
+
override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? {
- val providerEntity = providerDao.getById(providerId) ?: return null
+ return buildCatchUpUrls(providerId, streamId, start, end).firstOrNull()
+ }
+
+ override suspend fun buildCatchUpUrls(providerId: Long, streamId: Long, start: Long, end: Long): List<String> {
+ val providerEntity = providerDao.getById(providerId) ?: return emptyList()
val provider = providerEntity.toPublicDomain()
val providerPassword = CredentialCrypto.decryptIfNeeded(providerEntity.password)
val channel = channelDao.getById(streamId)
val resolvedStreamId = channel?.streamId?.takeIf { it > 0 } ?: streamId
return if (provider.type == ProviderType.XTREAM_CODES) {
- createXtreamProvider(providerId, provider.serverUrl, provider.username, providerPassword)
- .buildCatchUpUrl(resolvedStreamId, start, end)
+ createXtreamProvider(
+ providerId = providerId,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = providerPassword,
+ allowedOutputFormats = provider.allowedOutputFormats
+ )
+ .buildCatchUpUrls(resolvedStreamId, start, end)
} else {
// M3U catch-up
- val source = channel?.catchUpSource ?: return null
+ val source = channel?.catchUpSource ?: return emptyList()
// Substitute common provider placeholder variants.
- source.replace("{start}", start.toString())
- .replace("{end}", end.toString())
- .replace("{duration}", (end - start).toString())
- .replace("{utc}", start.toString())
- .replace("{utcend}", end.toString())
- .replace("{lutc}", end.toString())
- .replace("{timestamp}", start.toString())
+ listOf(
+ source.replace("{start}", start.toString())
+ .replace("{end}", end.toString())
+ .replace("{duration}", (end - start).toString())
+ .replace("{utc}", start.toString())
+ .replace("{utcend}", end.toString())
+ .replace("{lutc}", end.toString())
+ .replace("{timestamp}", start.toString())
+ )
}
}
@@ -285,13 +372,15 @@ class ProviderRepositoryImpl @Inject constructor(
providerId: Long,
serverUrl: String,
username: String,
- password: String
+ password: String,
+ allowedOutputFormats: List<String> = emptyList()
): IptvProvider = XtreamProvider(
providerId = providerId,
api = xtreamApiService,
serverUrl = serverUrl,
username = username,
- password = password
+ password = password,
+ allowedOutputFormats = allowedOutputFormats
)
private fun ProviderEntity.toPublicDomain(): Provider {
@@ -315,4 +404,32 @@ class ProviderRepositoryImpl @Inject constructor(
)
providerDao.update(updated)
}
+
+ private fun normalizeXtreamPrograms(
+ providerId: Long,
+ channelId: String,
+ programs: List<Program>
+ ): List<Program> {
+ return programs.map { program ->
+ program.copy(
+ providerId = providerId,
+ channelId = channelId
+ )
+ }
+ }
+
+ private suspend fun cacheProgramsForChannel(providerId: Long, programs: List<Program>) {
+ val channelId = programs.firstOrNull()?.channelId ?: return
+ programDao.deleteForChannel(providerId, channelId)
+ programDao.insertAll(programs.map { it.toEntity().copy(providerId = providerId) })
+ }
+
+ private suspend fun refreshCachedEpgMetadata(providerId: Long) {
+ val now = System.currentTimeMillis()
+ val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId)).copy(
+ lastEpgSync = now,
+ epgCount = programDao.countByProvider(providerId)
+ )
+ syncMetadataRepository.updateMetadata(metadata)
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index b14d5d4c..6c65f4fb 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -8,11 +8,15 @@ import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.domain.model.*
+import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.repository.SeriesRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.emitAll
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import com.streamvault.data.util.toFtsPrefixQuery
@@ -21,6 +25,8 @@ import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.util.isPlaybackComplete
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import javax.inject.Singleton
@Singleton
@@ -46,6 +52,8 @@ class SeriesRepositoryImpl @Inject constructor(
)
private val xtreamProviderCache = ConcurrentHashMap<Long, CachedXtreamProvider>()
+ private val xtreamCategoryLoadLocks = ConcurrentHashMap<String, Mutex>()
+ private val loadedXtreamCategories = ConcurrentHashMap.newKeySet<String>()
override fun getSeries(providerId: Long): Flow<List<Series>> =
combine(
@@ -60,45 +68,59 @@ class SeriesRepositoryImpl @Inject constructor(
}.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
override fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>> =
- combine(
- seriesDao.getByCategory(providerId, categoryId),
- preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getByCategory(providerId, categoryId),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ )
+ }
override fun getSeriesByCategoryPage(
providerId: Long,
categoryId: Long,
limit: Int,
offset: Int
- ): Flow<List<Series>> =
- combine(
- seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),
- preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ ): Flow<List<Series>> = flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ )
+ }
override fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>> =
- combine(
- seriesDao.getByCategoryPreview(providerId, categoryId, limit),
- preferencesRepository.parentalControlLevel
- ) { entities: List<SeriesEntity>, level: Int ->
- if (level == 2) {
- entities.filter { !it.isUserProtected }
- } else {
- entities
- }
- }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ flow {
+ ensureXtreamCategoryLoaded(providerId, categoryId)
+ emitAll(
+ combine(
+ seriesDao.getByCategoryPreview(providerId, categoryId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ )
+ }
override fun getCategoryPreviewRows(providerId: Long, limitPerCategory: Int): Flow<Map<Long?, List<Series>>> =
combine(
@@ -174,41 +196,46 @@ class SeriesRepositoryImpl @Inject constructor(
seriesDao.getCount(providerId)
override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> {
- return combine(
- seriesBrowseSource(query.providerId, query.categoryId),
- favoriteDao.getAllByType(ContentType.SERIES.name),
- playbackHistoryDao.getByProvider(query.providerId)
- ) { series, favorites, history ->
- val favoriteIds = favorites
- .asSequence()
- .filter { it.groupId == null }
- .map { it.contentId }
- .toSet()
- val inProgressIds = history
- .asSequence()
- .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
- .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !isPlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
- .mapNotNull { it.seriesId ?: it.contentId }
- .toSet()
- val watchCounts = history
- .asSequence()
- .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
- .groupBy { it.seriesId ?: it.contentId }
- .mapValues { (_, entries) -> entries.maxOf { it.watchCount } }
-
- val browsed = applySeriesBrowseQuery(
- series = series,
- query = query,
- favoriteIds = favoriteIds,
- inProgressIds = inProgressIds,
- watchCounts = watchCounts
- )
+ return flow {
+ query.categoryId?.let { ensureXtreamCategoryLoaded(query.providerId, it) }
+ emitAll(
+ combine(
+ seriesBrowseSource(query.providerId, query.categoryId),
+ favoriteDao.getAllByType(ContentType.SERIES.name),
+ playbackHistoryDao.getByProvider(query.providerId)
+ ) { series, favorites, history ->
+ val favoriteIds = favorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val inProgressIds = history
+ .asSequence()
+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
+ .filter { it.resumePositionMs > 0L && (it.totalDurationMs <= 0L || !isPlaybackComplete(it.resumePositionMs, it.totalDurationMs)) }
+ .mapNotNull { it.seriesId ?: it.contentId }
+ .toSet()
+ val watchCounts = history
+ .asSequence()
+ .filter { it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE }
+ .groupBy { it.seriesId ?: it.contentId }
+ .mapValues { (_, entries) -> entries.maxOf { it.watchCount } }
+
+ val browsed = applySeriesBrowseQuery(
+ series = series,
+ query = query,
+ favoriteIds = favoriteIds,
+ inProgressIds = inProgressIds,
+ watchCounts = watchCounts
+ )
- PagedResult(
- items = browsed.drop(query.offset).take(query.limit),
- totalCount = browsed.size,
- offset = query.offset,
- limit = query.limit
+ PagedResult(
+ items = browsed.drop(query.offset).take(query.limit),
+ totalCount = browsed.size,
+ offset = query.offset,
+ limit = query.limit
+ )
+ }
)
}
}
@@ -449,6 +476,43 @@ class SeriesRepositoryImpl @Inject constructor(
.any { value -> value.lowercase().contains(normalizedQuery) }
}
+ private suspend fun ensureXtreamCategoryLoaded(providerId: Long, categoryId: Long) {
+ val key = "$providerId:$categoryId"
+ if (loadedXtreamCategories.contains(key)) return
+ if (seriesDao.getCountByCategory(providerId, categoryId).first() > 0) {
+ loadedXtreamCategories.add(key)
+ return
+ }
+
+ val provider = providerDao.getById(providerId) ?: return
+ if (provider.type != ProviderType.XTREAM_CODES) return
+
+ val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
+ lock.withLock {
+ if (loadedXtreamCategories.contains(key)) return
+ if (seriesDao.getCountByCategory(providerId, categoryId).first() > 0) {
+ loadedXtreamCategories.add(key)
+ return
+ }
+
+ runCatching {
+ val xtreamProvider = getOrCreateXtreamProvider(providerId, provider)
+ when (val result = xtreamProvider.getSeriesList(categoryId)) {
+ is Success -> {
+ seriesDao.replaceCategory(
+ providerId,
+ categoryId,
+ result.data.map { item -> item.toEntity() }
+ )
+ episodeDao.deleteOrphans()
+ loadedXtreamCategories.add(key)
+ }
+ else -> Unit
+ }
+ }
+ }
+ }
+
private fun seriesFreshnessScore(series: Series): Long =
series.lastModified
.takeIf { it > 0L }
@@ -472,7 +536,8 @@ class SeriesRepositoryImpl @Inject constructor(
api = xtreamApiService,
serverUrl = provider.serverUrl,
username = provider.username,
- password = decryptedPassword
+ password = decryptedPassword,
+ allowedOutputFormats = provider.toDomain().allowedOutputFormats
)
)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 3ccfe38f..864d0ec5 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -4,6 +4,7 @@ import android.util.Log
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
+import com.streamvault.data.local.dao.ProgramDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesDao
import com.streamvault.data.local.entity.CategoryEntity
@@ -12,6 +13,10 @@ import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.mapper.toDomain
import com.streamvault.data.mapper.toEntity
import com.streamvault.data.parser.M3uParser
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.dto.XtreamStream
+import com.streamvault.data.remote.xtream.OkHttpXtreamApiService
import com.streamvault.data.remote.xtream.XtreamAuthenticationException
import com.streamvault.data.remote.xtream.XtreamNetworkException
import com.streamvault.data.remote.xtream.XtreamParsingException
@@ -22,24 +27,35 @@ import com.streamvault.data.remote.xtream.XtreamUrlFactory
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.data.util.UrlSecurityPolicy
+import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Series
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.model.VodSyncMode
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.SyncMetadataRepository
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.sync.withLock
+import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
@@ -47,11 +63,25 @@ import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.security.MessageDigest
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit.MINUTES
import java.util.zip.GZIPInputStream
import javax.inject.Inject
import javax.inject.Singleton
+import kotlin.random.Random
+import kotlin.system.measureTimeMillis
private const val TAG = "SyncManager"
+private const val XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY = 4
+private const val XTREAM_CATALOG_TIMEOUT_MINUTES = 5L
+private const val XTREAM_CATALOG_PAGE_SIZE = 1000
+private const val XTREAM_CATALOG_MAX_PAGES = 200
+private const val MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Movies category-bulk sync downgraded to sequential mode after provider stress signals."
+private const val LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Live category sync downgraded to sequential mode after provider stress signals."
+private const val SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING =
+ "Series category sync downgraded to sequential mode after provider stress signals."
enum class SyncRepairSection {
EPG,
@@ -65,8 +95,9 @@ class SyncManager @Inject constructor(
private val channelDao: ChannelDao,
private val movieDao: MovieDao,
private val seriesDao: SeriesDao,
+ private val programDao: ProgramDao,
private val categoryDao: CategoryDao,
- private val xtreamApiService: XtreamApiService,
+ private val xtreamJson: Json,
private val m3uParser: M3uParser,
private val epgRepository: EpgRepository,
private val okHttpClient: OkHttpClient,
@@ -77,6 +108,57 @@ class SyncManager @Inject constructor(
val warnings: List<String> = emptyList()
)
+ private sealed interface CatalogStrategyResult<out T> {
+ val strategyName: String
+
+ data class Success<T>(
+ override val strategyName: String,
+ val items: List<T>,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<T>
+
+ data class Partial<T>(
+ override val strategyName: String,
+ val items: List<T>,
+ val warnings: List<String>
+ ) : CatalogStrategyResult<T>
+
+ data class Failure(
+ override val strategyName: String,
+ val error: Throwable,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<Nothing>
+
+ data class EmptyValid(
+ override val strategyName: String,
+ val warnings: List<String> = emptyList()
+ ) : CatalogStrategyResult<Nothing>
+ }
+
+ private data class MovieCatalogSyncResult(
+ val catalogResult: CatalogStrategyResult<Movie>,
+ val categories: List<CategoryEntity>?,
+ val syncMode: VodSyncMode,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class CatalogSyncPayload<T>(
+ val catalogResult: CatalogStrategyResult<T>,
+ val categories: List<CategoryEntity>?,
+ val warnings: List<String> = emptyList()
+ )
+
+ private data class MovieProviderAdaptation(
+ val rememberSequential: Boolean,
+ val healthyStreak: Int
+ )
+
+ private sealed interface CategoryFetchOutcome<out T> {
+ data class Success<T>(val categoryName: String, val items: List<T>) : CategoryFetchOutcome<T>
+ data class Empty(val categoryName: String) : CategoryFetchOutcome<Nothing>
+ data class Failure(val categoryName: String, val error: Throwable) : CategoryFetchOutcome<Nothing>
+ }
+
private data class M3uImportStats(
val header: M3uParser.M3uHeader,
val liveCount: Int,
@@ -144,7 +226,17 @@ class SyncManager @Inject constructor(
val syncState: StateFlow<SyncState> = _syncState.asStateFlow()
private val _syncStatesByProvider = MutableStateFlow<Map<Long, SyncState>>(emptyMap())
val syncStatesByProvider: StateFlow<Map<Long, SyncState>> = _syncStatesByProvider.asStateFlow()
- private val syncMutex = Mutex()
+ private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()
+ private val xtreamCatalogApiService: XtreamApiService by lazy {
+ OkHttpXtreamApiService(
+ client = okHttpClient.newBuilder()
+ .connectTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .readTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .writeTimeout(XTREAM_CATALOG_TIMEOUT_MINUTES, MINUTES)
+ .build(),
+ json = xtreamJson
+ )
+ }
fun syncStateForProvider(providerId: Long): Flow<SyncState> =
syncStatesByProvider.map { states -> states[providerId] ?: SyncState.Idle }
@@ -152,13 +244,18 @@ class SyncManager @Inject constructor(
fun currentSyncState(providerId: Long): SyncState =
_syncStatesByProvider.value[providerId] ?: SyncState.Idle
+ private suspend fun <T> withProviderLock(providerId: Long, block: suspend () -> T): T {
+ val mutex = providerSyncMutexes.computeIfAbsent(providerId) { Mutex() }
+ return mutex.withLock { block() }
+ }
+
suspend fun sync(
providerId: Long,
force: Boolean = false,
onProgress: ((String) -> Unit)? = null
- ): com.streamvault.domain.model.Result<Unit> = syncMutex.withLock {
+ ): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{
val providerEntity = providerDao.getById(providerId)
- ?: return@withLock com.streamvault.domain.model.Result.error("Provider $providerId not found")
+ ?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")
val provider = providerEntity
.copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
@@ -166,11 +263,17 @@ class SyncManager @Inject constructor(
publishSyncState(providerId, SyncState.Syncing("Starting..."))
try {
- val outcome = when (provider.type) {
- ProviderType.XTREAM_CODES -> syncXtream(provider, force, onProgress)
- ProviderType.M3U -> syncM3u(provider, force, onProgress)
+ val outcome = withContext(Dispatchers.IO) {
+ when (provider.type) {
+ ProviderType.XTREAM_CODES -> syncXtream(provider, force, onProgress)
+ ProviderType.M3U -> syncM3u(provider, force, onProgress)
+ }
}
providerDao.updateSyncTime(providerId, System.currentTimeMillis())
+ updateSyncStatusMetadata(
+ providerId = providerId,
+ status = if (outcome.partial) "PARTIAL" else "SUCCESS"
+ )
publishSyncState(providerId, if (outcome.partial) {
SyncState.Partial("Sync completed with warnings", outcome.warnings)
} else {
@@ -179,6 +282,7 @@ class SyncManager @Inject constructor(
com.streamvault.domain.model.Result.success(Unit)
} catch (e: Exception) {
Log.e(TAG, "Sync failed for provider $providerId: ${redactUrlForLogs(e.message)}")
+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
publishSyncState(providerId, SyncState.Error(e.message ?: "Unknown error", e))
com.streamvault.domain.model.Result.error(e.message ?: "Sync failed", e)
}
@@ -197,24 +301,28 @@ class SyncManager @Inject constructor(
providerId: Long,
section: SyncRepairSection,
onProgress: ((String) -> Unit)? = null
- ): com.streamvault.domain.model.Result<Unit> = syncMutex.withLock {
+ ): com.streamvault.domain.model.Result<Unit> = withProviderLock(providerId) lock@{
val providerEntity = providerDao.getById(providerId)
- ?: return@withLock com.streamvault.domain.model.Result.error("Provider $providerId not found")
+ ?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")
val provider = providerEntity
.copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
.toDomain()
try {
- when (section) {
- SyncRepairSection.EPG -> syncEpgOnly(provider, onProgress)
- SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)
- SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)
+ withContext(Dispatchers.IO) {
+ when (section) {
+ SyncRepairSection.EPG -> syncEpgOnly(provider, onProgress)
+ SyncRepairSection.MOVIES -> syncMoviesOnly(provider, onProgress)
+ SyncRepairSection.SERIES -> syncSeriesOnly(provider, onProgress)
+ }
}
+ updateSyncStatusMetadata(providerId = providerId, status = "SUCCESS")
publishSyncState(providerId, SyncState.Success())
com.streamvault.domain.model.Result.success(Unit)
} catch (e: Exception) {
Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${redactUrlForLogs(e.message)}")
+ updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
publishSyncState(providerId, SyncState.Error(e.message ?: "Retry failed", e))
com.streamvault.domain.model.Result.error(e.message ?: "Retry failed", e)
}
@@ -230,57 +338,210 @@ class SyncManager @Inject constructor(
throw IllegalStateException(message)
}
progress(provider.id, onProgress, "Connecting to server...")
- val api = XtreamProvider(
- providerId = provider.id,
- api = xtreamApiService,
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password
- )
+ val api = createXtreamSyncProvider(provider)
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(provider.id, onProgress, "Downloading Live TV...")
- val cats = retryTransient { api.getLiveCategories().getOrThrow("Live categories") }
- categoryDao.replaceAll(provider.id, "LIVE", cats.map { it.toEntity(provider.id) })
-
- val channels = retryTransient { api.getLiveStreams().getOrThrow("Live streams") }
- channelDao.replaceAll(provider.id, channels.map { it.toEntity() })
+ val liveSyncResult = syncXtreamLiveCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
- metadata = metadata.copy(lastLiveSync = now, liveCount = channels.size)
+ when (val liveResult = liveSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
+ channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ warnings += liveSyncResult.warnings + liveResult.warnings
+ }
+ is CatalogStrategyResult.Partial -> {
+ liveSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "LIVE", it) }
+ channelDao.replaceAll(provider.id, liveResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastLiveSync = now, liveCount = liveResult.items.size)
+ warnings += liveSyncResult.warnings + liveResult.warnings + listOf("Live TV sync completed partially.")
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingChannelCount = channelDao.getCount(provider.id).first()
+ Log.w(TAG, "Live TV sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingChannelCount")
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ if (existingChannelCount > 0) {
+ listOf("Live TV refresh returned an empty valid catalog; keeping previous channel library.")
+ } else {
+ listOf("Live TV refresh returned an empty valid catalog with no previous channel library.")
+ }
+ if (existingChannelCount == 0) {
+ throw IllegalStateException("Live TV catalog was empty.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingChannelCount = channelDao.getCount(provider.id).first()
+ Log.w(TAG, "Live TV sync preserved previous catalog for provider ${provider.id}: strategy=${liveResult.strategyName}, existingCount=$existingChannelCount, reason=${sanitizeThrowableMessage(liveResult.error)}")
+ warnings += liveSyncResult.warnings + liveResult.warnings +
+ if (existingChannelCount > 0) {
+ listOf("Live TV sync degraded; keeping previous channel library.")
+ } else {
+ listOf("Live TV sync failed before any usable channel catalog was available.")
+ }
+ if (existingChannelCount == 0) {
+ throw IllegalStateException("Failed to fetch live streams: ${liveResult.error.message}")
+ }
+ }
+ }
syncMetadataRepository.updateMetadata(metadata)
}
if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(provider.id, onProgress, "Downloading Movies...")
- val catsResult = runCatching { retryTransient { api.getVodCategories().getOrThrow("VOD categories") } }
- catsResult.getOrNull()?.let {
- categoryDao.replaceAll(provider.id, "MOVIE", it.map { category -> category.toEntity(provider.id) })
- } ?: warnings.add("Movies categories sync failed")
-
- val moviesResult = runCatching { retryTransient { api.getVodStreams().getOrThrow("VOD streams") } }
- moviesResult.getOrNull()?.let {
- movieDao.replaceAll(provider.id, it.map { movie -> movie.toEntity() })
- metadata = metadata.copy(lastMovieSync = now, movieCount = it.size)
- syncMetadataRepository.updateMetadata(metadata)
- } ?: warnings.add("Movies streams sync failed")
+ val movieSyncResult = syncXtreamMoviesCatalog(
+ provider = provider,
+ api = api,
+ existingMetadata = metadata,
+ onProgress = onProgress
+ )
+ val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
+ .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
+ val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ previousRemembered = metadata.movieParallelFailuresRemembered,
+ previousHealthyStreak = metadata.movieHealthySyncStreak,
+ sawSequentialStress = sawSequentialStress
+ )
+
+ when (val catalogResult = movieSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ metadata = metadata.copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
+ movieCount = catalogResult.items.size,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = false,
+ movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
+ movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ metadata = metadata.copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMoviePartial = now,
+ movieCount = catalogResult.items.size,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = true,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ Log.w(TAG, "Movies sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingMovieCount")
+ metadata = metadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings +
+ if (existingMovieCount > 0) {
+ listOf("Movies refresh returned an empty valid catalog; keeping previous movie library.")
+ } else {
+ listOf("Movies refresh returned an empty valid catalog with no previous movie library.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ val finalMode = if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ VodSyncMode.LAZY_BY_CATEGORY
+ } else {
+ metadata.movieSyncMode
+ }
+ if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ }
+ Log.w(TAG, "Movies sync preserved previous catalog for provider ${provider.id}: strategy=${catalogResult.strategyName}, existingCount=$existingMovieCount, mode=${movieSyncResult.syncMode}, reason=${sanitizeThrowableMessage(catalogResult.error)}")
+ metadata = metadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = finalMode,
+ movieWarningsCount = (movieSyncResult.warnings + catalogResult.warnings).size,
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = metadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
+ movieHealthySyncStreak = 0
+ )
+ warnings += movieSyncResult.warnings + catalogResult.warnings +
+ if (existingMovieCount > 0) {
+ listOf("Movies sync degraded; keeping previous movie library.")
+ } else {
+ listOf("Movies sync failed before any usable movie catalog was available.")
+ }
+ if (existingMovieCount == 0 && movieSyncResult.syncMode != VodSyncMode.LAZY_BY_CATEGORY) {
+ throw IllegalStateException("Failed to fetch movie catalog: ${catalogResult.error.message}")
+ }
+ }
+ }
+ syncMetadataRepository.updateMetadata(metadata)
}
if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSync, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(provider.id, onProgress, "Downloading Series...")
- val catsResult = runCatching { retryTransient { api.getSeriesCategories().getOrThrow("Series categories") } }
- catsResult.getOrNull()?.let {
- categoryDao.replaceAll(provider.id, "SERIES", it.map { category -> category.toEntity(provider.id) })
- } ?: warnings.add("Series categories sync failed")
-
- val seriesResult = runCatching { retryTransient { api.getSeriesList().getOrThrow("Series list") } }
- seriesResult.getOrNull()?.let {
- seriesDao.replaceAll(provider.id, it.map { series -> series.toEntity() })
- metadata = metadata.copy(lastSeriesSync = now, seriesCount = it.size)
- syncMetadataRepository.updateMetadata(metadata)
- } ?: warnings.add("Series list sync failed")
+ val seriesSyncResult = syncXtreamSeriesCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
+
+ when (val seriesResult = seriesSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ warnings += seriesSyncResult.warnings + seriesResult.warnings
+ }
+ is CatalogStrategyResult.Partial -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ warnings += seriesSyncResult.warnings + seriesResult.warnings + listOf("Series sync completed partially.")
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ Log.w(TAG, "Series sync kept existing catalog for provider ${provider.id}: empty valid result, existingCount=$existingSeriesCount")
+ warnings += seriesSyncResult.warnings + seriesResult.warnings +
+ if (existingSeriesCount > 0) {
+ listOf("Series refresh returned an empty valid catalog; keeping previous series library.")
+ } else {
+ listOf("Series refresh returned an empty valid catalog with no previous series library.")
+ }
+ if (existingSeriesCount == 0) {
+ throw IllegalStateException("Series catalog was empty.")
+ }
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ Log.w(TAG, "Series sync preserved previous catalog for provider ${provider.id}: strategy=${seriesResult.strategyName}, existingCount=$existingSeriesCount, reason=${sanitizeThrowableMessage(seriesResult.error)}")
+ warnings += seriesSyncResult.warnings + seriesResult.warnings +
+ if (existingSeriesCount > 0) {
+ listOf("Series sync degraded; keeping previous series library.")
+ } else {
+ listOf("Series sync failed before any usable series catalog was available.")
+ }
+ if (existingSeriesCount == 0) {
+ throw IllegalStateException("Failed to fetch series catalog: ${seriesResult.error.message}")
+ }
+ }
+ }
+ syncMetadataRepository.updateMetadata(metadata)
}
if (force || ContentCachePolicy.shouldRefresh(metadata.lastEpgSync, ContentCachePolicy.EPG_TTL_MILLIS, now)) {
@@ -290,15 +551,22 @@ class SyncManager @Inject constructor(
val xmltvUrl = provider.epgUrl.ifBlank {
XtreamUrlFactory.buildXmltvUrl(base, provider.username, provider.password)
}
- UrlSecurityPolicy.validateOptionalEpgUrl(xmltvUrl)?.let { message ->
+ UrlSecurityPolicy.validateXtreamEpgUrl(xmltvUrl)?.let { message ->
throw IllegalStateException(message)
}
retryTransient { epgRepository.refreshEpg(provider.id, xmltvUrl) }
- metadata = metadata.copy(lastEpgSync = now)
+ val epgCount = programDao.countByProvider(provider.id)
+ metadata = metadata.copy(
+ lastEpgSync = now,
+ epgCount = epgCount
+ )
syncMetadataRepository.updateMetadata(metadata)
+ if (epgCount == 0) {
+ warnings.add("EPG imported zero programs; live guide will fall back to on-demand Xtream data.")
+ }
} catch (e: Exception) {
- Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
- warnings.add("EPG sync failed")
+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
+ warnings.add("EPG XMLTV sync failed; live guide will fall back to on-demand Xtream data.")
}
}
@@ -327,8 +595,14 @@ class SyncManager @Inject constructor(
lastLiveSync = now,
lastMovieSync = now,
lastSeriesSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
liveCount = stats.liveCount,
- movieCount = stats.movieCount
+ movieCount = stats.movieCount,
+ movieSyncMode = VodSyncMode.FULL,
+ movieWarningsCount = stats.warnings.size,
+ movieCatalogStale = false,
+ movieHealthySyncStreak = 0
)
syncMetadataRepository.updateMetadata(metadata)
}
@@ -342,10 +616,13 @@ class SyncManager @Inject constructor(
try {
progress(provider.id, onProgress, "Downloading EPG...")
retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
- metadata = metadata.copy(lastEpgSync = now)
+ metadata = metadata.copy(
+ lastEpgSync = now,
+ epgCount = programDao.countByProvider(provider.id)
+ )
syncMetadataRepository.updateMetadata(metadata)
} catch (e: Exception) {
- Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
+ Log.e(TAG, "EPG sync failed (non-fatal): ${sanitizeThrowableMessage(e)}")
warnings.add("EPG sync failed")
}
}
@@ -371,13 +648,20 @@ class SyncManager @Inject constructor(
if (epgUrl.isBlank()) {
throw IllegalStateException("No EPG URL configured for this provider")
}
- UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)?.let { message ->
+ val validationError = when (provider.type) {
+ ProviderType.XTREAM_CODES -> UrlSecurityPolicy.validateXtreamEpgUrl(epgUrl)
+ ProviderType.M3U -> UrlSecurityPolicy.validateOptionalEpgUrl(epgUrl)
+ }
+ validationError?.let { message ->
throw IllegalStateException(message)
}
retryTransient { epgRepository.refreshEpg(provider.id, epgUrl) }
val now = System.currentTimeMillis()
val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
- .copy(lastEpgSync = now)
+ .copy(
+ lastEpgSync = now,
+ epgCount = programDao.countByProvider(provider.id)
+ )
syncMetadataRepository.updateMetadata(metadata)
}
@@ -389,22 +673,92 @@ class SyncManager @Inject constructor(
when (provider.type) {
ProviderType.XTREAM_CODES -> {
progress(provider.id, onProgress, "Retrying Movies...")
- val api = XtreamProvider(
- providerId = provider.id,
- api = xtreamApiService,
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password
+ val api = createXtreamSyncProvider(provider)
+ val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ val movieSyncResult = syncXtreamMoviesCatalog(
+ provider = provider,
+ api = api,
+ existingMetadata = currentMetadata,
+ onProgress = onProgress
+ )
+ val sawSequentialStress = (movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult))
+ .any { warning -> warning.contains(MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING, ignoreCase = true) }
+ val healthyMovieProviderAdaptation = updateMovieProviderAdaptation(
+ previousRemembered = currentMetadata.movieParallelFailuresRemembered,
+ previousHealthyStreak = currentMetadata.movieHealthySyncStreak,
+ sawSequentialStress = sawSequentialStress
+ )
+ val movieWarnings = movieSyncResult.warnings + strategyWarnings(movieSyncResult.catalogResult)
+
+ val metadata = currentMetadata.copy(
+ lastMovieAttempt = now,
+ movieSyncMode = movieSyncResult.syncMode,
+ movieWarningsCount = movieWarnings.size,
+ movieCatalogStale = movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress
)
- val cats = retryTransient { api.getVodCategories().getOrThrow("VOD categories") }
- categoryDao.replaceAll(provider.id, "MOVIE", cats.map { it.toEntity(provider.id) })
-
- val movies = retryTransient { api.getVodStreams().getOrThrow("VOD streams") }
- movieDao.replaceAll(provider.id, movies.map { it.toEntity() })
- val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
- .copy(lastMovieSync = now, movieCount = movies.size)
- syncMetadataRepository.updateMetadata(metadata)
+ when (val catalogResult = movieSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieSync = now,
+ lastMovieSuccess = now,
+ movieCount = catalogResult.items.size,
+ movieCatalogStale = false,
+ movieParallelFailuresRemembered = healthyMovieProviderAdaptation.rememberSequential,
+ movieHealthySyncStreak = healthyMovieProviderAdaptation.healthyStreak
+ )
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ movieDao.replaceAll(provider.id, catalogResult.items.map { movie -> movie.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ lastMovieSync = now,
+ lastMoviePartial = now,
+ movieCount = catalogResult.items.size,
+ movieCatalogStale = true,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ )
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress,
+ movieHealthySyncStreak = 0
+ )
+ )
+ throw IllegalStateException(
+ if (existingMovieCount > 0) {
+ "Movies refresh returned an empty catalog; existing library was preserved."
+ } else {
+ "Movies refresh returned an empty catalog."
+ }
+ )
+ }
+ is CatalogStrategyResult.Failure -> {
+ val existingMovieCount = movieDao.getCount(provider.id).first()
+ if (movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY) {
+ movieSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "MOVIE", it) }
+ }
+ syncMetadataRepository.updateMetadata(
+ metadata.copy(
+ movieCatalogStale = existingMovieCount > 0 || movieSyncResult.syncMode == VodSyncMode.LAZY_BY_CATEGORY,
+ movieParallelFailuresRemembered = currentMetadata.movieParallelFailuresRemembered || sawSequentialStress || shouldRememberSequentialPreference(catalogResult.error),
+ movieHealthySyncStreak = 0
+ )
+ )
+ throw IllegalStateException(catalogResult.error.message ?: "Failed to fetch VOD streams", catalogResult.error)
+ }
+ }
}
ProviderType.M3U -> {
progress(provider.id, onProgress, "Retrying Movies...")
@@ -415,7 +769,15 @@ class SyncManager @Inject constructor(
throw IllegalStateException("Playlist contains no movie entries")
}
val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
- .copy(lastMovieSync = now, movieCount = stats.movieCount)
+ .copy(
+ lastMovieSync = now,
+ lastMovieAttempt = now,
+ lastMovieSuccess = now,
+ movieCount = stats.movieCount,
+ movieSyncMode = VodSyncMode.FULL,
+ movieWarningsCount = stats.warnings.size,
+ movieCatalogStale = false
+ )
syncMetadataRepository.updateMetadata(metadata)
}
}
@@ -429,23 +791,1032 @@ class SyncManager @Inject constructor(
throw IllegalStateException("Series retry is available only for Xtream providers")
}
progress(provider.id, onProgress, "Retrying Series...")
- val api = XtreamProvider(
- providerId = provider.id,
- api = xtreamApiService,
- serverUrl = provider.serverUrl,
- username = provider.username,
- password = provider.password
+ val api = createXtreamSyncProvider(provider)
+ val seriesSyncResult = syncXtreamSeriesCatalog(
+ provider = provider,
+ api = api,
+ onProgress = onProgress
+ )
+
+ val now = System.currentTimeMillis()
+ val currentMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
+ when (val seriesResult = seriesSyncResult.catalogResult) {
+ is CatalogStrategyResult.Success -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ )
+ }
+ is CatalogStrategyResult.Partial -> {
+ seriesSyncResult.categories?.let { categoryDao.replaceAll(provider.id, "SERIES", it) }
+ seriesDao.replaceAll(provider.id, seriesResult.items.map { it.toEntity() })
+ syncMetadataRepository.updateMetadata(
+ currentMetadata.copy(lastSeriesSync = now, seriesCount = seriesResult.items.size)
+ )
+ }
+ is CatalogStrategyResult.EmptyValid -> {
+ val existingSeriesCount = seriesDao.getCount(provider.id).first()
+ throw IllegalStateException(
+ if (existingSeriesCount > 0) {
+ "Series refresh returned an empty catalog; existing library was preserved."
+ } else {
+ "Series catalog was empty."
+ }
+ )
+ }
+ is CatalogStrategyResult.Failure -> {
+ throw IllegalStateException(seriesResult.error.message ?: "Failed to fetch series list", seriesResult.error)
+ }
+ }
+ }
+
+ private suspend fun syncXtreamMoviesCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ existingMetadata: SyncMetadata,
+ onProgress: ((String) -> Unit)?
+ ): MovieCatalogSyncResult {
+ Log.i(
+ TAG,
+ "Xtream movies strategy start for provider ${provider.id}. previousMode=${existingMetadata.movieSyncMode} rememberSequential=${existingMetadata.movieParallelFailuresRemembered}"
+ )
+ val rawVodCategories = fetchXtreamVodCategories(provider)
+ val resolvedCategories = rawVodCategories
+ ?.let { categories -> api.mapCategories(ContentType.MOVIE, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamMoviesFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
+ syncMode = VodSyncMode.FULL
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected FULL for provider ${provider.id} with ${fullResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, fullResult.items),
+ syncMode = VodSyncMode.FULL,
+ warnings = emptyList()
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected FULL(partial) for provider ${provider.id} with ${fullResult.items.size} items.")
+ }
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamMoviesByCategory(
+ provider = provider,
+ api = api,
+ rawCategories = rawVodCategories.orEmpty(),
+ onProgress = onProgress,
+ preferSequential = existingMetadata.movieParallelFailuresRemembered
)
+ when (categoryResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ syncMode = VodSyncMode.CATEGORY_BULK,
+ warnings = strategyWarnings(fullResult)
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected CATEGORY_BULK for provider ${provider.id} with ${categoryResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, categoryResult.items),
+ syncMode = VodSyncMode.CATEGORY_BULK,
+ warnings = strategyWarnings(fullResult)
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected CATEGORY_BULK(partial) for provider ${provider.id} with ${categoryResult.items.size} items.")
+ }
+ else -> Unit
+ }
- val cats = retryTransient { api.getSeriesCategories().getOrThrow("Series categories") }
- categoryDao.replaceAll(provider.id, "SERIES", cats.map { it.toEntity(provider.id) })
+ val pagedResult = loadXtreamMoviesByPage(provider, api, onProgress)
+ when (pagedResult) {
+ is CatalogStrategyResult.Success -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ ).also {
+ Log.i(TAG, "Xtream movies strategy selected PAGED for provider ${provider.id} with ${pagedResult.items.size} items.")
+ }
+ is CatalogStrategyResult.Partial -> return MovieCatalogSyncResult(
+ catalogResult = pagedResult,
+ categories = resolvedCategories ?: buildFallbackMovieCategories(provider.id, pagedResult.items),
+ syncMode = VodSyncMode.PAGED,
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ ).also {
+ Log.w(TAG, "Xtream movies strategy selected PAGED(partial) for provider ${provider.id} with ${pagedResult.items.size} items.")
+ }
+ else -> Unit
+ }
- val seriesList = retryTransient { api.getSeriesList().getOrThrow("Series list") }
- seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })
+ val lazyWarnings = buildList {
+ addAll(strategyWarnings(fullResult))
+ addAll(strategyWarnings(categoryResult))
+ addAll(strategyWarnings(pagedResult))
+ add("Movies entered lazy category-only mode after full, category-bulk, and paged strategies failed.")
+ }
+ Log.w(
+ TAG,
+ "Xtream movies strategy exhausted for provider ${provider.id}. categoriesAvailable=${!resolvedCategories.isNullOrEmpty()} finalMode=${if (!resolvedCategories.isNullOrEmpty()) VodSyncMode.LAZY_BY_CATEGORY else VodSyncMode.UNKNOWN}"
+ )
- val now = System.currentTimeMillis()
- val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
- .copy(lastSeriesSync = now, seriesCount = seriesList.size)
+ return if (!resolvedCategories.isNullOrEmpty()) {
+ MovieCatalogSyncResult(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "lazy_by_category",
+ error = IllegalStateException("Movie catalog strategies failed; exposing categories only"),
+ warnings = lazyWarnings
+ ),
+ categories = resolvedCategories,
+ syncMode = VodSyncMode.LAZY_BY_CATEGORY,
+ warnings = lazyWarnings
+ )
+ } else {
+ MovieCatalogSyncResult(
+ catalogResult = CatalogStrategyResult.Failure(
+ strategyName = "movies",
+ error = IllegalStateException("Movie catalog strategies failed and no categories were available"),
+ warnings = lazyWarnings
+ ),
+ categories = null,
+ syncMode = VodSyncMode.UNKNOWN,
+ warnings = lazyWarnings
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Movie> {
+ var fullMovies: List<Movie>? = null
+ var fullMoviesFailure: Throwable? = null
+ val fullMoviesElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getVodStreams().getOrThrow("VOD streams") }
+ }.onSuccess { movies ->
+ fullMovies = movies
+ }.onFailure { error ->
+ fullMoviesFailure = error
+ }
+ }
+ if (!fullMovies.isNullOrEmpty()) {
+ Log.i(
+ TAG,
+ "Xtream movies full catalog succeeded for provider ${provider.id} in ${fullMoviesElapsedMs}ms with ${fullMovies!!.size} items."
+ )
+ return CatalogStrategyResult.Success(
+ strategyName = "full",
+ items = fullMovies!!
+ )
+ }
+ return if (fullMoviesFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "movies",
+ stage = "full catalog",
+ elapsedMs = fullMoviesElapsedMs,
+ itemCount = fullMovies?.size,
+ error = fullMoviesFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullMoviesFailure!!,
+ warnings = listOf("Movies full catalog request failed: ${sanitizeThrowableMessage(fullMoviesFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "movies",
+ stage = "full catalog",
+ elapsedMs = fullMoviesElapsedMs,
+ itemCount = fullMovies?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Movies full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun syncXtreamLiveCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogSyncPayload<Channel> {
+ Log.i(TAG, "Xtream live strategy start for provider ${provider.id}.")
+ val rawLiveCategories = runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getLiveCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream live categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ val resolvedCategories = rawLiveCategories
+ ?.let { categories -> api.mapCategories(ContentType.LIVE, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamLiveFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackLiveCategories(provider.id, fullResult.items),
+ warnings = emptyList()
+ )
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamLiveByCategory(provider, api, rawLiveCategories.orEmpty(), onProgress, preferSequential = false)
+ return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = when (categoryResult) {
+ is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)
+ is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackLiveCategories(provider.id, categoryResult.items)
+ else -> null
+ },
+ warnings = strategyWarnings(fullResult)
+ )
+ }
+
+ private suspend fun loadXtreamLiveFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Channel> {
+ var fullChannels: List<Channel>? = null
+ var fullChannelsFailure: Throwable? = null
+ val fullChannelsElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getLiveStreams().getOrThrow("Live streams") }
+ }.onSuccess { channels ->
+ fullChannels = channels
+ }.onFailure { error ->
+ fullChannelsFailure = error
+ }
+ }
+ if (!fullChannels.isNullOrEmpty()) {
+ Log.i(TAG, "Xtream live full catalog succeeded for provider ${provider.id} in ${fullChannelsElapsedMs}ms with ${fullChannels!!.size} items.")
+ return CatalogStrategyResult.Success("full", fullChannels!!)
+ }
+ return if (fullChannelsFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "live",
+ stage = "full catalog",
+ elapsedMs = fullChannelsElapsedMs,
+ itemCount = fullChannels?.size,
+ error = fullChannelsFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullChannelsFailure!!,
+ warnings = listOf("Live full catalog request failed: ${sanitizeThrowableMessage(fullChannelsFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "live",
+ stage = "full catalog",
+ elapsedMs = fullChannelsElapsedMs,
+ itemCount = fullChannels?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Live full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamLiveByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Channel> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No live categories available"),
+ warnings = listOf("Live category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else XTREAM_LIVE_CATEGORY_SYNC_MAX_CONCURRENCY
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Live TV 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getLiveStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_live_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Live TV $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Live category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
+ }
+ Log.w(TAG, "Xtream live category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream live category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapLiveStreamsResponse(rawStreams))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
+ Log.w(TAG, "Xtream live category sync is downgrading to sequential mode for provider ${provider.id}.")
+ return when (val sequentialResult = loadXtreamLiveByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ }
+ }
+
+ val channels = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Channel>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.streamId > 0L }
+ .associateBy { it.streamId }
+ .values
+ .toList()
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ Log.i(TAG, "Xtream live category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedChannels=${channels.size} concurrency=$concurrency")
+
+ return when {
+ channels.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", channels, warnings.toList())
+ channels.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", channels, warnings.toList())
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Live category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All live categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Movie> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No VOD categories available"),
+ warnings = listOf("Movies category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Movies 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Movies $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Category '${category.categoryName}' failed: ${failure.message}"
+ }
+ Log.w(
+ TAG,
+ "Xtream movie category '${category.categoryName}' failed after ${elapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
+ )
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawStreams.isEmpty() -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream movie category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawStreams.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapVodStreamsResponse(rawStreams))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(
+ totalCategories = categories.size,
+ failures = failureCount.get(),
+ fastFailures = fastFailureCount.get(),
+ outcomes = categoryOutcomes
+ )
+ ) {
+ val downgradeReasons = buildList {
+ add("failures=${failureCount.get()}/${categories.size}")
+ if (fastFailureCount.get() > 0) add("fastFailures=${fastFailureCount.get()}")
+ val providerStressSignals = categoryOutcomes.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ if (providerStressSignals > 0) add("providerStressSignals=$providerStressSignals")
+ }.joinToString(", ")
+ Log.w(
+ TAG,
+ "Xtream movie category sync is downgrading to sequential mode for provider ${provider.id}: $downgradeReasons"
+ )
+ return when (val sequentialResult = loadXtreamMoviesByCategory(
+ provider = provider,
+ api = api,
+ rawCategories = rawCategories,
+ onProgress = onProgress,
+ preferSequential = true
+ )) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(
+ warnings = sequentialResult.warnings + MOVIE_CATEGORY_SEQUENTIAL_MODE_WARNING
+ )
+ }
+ }
+
+ val movies = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Movie>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.streamId > 0L }
+ .associateBy { it.streamId }
+ .values
+ .toList()
+
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ Log.i(
+ TAG,
+ "Xtream movie category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedMovies=${movies.size} concurrency=$concurrency"
+ )
+ return when {
+ movies.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success(
+ strategyName = "category_bulk",
+ items = movies,
+ warnings = warnings.toList()
+ )
+ movies.isNotEmpty() -> CatalogStrategyResult.Partial(
+ strategyName = "category_bulk",
+ items = movies,
+ warnings = warnings.toList()
+ )
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Movie category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All movie categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamMoviesByPage(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogStrategyResult<Movie> {
+ val moviesByStreamId = LinkedHashMap<Long, Movie>()
+ val warnings = mutableListOf<String>()
+ var sawValidPage = false
+ for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
+ progress(provider.id, onProgress, "Downloading Movies page $page...")
+ rateLimitXtreamCatalogRequest()
+ var rawStreams: List<XtreamStream> = emptyList()
+ var pageFailure: Throwable? = null
+ val pageElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getVodStreams(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_streams",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }.onSuccess { streams ->
+ rawStreams = streams
+ }.onFailure { error ->
+ pageFailure = error
+ }
+ }
+
+ if (pageFailure != null) {
+ val failure = pageFailure!!
+ Log.w(
+ TAG,
+ "Xtream paged movie request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${failure::class.java.simpleName}: ${failure.message}"
+ )
+ return if (page == 1 || moviesByStreamId.isEmpty()) {
+ CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = failure,
+ warnings = listOf("Movie paging failed on the first page: ${failure.message}")
+ )
+ } else {
+ warnings += "Movie paging failed on page $page: ${failure.message}"
+ CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = moviesByStreamId.values.toList(),
+ warnings = warnings.toList()
+ )
+ }
+ }
+
+ Log.i(
+ TAG,
+ "Xtream paged movie request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawStreams.size} raw items."
+ )
+
+ if (rawStreams.isEmpty()) {
+ return when {
+ moviesByStreamId.isNotEmpty() -> CatalogStrategyResult.Success(
+ strategyName = "paged",
+ items = moviesByStreamId.values.toList(),
+ warnings = warnings.toList()
+ )
+ sawValidPage -> CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog returned no items.")
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog is unsupported or empty on this provider.")
+ )
+ }
+ }
+
+ sawValidPage = true
+ val mappedMovies = api.mapVodStreamsResponse(rawStreams)
+ val beforeCount = moviesByStreamId.size
+ mappedMovies.forEach { movie ->
+ if (movie.streamId > 0L) {
+ moviesByStreamId[movie.streamId] = movie
+ }
+ }
+ val newItems = moviesByStreamId.size - beforeCount
+ if (rawStreams.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ break
+ }
+ }
+
+ return moviesByStreamId.values.toList()
+ .takeIf { it.isNotEmpty() }
+ ?.let { items ->
+ Log.i(TAG, "Xtream paged movie strategy completed for provider ${provider.id} with ${items.size} deduped items.")
+ CatalogStrategyResult.Success("paged", items, warnings.toList())
+ }
+ ?: CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged movie catalog completed without items.")
+ )
+ }
+
+ private suspend fun syncXtreamSeriesCatalog(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogSyncPayload<Series> {
+ Log.i(TAG, "Xtream series strategy start for provider ${provider.id}.")
+ val rawSeriesCategories = runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getSeriesCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream series categories request failed for provider ${provider.id}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ val resolvedCategories = rawSeriesCategories
+ ?.let { categories -> api.mapCategories(ContentType.SERIES, categories) }
+ ?.map { category -> category.toEntity(provider.id) }
+ ?.takeIf { it.isNotEmpty() }
+
+ val fullResult = loadXtreamSeriesFull(provider, api)
+ when (fullResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = fullResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, fullResult.items),
+ warnings = emptyList()
+ )
+ else -> Unit
+ }
+
+ val categoryResult = loadXtreamSeriesByCategory(provider, api, rawSeriesCategories.orEmpty(), onProgress, preferSequential = false)
+ when (categoryResult) {
+ is CatalogStrategyResult.Success -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
+ warnings = strategyWarnings(fullResult)
+ )
+ is CatalogStrategyResult.Partial -> return CatalogSyncPayload(
+ catalogResult = categoryResult,
+ categories = resolvedCategories ?: buildFallbackSeriesCategories(provider.id, categoryResult.items),
+ warnings = strategyWarnings(fullResult)
+ )
+ else -> Unit
+ }
+
+ val pagedResult = loadXtreamSeriesByPage(provider, api, onProgress)
+ return CatalogSyncPayload(
+ catalogResult = pagedResult,
+ categories = when (pagedResult) {
+ is CatalogStrategyResult.Success -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
+ is CatalogStrategyResult.Partial -> resolvedCategories ?: buildFallbackSeriesCategories(provider.id, pagedResult.items)
+ else -> null
+ },
+ warnings = strategyWarnings(fullResult) + strategyWarnings(categoryResult)
+ )
+ }
+
+ private suspend fun loadXtreamSeriesFull(
+ provider: Provider,
+ api: XtreamProvider
+ ): CatalogStrategyResult<Series> {
+ var fullSeries: List<Series>? = null
+ var fullSeriesFailure: Throwable? = null
+ val fullSeriesElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient { api.getSeriesList().getOrThrow("Series list") }
+ }.onSuccess { series ->
+ fullSeries = series
+ }.onFailure { error ->
+ fullSeriesFailure = error
+ }
+ }
+ if (!fullSeries.isNullOrEmpty()) {
+ Log.i(TAG, "Xtream series full catalog succeeded for provider ${provider.id} in ${fullSeriesElapsedMs}ms with ${fullSeries!!.size} items.")
+ return CatalogStrategyResult.Success("full", fullSeries!!)
+ }
+ return if (fullSeriesFailure != null) {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "series",
+ stage = "full catalog",
+ elapsedMs = fullSeriesElapsedMs,
+ itemCount = fullSeries?.size,
+ error = fullSeriesFailure,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.Failure(
+ strategyName = "full",
+ error = fullSeriesFailure!!,
+ warnings = listOf("Series full catalog request failed: ${sanitizeThrowableMessage(fullSeriesFailure)}")
+ )
+ } else {
+ logXtreamCatalogFallback(
+ provider = provider,
+ section = "series",
+ stage = "full catalog",
+ elapsedMs = fullSeriesElapsedMs,
+ itemCount = fullSeries?.size,
+ error = null,
+ nextStep = "category-bulk"
+ )
+ CatalogStrategyResult.EmptyValid(
+ strategyName = "full",
+ warnings = listOf("Series full catalog returned an empty valid result.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamSeriesByCategory(
+ provider: Provider,
+ api: XtreamProvider,
+ rawCategories: List<XtreamCategory>,
+ onProgress: ((String) -> Unit)?,
+ preferSequential: Boolean
+ ): CatalogStrategyResult<Series> {
+ val categories = rawCategories.filter { it.categoryId.isNotBlank() }
+ if (categories.isEmpty()) {
+ return CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("No series categories available"),
+ warnings = listOf("Series category-bulk strategy was unavailable because no categories were returned.")
+ )
+ }
+
+ val concurrency = if (preferSequential) 1 else xtreamCategorySyncConcurrency(categories.size)
+ val semaphore = Semaphore(concurrency)
+ val progressCounter = java.util.concurrent.atomic.AtomicInteger(0)
+ val failureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val fastFailureCount = java.util.concurrent.atomic.AtomicInteger(0)
+ val warnings = mutableListOf<String>()
+ val warningsMutex = Mutex()
+ progress(provider.id, onProgress, "Downloading Series 0/${categories.size}...")
+
+ val categoryOutcomes = coroutineScope {
+ categories.map { category ->
+ async {
+ semaphore.withPermit {
+ rateLimitXtreamCatalogRequest()
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var categoryFailure: Throwable? = null
+ val elapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = mapOf("category_id" to category.categoryId)
+ )
+ )
+ }
+ }.onSuccess { series ->
+ rawSeries = series
+ }.onFailure { error ->
+ categoryFailure = error
+ }
+ }
+
+ val completed = progressCounter.incrementAndGet()
+ progress(provider.id, onProgress, "Downloading Series $completed/${categories.size}...")
+
+ when {
+ categoryFailure != null -> {
+ failureCount.incrementAndGet()
+ if (elapsedMs <= 5_000L) fastFailureCount.incrementAndGet()
+ val failure = categoryFailure!!
+ warningsMutex.withLock {
+ warnings += "Series category '${category.categoryName}' failed: ${sanitizeThrowableMessage(failure)}"
+ }
+ Log.w(TAG, "Xtream series category '${category.categoryName}' failed after ${elapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ CategoryFetchOutcome.Failure(category.categoryName, failure)
+ }
+ rawSeries.isEmpty() -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with a valid empty result.")
+ CategoryFetchOutcome.Empty(category.categoryName)
+ }
+ else -> {
+ Log.i(TAG, "Xtream series category '${category.categoryName}' completed in ${elapsedMs}ms with ${rawSeries.size} raw items.")
+ CategoryFetchOutcome.Success(category.categoryName, api.mapSeriesListResponse(rawSeries))
+ }
+ }
+ }
+ }
+ }.awaitAll()
+ }
+
+ if (concurrency > 1 && shouldDowngradeCategorySync(categories.size, failureCount.get(), fastFailureCount.get(), categoryOutcomes)) {
+ Log.w(TAG, "Xtream series category sync is downgrading to sequential mode for provider ${provider.id}.")
+ return when (val sequentialResult = loadXtreamSeriesByCategory(provider, api, rawCategories, onProgress, preferSequential = true)) {
+ is CatalogStrategyResult.Success -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Partial -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.Failure -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ is CatalogStrategyResult.EmptyValid -> sequentialResult.copy(warnings = sequentialResult.warnings + SERIES_CATEGORY_SEQUENTIAL_MODE_WARNING)
+ }
+ }
+
+ val series = categoryOutcomes
+ .asSequence()
+ .filterIsInstance<CategoryFetchOutcome.Success<Series>>()
+ .flatMap { it.items.asSequence() }
+ .filter { it.seriesId > 0L }
+ .associateBy { it.seriesId }
+ .values
+ .toList()
+ val failedCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Failure }
+ val emptyCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Empty }
+ val successfulCategories = categoryOutcomes.count { it is CategoryFetchOutcome.Success }
+ Log.i(TAG, "Xtream series category strategy summary for provider ${provider.id}: successful=$successfulCategories empty=$emptyCategories failed=$failedCategories dedupedSeries=${series.size} concurrency=$concurrency")
+
+ return when {
+ series.isNotEmpty() && failedCategories == 0 -> CatalogStrategyResult.Success("category_bulk", series, warnings.toList())
+ series.isNotEmpty() -> CatalogStrategyResult.Partial("category_bulk", series, warnings.toList())
+ failedCategories > 0 -> CatalogStrategyResult.Failure(
+ strategyName = "category_bulk",
+ error = IllegalStateException("Series category-bulk sync failed for all usable categories"),
+ warnings = warnings.toList()
+ )
+ else -> CatalogStrategyResult.EmptyValid(
+ strategyName = "category_bulk",
+ warnings = listOf("All series categories returned valid empty results.")
+ )
+ }
+ }
+
+ private suspend fun loadXtreamSeriesByPage(
+ provider: Provider,
+ api: XtreamProvider,
+ onProgress: ((String) -> Unit)?
+ ): CatalogStrategyResult<Series> {
+ val seriesById = LinkedHashMap<Long, Series>()
+ val warnings = mutableListOf<String>()
+ var sawValidPage = false
+ for (page in 1..XTREAM_CATALOG_MAX_PAGES) {
+ progress(provider.id, onProgress, "Downloading Series page $page...")
+ rateLimitXtreamCatalogRequest()
+ var rawSeries: List<XtreamSeriesItem> = emptyList()
+ var pageFailure: Throwable? = null
+ val pageElapsedMs = measureTimeMillis {
+ runCatching {
+ retryXtreamCatalogTransient {
+ xtreamCatalogApiService.getSeriesList(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_series",
+ extraQueryParams = paginationParamsForPage(page)
+ )
+ )
+ }
+ }.onSuccess { series ->
+ rawSeries = series
+ }.onFailure { error ->
+ pageFailure = error
+ }
+ }
+
+ if (pageFailure != null) {
+ val failure = pageFailure!!
+ Log.w(TAG, "Xtream paged series request failed for provider ${provider.id} on page $page after ${pageElapsedMs}ms: ${sanitizeThrowableMessage(failure)}")
+ return if (page == 1 || seriesById.isEmpty()) {
+ CatalogStrategyResult.Failure(
+ strategyName = "paged",
+ error = failure,
+ warnings = listOf("Series paging failed on the first page: ${sanitizeThrowableMessage(failure)}")
+ )
+ } else {
+ warnings += "Series paging failed on page $page: ${sanitizeThrowableMessage(failure)}"
+ CatalogStrategyResult.Partial(
+ strategyName = "paged",
+ items = seriesById.values.toList(),
+ warnings = warnings.toList()
+ )
+ }
+ }
+
+ Log.i(TAG, "Xtream paged series request for provider ${provider.id} page $page completed in ${pageElapsedMs}ms with ${rawSeries.size} raw items.")
+ if (rawSeries.isEmpty()) {
+ return when {
+ seriesById.isNotEmpty() -> CatalogStrategyResult.Success("paged", seriesById.values.toList(), warnings.toList())
+ sawValidPage -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog returned no items."))
+ else -> CatalogStrategyResult.EmptyValid("paged", listOf("Paged series catalog is unsupported or empty on this provider."))
+ }
+ }
+
+ sawValidPage = true
+ val mappedSeries = api.mapSeriesListResponse(rawSeries)
+ val beforeCount = seriesById.size
+ mappedSeries.forEach { item ->
+ if (item.seriesId > 0L) {
+ seriesById[item.seriesId] = item
+ }
+ }
+ val newItems = seriesById.size - beforeCount
+ if (rawSeries.size < XTREAM_CATALOG_PAGE_SIZE || newItems == 0) {
+ break
+ }
+ }
+
+ return seriesById.values.toList()
+ .takeIf { it.isNotEmpty() }
+ ?.let { items -> CatalogStrategyResult.Success("paged", items, warnings.toList()) }
+ ?: CatalogStrategyResult.EmptyValid(
+ strategyName = "paged",
+ warnings = listOf("Paged series catalog completed without items.")
+ )
+ }
+
+ private suspend fun updateSyncStatusMetadata(providerId: Long, status: String) {
+ val metadata = (syncMetadataRepository.getMetadata(providerId) ?: SyncMetadata(providerId))
+ .copy(lastSyncStatus = status)
syncMetadataRepository.updateMetadata(metadata)
}
@@ -698,6 +2069,86 @@ class SyncManager @Inject constructor(
}
}
+ private suspend fun fetchXtreamVodCategories(provider: Provider): List<XtreamCategory>? {
+ return runCatching {
+ retryTransient {
+ xtreamCatalogApiService.getVodCategories(
+ XtreamUrlFactory.buildPlayerApiUrl(
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ action = "get_vod_categories"
+ )
+ )
+ }
+ }.onFailure { error ->
+ Log.w(TAG, "Xtream VOD categories request failed for provider ${provider.id}: ${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}")
+ }.getOrNull()
+ }
+
+ private fun strategyWarnings(result: CatalogStrategyResult<*>): List<String> = when (result) {
+ is CatalogStrategyResult.Success -> result.warnings
+ is CatalogStrategyResult.Partial -> result.warnings
+ is CatalogStrategyResult.Failure -> result.warnings
+ is CatalogStrategyResult.EmptyValid -> result.warnings
+ }
+
+ private fun <T> shouldDowngradeCategorySync(
+ totalCategories: Int,
+ failures: Int,
+ fastFailures: Int,
+ outcomes: List<CategoryFetchOutcome<T>>
+ ): Boolean {
+ if (totalCategories <= 1) return false
+ val failureRatio = failures.toFloat() / totalCategories.toFloat()
+ val firstWindow = outcomes.take(minOf(4, outcomes.size))
+ val firstWindowFailures = firstWindow.count { outcome ->
+ outcome is CategoryFetchOutcome.Failure && shouldRememberSequentialPreference(outcome.error)
+ }
+ return failureRatio >= 0.75f ||
+ fastFailures >= minOf(3, totalCategories) ||
+ firstWindowFailures >= minOf(3, firstWindow.size)
+ }
+
+ private fun shouldRememberSequentialPreference(error: Throwable): Boolean {
+ return error is XtreamAuthenticationException ||
+ error is XtreamParsingException ||
+ (error is XtreamRequestException && error.statusCode in setOf(403, 429)) ||
+ (error is XtreamNetworkException && error.message.orEmpty().contains("reset", ignoreCase = true))
+ }
+
+ private fun paginationParamsForPage(page: Int): Map<String, String> {
+ return mapOf(
+ "page" to page.toString(),
+ "limit" to XTREAM_CATALOG_PAGE_SIZE.toString(),
+ "offset" to ((page - 1) * XTREAM_CATALOG_PAGE_SIZE).toString(),
+ "items_per_page" to XTREAM_CATALOG_PAGE_SIZE.toString()
+ )
+ }
+
+ private suspend fun rateLimitXtreamCatalogRequest() {
+ delay(250L)
+ }
+
+ private fun updateMovieProviderAdaptation(
+ previousRemembered: Boolean,
+ previousHealthyStreak: Int,
+ sawSequentialStress: Boolean
+ ): MovieProviderAdaptation {
+ if (sawSequentialStress) {
+ return MovieProviderAdaptation(rememberSequential = true, healthyStreak = 0)
+ }
+ if (!previousRemembered) {
+ return MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ }
+ val nextHealthyStreak = (previousHealthyStreak + 1).coerceAtMost(2)
+ return if (nextHealthyStreak >= 2) {
+ MovieProviderAdaptation(rememberSequential = false, healthyStreak = 0)
+ } else {
+ MovieProviderAdaptation(rememberSequential = true, healthyStreak = nextHealthyStreak)
+ }
+ }
+
private fun stableId(
providerId: Long,
tvgId: String?,
@@ -711,6 +2162,67 @@ class SyncManager @Inject constructor(
}
}
+ private fun buildFallbackMovieCategories(providerId: Long, movies: List<Movie>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.MOVIE,
+ items = movies,
+ categoryId = { movie -> movie.categoryId },
+ categoryName = { movie -> movie.categoryName },
+ isAdult = { movie -> movie.isAdult }
+ )
+ }
+
+ private fun buildFallbackLiveCategories(providerId: Long, channels: List<Channel>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.LIVE,
+ items = channels,
+ categoryId = { channel -> channel.categoryId },
+ categoryName = { channel -> channel.categoryName ?: channel.groupTitle },
+ isAdult = { channel -> channel.isAdult }
+ )
+ }
+
+ private fun buildFallbackSeriesCategories(providerId: Long, series: List<Series>): List<CategoryEntity> {
+ return buildFallbackCategories(
+ providerId = providerId,
+ type = ContentType.SERIES,
+ items = series,
+ categoryId = { item -> item.categoryId },
+ categoryName = { item -> item.categoryName },
+ isAdult = { item -> item.isAdult }
+ )
+ }
+
+ private fun <T> buildFallbackCategories(
+ providerId: Long,
+ type: ContentType,
+ items: List<T>,
+ categoryId: (T) -> Long?,
+ categoryName: (T) -> String?,
+ isAdult: (T) -> Boolean
+ ): List<CategoryEntity> {
+ return items
+ .asSequence()
+ .mapNotNull { item ->
+ val resolvedCategoryId = categoryId(item) ?: return@mapNotNull null
+ val resolvedCategoryName = categoryName(item)?.trim().takeUnless { it.isNullOrEmpty() }
+ ?: "Category $resolvedCategoryId"
+ CategoryEntity(
+ categoryId = resolvedCategoryId,
+ name = resolvedCategoryName,
+ parentId = 0,
+ type = type,
+ providerId = providerId,
+ isAdult = isAdult(item) || AdultContentClassifier.isAdultCategoryName(resolvedCategoryName)
+ )
+ }
+ .distinctBy { it.categoryId }
+ .sortedBy { it.name.lowercase() }
+ .toList()
+ }
+
/** Delegates to M3uParser to avoid duplicate logic. */
internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean = M3uParser.isVodEntry(entry)
@@ -735,6 +2247,19 @@ class SyncManager @Inject constructor(
}.getOrDefault("<redacted>")
}
+ private fun sanitizeThrowableMessage(error: Throwable?): String {
+ return sanitizeLogMessage(error?.message)
+ }
+
+ private fun sanitizeLogMessage(message: String?): String {
+ if (message.isNullOrBlank()) {
+ return "<empty>"
+ }
+ return message
+ .replace(Regex("""https?://\S+""", RegexOption.IGNORE_CASE), "<redacted-url>")
+ .replace(Regex("""([?&](username|password|token)=[^&\s]+)""", RegexOption.IGNORE_CASE), "<redacted-param>")
+ }
+
private suspend fun <T> retryTransient(
maxAttempts: Int = 3,
initialDelayMs: Long = 700L,
@@ -761,6 +2286,29 @@ class SyncManager @Inject constructor(
throw lastError ?: IllegalStateException("Unknown sync retry failure")
}
+ private suspend fun <T> retryXtreamCatalogTransient(block: suspend () -> T): T {
+ var attempt = 0
+ var delayMs = 1_000L
+ var lastError: Throwable? = null
+
+ while (attempt < 3) {
+ try {
+ return block()
+ } catch (t: Throwable) {
+ lastError = t
+ attempt++
+ if (attempt >= 3 || !isXtreamCatalogRetryable(t, attempt)) {
+ throw t
+ }
+ val jitterMs = Random.nextLong(0L, (delayMs / 3L).coerceAtLeast(1L) + 1L)
+ delay(delayMs + jitterMs)
+ delayMs = (delayMs * 2).coerceAtMost(8_000L)
+ }
+ }
+
+ throw lastError ?: IllegalStateException("Unknown Xtream catalog retry failure")
+ }
+
private fun isRetryable(error: Throwable): Boolean {
if (error is XtreamAuthenticationException) return false
if (error is XtreamParsingException) return false
@@ -777,8 +2325,57 @@ class SyncManager @Inject constructor(
message.contains("network")
}
+ private fun isXtreamCatalogRetryable(error: Throwable, attempt: Int): Boolean {
+ return when (error) {
+ is XtreamAuthenticationException -> false
+ is XtreamParsingException -> attempt == 1
+ is XtreamRequestException -> error.statusCode == 408 || error.statusCode == 409 || error.statusCode in 500..599
+ is XtreamNetworkException -> true
+ is IOException -> true
+ else -> isRetryable(error)
+ }
+ }
+
companion object {
private const val PROGRESS_INTERVAL = 5_000
+ private const val XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY = 2
+ }
+
+ private fun xtreamCategorySyncConcurrency(categoryCount: Int): Int {
+ return categoryCount
+ .coerceAtLeast(1)
+ .coerceAtMost(XTREAM_CATEGORY_SYNC_MAX_CONCURRENCY)
+ }
+
+ private fun createXtreamSyncProvider(provider: Provider): XtreamProvider {
+ return XtreamProvider(
+ providerId = provider.id,
+ api = xtreamCatalogApiService,
+ serverUrl = provider.serverUrl,
+ username = provider.username,
+ password = provider.password,
+ allowedOutputFormats = provider.allowedOutputFormats
+ )
+ }
+
+ private fun logXtreamCatalogFallback(
+ provider: Provider,
+ section: String,
+ stage: String,
+ elapsedMs: Long,
+ itemCount: Int?,
+ error: Throwable?,
+ nextStep: String
+ ) {
+ val reason = when {
+ error != null -> "${error::class.java.simpleName}: ${sanitizeThrowableMessage(error)}"
+ itemCount == 0 -> "empty result"
+ else -> "no usable data"
+ }
+ Log.w(
+ TAG,
+ "Xtream $section $stage failed for provider ${provider.id} after ${elapsedMs}ms ($reason). Switching to $nextStep."
+ )
}
private fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
index b213e0bb..881d8e94 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncWorker.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.sync
import android.content.Context
+import android.database.sqlite.SQLiteException
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
@@ -35,7 +36,16 @@ class SyncWorker(
Result.success()
} catch (e: Exception) {
Log.e("SyncWorker", "Failed to run data maintenance", e)
- Result.retry()
+ if (shouldRetry(e)) Result.retry() else Result.failure()
+ }
+ }
+
+ private fun shouldRetry(error: Throwable): Boolean {
+ return when (error) {
+ is java.io.IOException -> true
+ is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||
+ error.message.orEmpty().contains("busy", ignoreCase = true)
+ else -> false
}
}
}
diff --git a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
index 4f47a466..f745903e 100644
--- a/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
+++ b/data/src/main/java/com/streamvault/data/util/UrlSecurityPolicy.kt
@@ -5,6 +5,7 @@ import java.util.Locale
object UrlSecurityPolicy {
private val secureRemoteSchemes = setOf("https")
+ private val xtreamServerSchemes = setOf("http", "https")
private val localSchemes = setOf("file", "content")
// IPTV stream/asset URLs may legitimately use plain HTTP or RTSP
private val streamEntrySchemes = setOf("http", "https", "rtsp", "rtsps", "rtmp", "file", "content")
@@ -20,10 +21,18 @@ object UrlSecurityPolicy {
!containsNewlines(url) && hasAllowedScheme(url, streamEntrySchemes)
fun validateXtreamServerUrl(url: String): String? {
- return if (isSecureRemoteUrl(url)) {
+ return if (!containsNewlines(url) && hasAllowedScheme(url, xtreamServerSchemes)) {
null
} else {
- "Only HTTPS Xtream server URLs are supported."
+ "Xtream server URLs must use HTTP or HTTPS."
+ }
+ }
+
+ fun validateXtreamEpgUrl(url: String): String? {
+ return if (!containsNewlines(url) && hasAllowedScheme(url, xtreamServerSchemes)) {
+ null
+ } else {
+ "Xtream EPG URLs must use HTTP or HTTPS."
}
}
diff --git a/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt
index af617850..b7bec86d 100644
--- a/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt
+++ b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt
@@ -39,6 +39,7 @@ class EntityMappersTest {
maxConnections = 3,
expirationDate = 1_798_761_600_000L, // 2027-01-01 UTC as epoch ms
apiVersion = "2.0.1",
+ allowedOutputFormats = listOf("m3u8", "ts"),
status = ProviderStatus.ACTIVE,
lastSyncedAt = 1_700_000_000_000L,
createdAt = 1_600_000_000_000L
@@ -58,6 +59,7 @@ class EntityMappersTest {
assertThat(roundTripped.maxConnections).isEqualTo(original.maxConnections)
assertThat(roundTripped.expirationDate).isEqualTo(original.expirationDate)
assertThat(roundTripped.apiVersion).isEqualTo(original.apiVersion)
+ assertThat(roundTripped.allowedOutputFormats).containsExactlyElementsIn(original.allowedOutputFormats).inOrder()
assertThat(roundTripped.status).isEqualTo(original.status)
assertThat(roundTripped.lastSyncedAt).isEqualTo(original.lastSyncedAt)
assertThat(roundTripped.createdAt).isEqualTo(original.createdAt)
@@ -108,6 +110,7 @@ class EntityMappersTest {
assertThat(roundTripped.qualityOptions).containsExactly(
ChannelQualityOption(label = "1080p", height = 1080, url = "http://stream.example.com/99_1080.ts")
)
+ assertThat(roundTripped.alternativeStreams).containsExactly("http://stream.example.com/99_1080.ts")
}
// ── Movie ─────────────────────────────────────────────────────
diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt
index 1ccefb8b..bcde66b4 100644
--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamProviderTest.kt
@@ -39,6 +39,29 @@ class XtreamProviderTest {
assertThat(parseXtreamExpirationDate("Unlimited")).isEqualTo(Long.MAX_VALUE)
}
+ @Test
+ fun `authenticate normalizes allowed output formats`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(
+ authResponse = XtreamAuthResponse(
+ userInfo = XtreamUserInfo(
+ auth = 1,
+ allowedOutputFormats = listOf("TS", "m3u8", " ts ")
+ ),
+ serverInfo = XtreamServerInfo()
+ )
+ ),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val authenticated = provider.authenticate().getOrNull()
+
+ assertThat(authenticated?.allowedOutputFormats).containsExactly("ts", "m3u8").inOrder()
+ }
+
@Test
fun `getLiveStreams preserves live container extension in internal url`() = runBlocking {
val provider = XtreamProvider(
@@ -66,6 +89,60 @@ class XtreamProviderTest {
)
}
+ @Test
+ fun `getLiveStreams prefers hls and keeps ts fallback when both output formats are allowed`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(
+ liveStreams = listOf(
+ XtreamStream(
+ name = "Live Channel",
+ streamId = 777
+ )
+ )
+ ),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass",
+ allowedOutputFormats = listOf("ts", "m3u8")
+ )
+
+ val channel = provider.getLiveStreams().getOrNull().orEmpty().single()
+
+ assertThat(channel.streamUrl).isEqualTo("xtream://42/live/777?ext=m3u8")
+ assertThat(channel.alternativeStreams).containsExactly("xtream://42/live/777?ext=ts")
+ assertThat(channel.qualityOptions.map { it.label to it.url }).containsExactly(
+ "HLS" to "xtream://42/live/777?ext=m3u8",
+ "MPEG-TS" to "xtream://42/live/777?ext=ts"
+ ).inOrder()
+ }
+
+ @Test
+ fun `buildCatchUpUrls includes xtream route and php fallbacks for preferred formats`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass",
+ allowedOutputFormats = listOf("m3u8", "ts")
+ )
+
+ val urls = provider.buildCatchUpUrls(
+ streamId = 777,
+ start = 1_710_000_000L,
+ end = 1_710_003_600L
+ )
+
+ assertThat(urls).containsAtLeast(
+ "https://example.com/timeshift/user/pass/60/2024-03-09%3A16-00/777.m3u8",
+ "https://example.com/timeshifts/user/pass/60/777/2024-03-09%3A16-00.m3u8",
+ "https://example.com/streaming/timeshift.php?username=user&password=pass&stream=777&start=2024-03-09%3A16-00&duration=60&extension=m3u8",
+ "https://example.com/timeshift.php?username=user&password=pass&stream=777&start=2024-03-09%3A16-00&duration=60"
+ )
+ assertThat(urls.first()).isEqualTo("https://example.com/timeshift/user/pass/60/2024-03-09%3A16-00/777.m3u8")
+ }
+
@Test
fun `getVodInfo decodes common xtream metadata fields`() = runBlocking {
val provider = XtreamProvider(
@@ -106,7 +183,83 @@ class XtreamProviderTest {
)
}
+ @Test
+ fun `getVodStreams still loads when category prefetch fails`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = object : XtreamApiService {
+ override suspend fun authenticate(endpoint: String): XtreamAuthResponse =
+ XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())
+
+ override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = emptyList()
+
+ override suspend fun getLiveStreams(endpoint: String): List<XtreamStream> = emptyList()
+
+ override suspend fun getVodCategories(endpoint: String): List<XtreamCategory> {
+ throw XtreamNetworkException("category prefetch failed")
+ }
+
+ override suspend fun getVodStreams(endpoint: String): List<XtreamStream> = listOf(
+ XtreamStream(
+ name = "Action Movie",
+ streamId = 321,
+ categoryId = "vod-action",
+ categoryName = "Action",
+ containerExtension = "mp4"
+ )
+ )
+
+ override suspend fun getVodInfo(endpoint: String): XtreamVodInfoResponse = XtreamVodInfoResponse()
+
+ override suspend fun getSeriesCategories(endpoint: String): List<XtreamCategory> = emptyList()
+
+ override suspend fun getSeriesList(endpoint: String): List<XtreamSeriesItem> = emptyList()
+
+ override suspend fun getSeriesInfo(endpoint: String): XtreamSeriesInfoResponse = XtreamSeriesInfoResponse()
+
+ override suspend fun getShortEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+
+ override suspend fun getFullEpg(endpoint: String): XtreamEpgResponse = XtreamEpgResponse()
+ },
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val movies = provider.getVodStreams().getOrNull().orEmpty()
+
+ assertThat(movies).hasSize(1)
+ assertThat(movies.first().name).isEqualTo("Action Movie")
+ assertThat(movies.first().categoryName).isEqualTo("Action")
+ assertThat(movies.first().categoryId).isNotNull()
+ }
+
+ @Test
+ fun `getVodStreams honors explicit adult flag from xtream payload`() = runBlocking {
+ val provider = XtreamProvider(
+ providerId = 42,
+ api = FakeXtreamApiService(
+ vodStreams = listOf(
+ XtreamStream(
+ name = "Movie",
+ streamId = 55,
+ categoryName = "Cinema",
+ isAdult = true
+ )
+ )
+ ),
+ serverUrl = "https://example.com",
+ username = "user",
+ password = "pass"
+ )
+
+ val movie = provider.getVodStreams().getOrNull().orEmpty().single()
+
+ assertThat(movie.isAdult).isTrue()
+ }
+
private class FakeXtreamApiService(
+ private val authResponse: XtreamAuthResponse = XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo()),
private val liveCategories: List<XtreamCategory> = emptyList(),
private val liveStreams: List<XtreamStream> = emptyList(),
private val vodCategories: List<XtreamCategory> = emptyList(),
@@ -119,7 +272,7 @@ class XtreamProviderTest {
private val fullEpg: XtreamEpgResponse = XtreamEpgResponse()
) : XtreamApiService {
override suspend fun authenticate(endpoint: String): XtreamAuthResponse {
- return XtreamAuthResponse(XtreamUserInfo(auth = 1), XtreamServerInfo())
+ return authResponse
}
override suspend fun getLiveCategories(endpoint: String): List<XtreamCategory> = liveCategories
diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
index 563e93de..2bfb1388 100644
--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
@@ -5,12 +5,19 @@ import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.FavoriteDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.PlaybackHistoryDao
+import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.entity.FavoriteEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.local.entity.PlaybackHistoryEntity
+import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamStream
+import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.runTest
@@ -18,12 +25,15 @@ import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class MovieRepositoryImplTest {
private val movieDao: MovieDao = mock()
private val categoryDao: CategoryDao = mock()
+ private val providerDao: ProviderDao = mock()
+ private val xtreamApiService: XtreamApiService = mock()
private val preferencesRepository: PreferencesRepository = mock()
private val favoriteDao: FavoriteDao = mock()
private val playbackHistoryDao: PlaybackHistoryDao = mock()
@@ -117,9 +127,49 @@ class MovieRepositoryImplTest {
assertThat(result.map { it.name }).containsExactly("Galaxy Pursuit", "Harbor Escape").inOrder()
}
+ @Test
+ fun `getMoviesByCategory lazily hydrates xtream category when local cache is empty`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))
+ whenever(movieDao.getByCategory(7L, 42L)).thenReturn(flowOf(emptyList()))
+ whenever(providerDao.getById(7L)).thenReturn(
+ ProviderEntity(
+ id = 7L,
+ name = "Xtream",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://example.com",
+ username = "user",
+ password = "pass",
+ status = ProviderStatus.ACTIVE
+ )
+ )
+ whenever(xtreamApiService.getVodCategories(any())).thenReturn(
+ listOf(XtreamCategory(categoryId = "42", categoryName = "Action"))
+ )
+ whenever(xtreamApiService.getVodStreams(any())).thenReturn(
+ listOf(
+ XtreamStream(
+ streamId = 101L,
+ name = "Movie",
+ categoryId = "42",
+ streamIcon = null,
+ containerExtension = "mp4"
+ )
+ )
+ )
+
+ val repository = createRepository()
+
+ repository.getMoviesByCategory(7L, 42L).first()
+
+ verify(movieDao).replaceCategory(eq(7L), eq(42L), any())
+ }
+
private fun createRepository() = MovieRepositoryImpl(
movieDao = movieDao,
categoryDao = categoryDao,
+ providerDao = providerDao,
+ xtreamApiService = xtreamApiService,
preferencesRepository = preferencesRepository,
favoriteDao = favoriteDao,
playbackHistoryDao = playbackHistoryDao,
@@ -149,4 +199,4 @@ class MovieRepositoryImplTest {
rating = rating,
streamUrl = "https://example.com/$id.m3u8"
)
-}
\ No newline at end of file
+}
diff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
new file mode 100644
index 00000000..ad196bbb
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
@@ -0,0 +1,91 @@
+package com.streamvault.data.repository
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.CategoryDao
+import com.streamvault.data.local.dao.EpisodeDao
+import com.streamvault.data.local.dao.FavoriteDao
+import com.streamvault.data.local.dao.PlaybackHistoryDao
+import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.SeriesDao
+import com.streamvault.data.local.entity.ProviderEntity
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.remote.dto.XtreamCategory
+import com.streamvault.data.remote.dto.XtreamSeriesItem
+import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.mockito.kotlin.any
+import org.mockito.kotlin.eq
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+
+class SeriesRepositoryImplTest {
+
+ private val seriesDao: SeriesDao = mock()
+ private val episodeDao: EpisodeDao = mock()
+ private val categoryDao: CategoryDao = mock()
+ private val favoriteDao: FavoriteDao = mock()
+ private val playbackHistoryDao: PlaybackHistoryDao = mock()
+ private val providerDao: ProviderDao = mock()
+ private val xtreamApiService: XtreamApiService = mock()
+ private val preferencesRepository: PreferencesRepository = mock()
+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver = mock()
+
+ @Test
+ fun `getSeriesByCategory lazily hydrates xtream category when local cache is empty`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))
+ whenever(seriesDao.getByCategory(7L, 77L)).thenReturn(flowOf(emptyList()))
+ whenever(providerDao.getById(7L)).thenReturn(
+ ProviderEntity(
+ id = 7L,
+ name = "Xtream",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://example.com",
+ username = "user",
+ password = "pass",
+ status = ProviderStatus.ACTIVE
+ )
+ )
+ whenever(xtreamApiService.getSeriesCategories(any())).thenReturn(
+ listOf(XtreamCategory(categoryId = "77", categoryName = "Drama"))
+ )
+ whenever(xtreamApiService.getSeriesList(any())).thenReturn(
+ listOf(
+ XtreamSeriesItem(
+ seriesId = 301L,
+ name = "Series",
+ categoryId = "77",
+ cover = null
+ )
+ )
+ )
+ whenever(episodeDao.deleteOrphans()).thenReturn(0)
+
+ val repository = createRepository()
+
+ val result = repository.getSeriesByCategory(7L, 77L).first()
+
+ assertThat(result).isEmpty()
+ verify(seriesDao).replaceCategory(eq(7L), eq(77L), any())
+ verify(episodeDao).deleteOrphans()
+ }
+
+ private fun createRepository() = SeriesRepositoryImpl(
+ seriesDao = seriesDao,
+ episodeDao = episodeDao,
+ categoryDao = categoryDao,
+ favoriteDao = favoriteDao,
+ playbackHistoryDao = playbackHistoryDao,
+ providerDao = providerDao,
+ xtreamApiService = xtreamApiService,
+ preferencesRepository = preferencesRepository,
+ xtreamStreamUrlResolver = xtreamStreamUrlResolver
+ )
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
index 19177aec..ab34dd2d 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -4,11 +4,13 @@ import com.google.common.truth.Truth.assertThat
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
+import com.streamvault.data.local.dao.ProgramDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesDao
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.xtream.XtreamApiService
+import com.streamvault.data.remote.dto.XtreamStream
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.ProviderType
@@ -28,6 +30,7 @@ import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.atLeast
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
@@ -97,6 +100,7 @@ class SyncManagerTest {
private val channelDao: ChannelDao = mock()
private val movieDao: MovieDao = mock()
private val seriesDao: SeriesDao = mock()
+ private val programDao: ProgramDao = mock()
private val categoryDao: CategoryDao = mock()
private val xtreamApi: XtreamApiService = mock()
private val epgRepo: EpgRepository = mock()
@@ -118,6 +122,7 @@ class SyncManagerTest {
channelDao = channelDao,
movieDao = movieDao,
seriesDao = seriesDao,
+ programDao = programDao,
categoryDao = categoryDao,
xtreamApiService = xtreamApi,
m3uParser = M3uParser(),
@@ -204,6 +209,41 @@ class SyncManagerTest {
verify(xtreamApi, never()).getLiveStreams(any())
}
+ @Test
+ fun `sync_xtream_falls_back_to_movie_categories_from_streams`() = runTest {
+ val mgr = buildManager(providerType = ProviderType.XTREAM_CODES)
+ val now = System.currentTimeMillis()
+ syncMetadataRepo.updateMetadata(
+ SyncMetadata(
+ providerId = 1L,
+ lastLiveSync = now,
+ lastSeriesSync = now,
+ lastEpgSync = now
+ )
+ )
+ whenever(xtreamApi.getVodCategories(any())).thenThrow(RuntimeException("categories unavailable"))
+ whenever(xtreamApi.getVodStreams(any())).thenReturn(
+ listOf(
+ XtreamStream(
+ name = "Movie One",
+ streamId = 101,
+ categoryId = "vod-action",
+ categoryName = "Action",
+ containerExtension = "mp4"
+ )
+ )
+ )
+
+ val result = mgr.sync(1L, force = false)
+
+ assertThat(result.isSuccess).isTrue()
+ val categoriesCaptor = argumentCaptor<List<com.streamvault.data.local.entity.CategoryEntity>>()
+ verify(categoryDao).replaceAll(eq(1L), eq("MOVIE"), categoriesCaptor.capture())
+ assertThat(categoriesCaptor.firstValue).hasSize(1)
+ assertThat(categoriesCaptor.firstValue.first().name).isEqualTo("Action")
+ assertThat(categoriesCaptor.firstValue.first().categoryId).isGreaterThan(0L)
+ }
+
@Test
fun `sync_m3u_fileImport_batchesAndDiscoversEpg`() = runTest {
whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
diff --git a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt
index a7a7f107..ec8ea10f 100644
--- a/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt
+++ b/data/src/test/java/com/streamvault/data/util/UrlSecurityPolicyTest.kt
@@ -6,10 +6,19 @@ import org.junit.Test
class UrlSecurityPolicyTest {
@Test
- fun `validateXtreamServerUrl rejects non https endpoints`() {
- assertThat(UrlSecurityPolicy.validateXtreamServerUrl("http://provider.example.com"))
- .isEqualTo("Only HTTPS Xtream server URLs are supported.")
+ fun `validateXtreamServerUrl allows http and https endpoints`() {
+ assertThat(UrlSecurityPolicy.validateXtreamServerUrl("http://provider.example.com")).isNull()
assertThat(UrlSecurityPolicy.validateXtreamServerUrl("https://provider.example.com")).isNull()
+ assertThat(UrlSecurityPolicy.validateXtreamServerUrl("ftp://provider.example.com"))
+ .isEqualTo("Xtream server URLs must use HTTP or HTTPS.")
+ }
+
+ @Test
+ fun `validateXtreamEpgUrl allows http and https endpoints`() {
+ assertThat(UrlSecurityPolicy.validateXtreamEpgUrl("http://provider.example.com/xmltv.php")).isNull()
+ assertThat(UrlSecurityPolicy.validateXtreamEpgUrl("https://provider.example.com/xmltv.php")).isNull()
+ assertThat(UrlSecurityPolicy.validateXtreamEpgUrl("file:///storage/emulated/0/guide.xml"))
+ .isEqualTo("Xtream EPG URLs must use HTTP or HTTPS.")
}
@Test
@@ -33,4 +42,4 @@ class UrlSecurityPolicyTest {
assertThat(UrlSecurityPolicy.sanitizeImportedAssetUrl("https://example.com/logo.png"))
.isEqualTo("https://example.com/logo.png")
}
-}
\ No newline at end of file
+}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
index fa321f35..802e21ea 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
@@ -13,6 +13,7 @@ data class Provider(
val maxConnections: Int = 1,
val expirationDate: Long? = null,
val apiVersion: String? = null,
+ val allowedOutputFormats: List<String> = emptyList(),
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/SyncMetadata.kt b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
index 39e8eab6..d8177d3e 100644
--- a/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/SyncMetadata.kt
@@ -1,21 +1,39 @@
package com.streamvault.domain.model
+enum class VodSyncMode {
+ UNKNOWN,
+ FULL,
+ CATEGORY_BULK,
+ PAGED,
+ LAZY_BY_CATEGORY
+}
+
data class SyncMetadata(
val providerId: Long,
val lastLiveSync: Long = 0,
val lastMovieSync: Long = 0,
val lastSeriesSync: Long = 0,
val lastEpgSync: Long = 0,
+ val lastMovieAttempt: Long = 0,
+ val lastMovieSuccess: Long = 0,
+ val lastMoviePartial: Long = 0,
val liveCount: Int = 0,
val movieCount: Int = 0,
val seriesCount: Int = 0,
val epgCount: Int = 0,
- val lastSyncStatus: String = "NONE"
+ val lastSyncStatus: String = "NONE",
+ val movieSyncMode: VodSyncMode = VodSyncMode.UNKNOWN,
+ val movieWarningsCount: Int = 0,
+ val movieCatalogStale: Boolean = false,
+ val movieParallelFailuresRemembered: Boolean = false,
+ val movieHealthySyncStreak: Int = 0
) {
init {
require(liveCount >= 0) { "liveCount must be non-negative" }
require(movieCount >= 0) { "movieCount must be non-negative" }
require(seriesCount >= 0) { "seriesCount must be non-negative" }
require(epgCount >= 0) { "epgCount must be non-negative" }
+ require(movieWarningsCount >= 0) { "movieWarningsCount must be non-negative" }
+ require(movieHealthySyncStreak >= 0) { "movieHealthySyncStreak must be non-negative" }
}
}
diff --git a/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt b/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt
index b9e92e2b..d217ab54 100644
--- a/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt
+++ b/domain/src/main/java/com/streamvault/domain/provider/IptvProvider.kt
@@ -27,4 +27,6 @@ interface IptvProvider {
suspend fun buildStreamUrl(streamId: Long, containerExtension: String? = null): String
suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String?
+ suspend fun buildCatchUpUrls(streamId: Long, start: Long, end: Long): List<String> =
+ listOfNotNull(buildCatchUpUrl(streamId, start, end))
}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
index 230bfa01..13f97343 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
@@ -1,5 +1,6 @@
package com.streamvault.domain.repository
+import com.streamvault.domain.model.Program
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.Result
import kotlinx.coroutines.flow.Flow
@@ -19,5 +20,13 @@ interface ProviderRepository {
force: Boolean = false,
onProgress: ((String) -> Unit)? = null
): Result<Unit>
+ suspend fun getProgramsForLiveStream(
+ providerId: Long,
+ streamId: Long,
+ epgChannelId: String? = null,
+ limit: Int = 12
+ ): Result<List<Program>>
suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String?
+ suspend fun buildCatchUpUrls(providerId: Long, streamId: Long, start: Long, end: Long): List<String> =
+ listOfNotNull(buildCatchUpUrl(providerId, streamId, start, end))
}
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
index 323c47fc..ae8b2a0e 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.usecase
import com.google.common.truth.Truth.assertThat
import com.streamvault.domain.manager.ProviderSyncStateReader
+import com.streamvault.domain.model.Program
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ProviderType
@@ -126,6 +127,13 @@ private class FakeSyncProviderRepository(
return refreshResult
}
+ override suspend fun getProgramsForLiveStream(
+ providerId: Long,
+ streamId: Long,
+ epgChannelId: String?,
+ limit: Int
+ ): Result<List<Program>> = error("Not used in test")
+
override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? = null
}
@@ -136,4 +144,4 @@ private fun syncProviderFixture(status: ProviderStatus = ProviderStatus.ACTIVE)
serverUrl = "https://example.com",
username = "user",
status = status
-)
\ No newline at end of file
+)
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
index 96724dab..95b8e851 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.usecase
import com.google.common.truth.Truth.assertThat
import com.streamvault.domain.manager.ProviderSetupInputValidator
+import com.streamvault.domain.model.Program
import com.streamvault.domain.manager.ValidatedM3uProviderInput
import com.streamvault.domain.manager.ValidatedXtreamProviderInput
import com.streamvault.domain.model.Provider
@@ -199,6 +200,13 @@ private class FakeProviderRepository : ProviderRepository {
onProgress: ((String) -> Unit)?
): Result<Unit> = error("Not used in test")
+ override suspend fun getProgramsForLiveStream(
+ providerId: Long,
+ streamId: Long,
+ epgChannelId: String?,
+ limit: Int
+ ): Result<List<Program>> = error("Not used in test")
+
override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? = null
private fun provider(
@@ -215,4 +223,4 @@ private class FakeProviderRepository : ProviderRepository {
m3uUrl = m3uUrl,
status = ProviderStatus.ACTIVE
)
-}
\ No newline at end of file
+}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index db00356b..ed602e10 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -6,6 +6,7 @@ import android.media.AudioManager
import android.net.Uri
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
+import android.os.Build
import android.graphics.Color as AndroidColor
import android.view.LayoutInflater
import android.view.View
@@ -22,6 +23,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.ScrubbingModeParameters
+import androidx.media3.exoplayer.DefaultLivePlaybackSpeedControl
import androidx.media3.exoplayer.mediacodec.MediaCodecInfo
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
@@ -151,9 +153,12 @@ class Media3PlayerEngine @Inject constructor(
companion object {
private const val TAG = "Media3PlayerEngine"
private const val MAX_RETRIES = 3
- private const val RETRY_BASE_DELAY_MS = 2000L
+ private const val RETRY_BASE_DELAY_MS = 3000L
private const val BANDWIDTH_STATS_MIN_INTERVAL_MS = 1500L
private const val BUFFERED_DURATION_PUBLISH_STEP_MS = 1000L
+ private const val PLAYBACK_CONNECT_TIMEOUT_SECONDS = 15L
+ private const val PLAYBACK_READ_TIMEOUT_SECONDS = 30L
+ private const val PLAYBACK_WRITE_TIMEOUT_SECONDS = 30L
}
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
@@ -174,6 +179,9 @@ class Media3PlayerEngine @Inject constructor(
private val _error = MutableSharedFlow<PlayerError?>(replay = 1)
override val error: Flow<PlayerError?> = _error.asSharedFlow()
+ private val _retryStatus = MutableStateFlow<PlayerRetryStatus?>(null)
+ override val retryStatus: StateFlow<PlayerRetryStatus?> = _retryStatus.asStateFlow()
+
private val _availableAudioTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
override val availableAudioTracks: StateFlow<List<PlayerTrack>> = _availableAudioTracks.asStateFlow()
@@ -235,49 +243,49 @@ class Media3PlayerEngine @Inject constructor(
}
private fun createPlayer(): ExoPlayer {
- // Custom renderers factory that disables video decoder reuse.
- // The emulator's goldfish H264 decoder (and some real HW decoders) produce
- // zoom/crop artefacts when the codec is reused with a flush during ABR
- // bitrate switches. By returning REUSE_RESULT_NO the player creates a
- // fresh decoder for every track switch, which is slightly heavier but
- // eliminates the glitch entirely.
- val renderersFactory = object : DefaultRenderersFactory(context) {
- override fun buildVideoRenderers(
- context: Context,
- extensionRendererMode: Int,
- mediaCodecSelector: MediaCodecSelector,
- enableDecoderFallback: Boolean,
- eventHandler: Handler,
- eventListener: VideoRendererEventListener,
- allowedVideoJoiningTimeMs: Long,
- out: ArrayList<Renderer>
- ) {
- out.add(object : MediaCodecVideoRenderer(
- context,
- mediaCodecSelector,
- allowedVideoJoiningTimeMs,
- enableDecoderFallback,
- eventHandler,
- eventListener,
- 50 // MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY
+ val renderersFactory = (if (shouldDisableVideoDecoderReuseWorkaround()) {
+ // Some emulator-style decoders still misbehave during ABR reuse. Keep the
+ // workaround there, but let real devices reuse decoders for smoother playback.
+ object : DefaultRenderersFactory(context) {
+ override fun buildVideoRenderers(
+ context: Context,
+ extensionRendererMode: Int,
+ mediaCodecSelector: MediaCodecSelector,
+ enableDecoderFallback: Boolean,
+ eventHandler: Handler,
+ eventListener: VideoRendererEventListener,
+ allowedVideoJoiningTimeMs: Long,
+ out: ArrayList<Renderer>
) {
- override fun canReuseCodec(
- codecInfo: MediaCodecInfo,
- oldFormat: Format,
- newFormat: Format
- ): DecoderReuseEvaluation {
- Log.w(TAG, "DECODER_NO_REUSE: ${oldFormat.width}x${oldFormat.height}@${oldFormat.bitrate} -> ${newFormat.width}x${newFormat.height}@${newFormat.bitrate}")
- return DecoderReuseEvaluation(
- codecInfo.name,
- oldFormat,
- newFormat,
- DecoderReuseEvaluation.REUSE_RESULT_NO,
- DecoderReuseEvaluation.DISCARD_REASON_MAX_INPUT_SIZE_EXCEEDED
- )
- }
- })
+ out.add(object : MediaCodecVideoRenderer(
+ context,
+ mediaCodecSelector,
+ allowedVideoJoiningTimeMs,
+ enableDecoderFallback,
+ eventHandler,
+ eventListener,
+ 50 // MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY
+ ) {
+ override fun canReuseCodec(
+ codecInfo: MediaCodecInfo,
+ oldFormat: Format,
+ newFormat: Format
+ ): DecoderReuseEvaluation {
+ Log.w(TAG, "DECODER_NO_REUSE: ${oldFormat.width}x${oldFormat.height}@${oldFormat.bitrate} -> ${newFormat.width}x${newFormat.height}@${newFormat.bitrate}")
+ return DecoderReuseEvaluation(
+ codecInfo.name,
+ oldFormat,
+ newFormat,
+ DecoderReuseEvaluation.REUSE_RESULT_NO,
+ DecoderReuseEvaluation.DISCARD_REASON_MAX_INPUT_SIZE_EXCEEDED
+ )
+ }
+ })
+ }
}
- }.apply {
+ } else {
+ DefaultRenderersFactory(context)
+ }).apply {
setExtensionRendererMode(
when (currentDecoderMode) {
DecoderMode.AUTO -> DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
@@ -287,18 +295,25 @@ class Media3PlayerEngine @Inject constructor(
)
}
- // Tuned for IPTV live streams: aggressive start with comfortable cruise buffer.
- // Low buffer-for-playback gets the first frame on screen sooner during channel zapping.
+ // Slightly longer live buffers trade a bit of zap speed for better stability on
+ // inconsistent IPTV segments, which reduces stutter and audio underruns.
val loadControl = DefaultLoadControl.Builder()
.setBufferDurationsMs(
- 15_000, // min buffer – keep smaller so the player starts faster
- 60_000, // max buffer – comfortable cruise; avoids OOM on 100k playlists
- 500, // buffer for playback – half-second is enough for key-frame start
- 2500 // buffer for rebuffering – recover quickly on network hiccup
+ 30_000,
+ 90_000,
+ 2_500,
+ 10_000
)
.setPrioritizeTimeOverSizeThresholds(true)
.build()
+ // Some live IPTV manifests drift around the live edge. Keeping live-speed correction
+ // pinned at 1.0x avoids pitchy/crackly audio from subtle speed hunting.
+ val livePlaybackSpeedControl = DefaultLivePlaybackSpeedControl.Builder()
+ .setFallbackMinPlaybackSpeed(1.0f)
+ .setFallbackMaxPlaybackSpeed(1.0f)
+ .build()
+
val trackSelector = androidx.media3.exoplayer.trackselection.DefaultTrackSelector(context).apply {
if (constrainResolutionForMultiView) {
parameters = parameters.buildUpon()
@@ -310,6 +325,7 @@ class Media3PlayerEngine @Inject constructor(
return ExoPlayer.Builder(context, renderersFactory)
.setTrackSelector(trackSelector)
.setLoadControl(loadControl)
+ .setLivePlaybackSpeedControl(livePlaybackSpeedControl)
.setSeekBackIncrementMs(10_000)
.setSeekForwardIncrementMs(10_000)
.setAudioAttributes(
@@ -408,6 +424,9 @@ class Media3PlayerEngine @Inject constructor(
else -> PlaybackState.IDLE
}
_playbackState.value = newState
+ if (newState == PlaybackState.READY) {
+ _retryStatus.value = null
+ }
}
override fun onIsPlayingChanged(playing: Boolean) {
@@ -447,10 +466,16 @@ class Media3PlayerEngine @Inject constructor(
Log.w(TAG, "Recoverable error (attempt $retryCount/$MAX_RETRIES), retrying...")
val streamInfoSnapshot = lastStreamInfo
_playerStats.update { it.copy(droppedFrames = 0) }
+ _retryStatus.value = PlayerRetryStatus(
+ attempt = retryCount,
+ maxAttempts = MAX_RETRIES,
+ delayMs = RETRY_BASE_DELAY_MS
+ )
handler.postDelayed({
streamInfoSnapshot?.let { prepare(it) }
- }, retryCount * RETRY_BASE_DELAY_MS)
+ }, RETRY_BASE_DELAY_MS)
} else {
+ _retryStatus.value = null
_error.tryEmit(PlayerError.fromException(error))
_playbackState.value = PlaybackState.ERROR
}
@@ -537,6 +562,7 @@ class Media3PlayerEngine @Inject constructor(
override fun prepare(streamInfo: StreamInfo) {
lastStreamInfo = streamInfo
retryCount = 0
+ _retryStatus.value = null
lastFrameRate = 0f
lastBandwidthStatsUpdateMs = 0L
lastVideoWidth = 0
@@ -596,8 +622,9 @@ class Media3PlayerEngine @Inject constructor(
}
val timeoutClient = okHttpClient.newBuilder()
- .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
- .readTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
+ .connectTimeout(PLAYBACK_CONNECT_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
+ .readTimeout(PLAYBACK_READ_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
+ .writeTimeout(PLAYBACK_WRITE_TIMEOUT_SECONDS, java.util.concurrent.TimeUnit.SECONDS)
.build()
return if (headers.isNotEmpty()) {
@@ -931,6 +958,7 @@ class Media3PlayerEngine @Inject constructor(
exoPlayer?.release()
exoPlayer = null
lastStreamInfo = null
+ _retryStatus.value = null
supervisorJob.cancel()
supervisorJob = SupervisorJob()
scope = CoroutineScope(Dispatchers.Main + supervisorJob)
@@ -1074,6 +1102,17 @@ class Media3PlayerEngine @Inject constructor(
return currentDurationMs == 0L || newDurationMs == 0L || abs(newDurationMs - currentDurationMs) >= BUFFERED_DURATION_PUBLISH_STEP_MS
}
+ private fun shouldDisableVideoDecoderReuseWorkaround(): Boolean {
+ val fingerprint = Build.FINGERPRINT.lowercase(Locale.ROOT)
+ val hardware = Build.HARDWARE.lowercase(Locale.ROOT)
+ val model = Build.MODEL.lowercase(Locale.ROOT)
+ return fingerprint.contains("generic") ||
+ fingerprint.contains("emulator") ||
+ hardware.contains("goldfish") ||
+ hardware.contains("ranchu") ||
+ model.contains("android sdk built for")
+ }
+
private fun stopPolling() {
pollingJob?.cancel()
pollingJob = null
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index f6b766c5..b0e61a49 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -23,6 +23,7 @@ interface PlayerEngine {
val duration: StateFlow<Long>
val videoFormat: StateFlow<VideoFormat>
val error: Flow<PlayerError?>
+ val retryStatus: StateFlow<PlayerRetryStatus?>
val playerStats: StateFlow<PlayerStats>
// Tracks
@@ -76,6 +77,12 @@ interface PlayerEngine {
fun releaseRenderView(renderView: View)
}
+data class PlayerRetryStatus(
+ val attempt: Int,
+ val maxAttempts: Int,
+ val delayMs: Long
+)
+
enum class PlayerSurfaceResizeMode {
FIT,
FILL,