StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Add generic Stalker catalog and playback support
David Nashashb26113ca3974
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 903a2511..6b2f0c58 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -105,7 +105,8 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_61_62,StreamVaultDatabase.MIGRATION_62_63,StreamVaultDatabase.MIGRATION_63_64,- StreamVaultDatabase.MIGRATION_64_65+ StreamVaultDatabase.MIGRATION_64_65,+ StreamVaultDatabase.MIGRATION_65_66)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -132,6 +133,8 @@ object DatabaseModule {@Provides fun provideSyncMetadataDao(db: StreamVaultDatabase): SyncMetadataDao = db.syncMetadataDao()@Provides fun provideMovieCategoryHydrationDao(db: StreamVaultDatabase): MovieCategoryHydrationDao = db.movieCategoryHydrationDao()@Provides fun provideSeriesCategoryHydrationDao(db: StreamVaultDatabase): SeriesCategoryHydrationDao = db.seriesCategoryHydrationDao()+ @Provides fun provideVodCategoryHydrationDao(db: StreamVaultDatabase): VodCategoryHydrationDao = db.vodCategoryHydrationDao()+ @Provides fun provideVodCatalogEntryDao(db: StreamVaultDatabase): VodCatalogEntryDao = db.vodCatalogEntryDao()@Provides fun provideEpgSourceDao(db: StreamVaultDatabase): EpgSourceDao = db.epgSourceDao()@Provides fun provideProviderEpgSourceDao(db: StreamVaultDatabase): ProviderEpgSourceDao = db.providerEpgSourceDao()@Provides fun provideEpgChannelDao(db: StreamVaultDatabase): EpgChannelDao = db.epgChannelDao()diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.ktindex 67d11c48..16fbe1d4 100644--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt@@ -43,6 +43,9 @@ abstract class RepositoryModule {@Binds @Singletonabstract fun bindSeriesRepository(impl: SeriesRepositoryImpl): SeriesRepository+ @Binds @Singleton+ abstract fun bindVodRepository(impl: VodRepositoryImpl): VodRepository+@Binds @Singletonabstract fun bindSearchRepository(impl: SearchRepositoryImpl): SearchRepositorydiff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex 4fb61f3d..e8431442 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -8,6 +8,7 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.produceStateimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleEventObserver@@ -34,6 +35,7 @@ import com.streamvault.app.ui.screens.player.PlayerScreenimport com.streamvault.app.ui.screens.plugins.PluginsScreenimport com.streamvault.app.ui.screens.provider.ProviderSetupScreenimport com.streamvault.app.ui.screens.series.SeriesScreen+import com.streamvault.app.ui.screens.vod.VodScreenimport com.streamvault.app.ui.screens.settings.SettingsScreenimport com.streamvault.app.ui.screens.welcome.WelcomeScreenimport com.streamvault.app.ui.screens.downloads.DownloadsScreen@@ -41,6 +43,7 @@ import com.streamvault.app.MainActivityimport com.streamvault.domain.model.AppLandingDestinationimport com.streamvault.domain.model.AppTopLevelDestinationimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.MovieDetailPresentationHintimport com.streamvault.domain.model.ActiveLiveSourceimport com.streamvault.domain.model.Series@@ -49,6 +52,7 @@ import com.streamvault.domain.model.VirtualCategoryIdsimport java.io.Serializableimport kotlin.coroutines.resumeimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.launchimport kotlinx.coroutines.suspendCancellableCoroutine@@ -61,6 +65,18 @@ private fun requiresResolvedStartupTarget(landingDestination: AppLandingDestinatlandingDestination == AppLandingDestination.FIRST_FAVORITE_LIVE ||landingDestination == AppLandingDestination.LAST_WATCHED_LIVE+internal fun resolveCatalogRoute(+ layout: CatalogLayout?,+ requestedRoute: String,+ lastSplitCatalogType: ContentType,+ splitPreferenceReady: Boolean+): String = when {+ layout != CatalogLayout.SPLIT && requestedRoute in setOf(Routes.MOVIES, Routes.SERIES) -> Routes.VOD+ layout == CatalogLayout.SPLIT && requestedRoute == Routes.VOD && splitPreferenceReady ->+ if (lastSplitCatalogType == ContentType.SERIES) Routes.SERIES else Routes.MOVIES+ else -> requestedRoute+}+data class PlayerNavigationRequest(val streamUrl: String,val title: String,@@ -90,6 +106,7 @@ object Routes {const val LIVE_TV_DESTINATION = "live_tv?categoryId={categoryId}"const val MOVIES = "movies"const val SERIES = "series"+ const val VOD = "vod"const val DOWNLOADS = "downloads"const val EPG = "epg"const val EPG_DESTINATION = "epg?categoryId={categoryId}&anchorTime={anchorTime}&favoritesOnly={favoritesOnly}"@@ -342,6 +359,20 @@ internal fun AppTopLevelDestination.toAppRoute(): String = when (this) {fun AppNavigation(mainActivity: MainActivity) {val navController = rememberNavController()val currentBackStackEntry = navController.currentBackStackEntryAsState().value+ val activeProvider = mainActivity.providerRepository.getActiveProvider()+ .collectAsStateWithLifecycle(initialValue = null)+ .value+ var lastSplitCatalogType by remember(activeProvider?.id) { mutableStateOf(ContentType.MOVIE) }+ var loadedSplitPreferenceProviderId by remember { mutableStateOf<Long?>(null) }+ val navigationScope = rememberCoroutineScope()+ LaunchedEffect(activeProvider?.id) {+ val providerId = activeProvider?.id ?: return@LaunchedEffect+ loadedSplitPreferenceProviderId = null+ lastSplitCatalogType = mainActivity.preferencesRepository+ .getLastSplitCatalogType(providerId)+ .first()+ loadedSplitPreferenceProviderId = providerId+ }val externalNavigationRequest = mainActivity.externalNavigationRequestFlow.collectAsStateWithLifecycle().valueval topLevelDestinations = mainActivity.preferencesRepository.appTopLevelDestinations.collectAsStateWithLifecycle(initialValue = AppTopLevelDestination.defaultOrder)@@ -444,9 +475,26 @@ fun AppNavigation(mainActivity: MainActivity) {val entry = navController.currentBackStackEntry ?: returnif (!entry.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) returnval currentRoute = entry.destination?.route- if (currentRoute == route || currentRoute?.startsWith("$route?") == true) return+ val provider = activeProvider+ if (+ provider?.catalogLayout == com.streamvault.domain.model.CatalogLayout.SPLIT &&+ route in setOf(Routes.MOVIES, Routes.SERIES)+ ) {+ val selectedType = if (route == Routes.SERIES) ContentType.SERIES else ContentType.MOVIE+ lastSplitCatalogType = selectedType+ navigationScope.launch {+ mainActivity.preferencesRepository.setLastSplitCatalogType(provider.id, selectedType)+ }+ }+ val resolvedRoute = resolveCatalogRoute(+ layout = provider?.catalogLayout,+ requestedRoute = route,+ lastSplitCatalogType = lastSplitCatalogType,+ splitPreferenceReady = provider == null || loadedSplitPreferenceProviderId == provider.id+ )+ if (currentRoute == resolvedRoute || currentRoute?.startsWith("$resolvedRoute?") == true) return- navController.navigate(route) {+ navController.navigate(resolvedRoute) {popUpTo(navController.graph.startDestinationId) {saveState = true}@@ -455,6 +503,20 @@ fun AppNavigation(mainActivity: MainActivity) {}}+ LaunchedEffect(activeProvider?.id, activeProvider?.catalogLayout, currentBackStackEntry?.destination?.route) {+ val provider = activeProvider ?: return@LaunchedEffect+ val route = currentBackStackEntry?.destination?.route ?: return@LaunchedEffect+ val resolvedRoute = resolveCatalogRoute(+ layout = provider.catalogLayout,+ requestedRoute = route,+ lastSplitCatalogType = lastSplitCatalogType,+ splitPreferenceReady = loadedSplitPreferenceProviderId == provider.id+ )+ if (resolvedRoute != route) {+ tabNavigate(resolvedRoute)+ }+ }+NavHost(navController = navController,startDestination = Routes.WELCOME@@ -542,7 +604,8 @@ fun AppNavigation(mainActivity: MainActivity) {returnRoute = Routes.HOME)}- com.streamvault.domain.model.ContentType.MOVIE -> {+ com.streamvault.domain.model.ContentType.MOVIE,+ com.streamvault.domain.model.ContentType.VOD -> {Routes.player(streamUrl = history.streamUrl,title = history.title,@@ -635,6 +698,19 @@ fun AppNavigation(mainActivity: MainActivity) {)}+ composable(Routes.VOD) {+ VodScreen(+ onMovieClick = { movie ->+ navController.navigateToMovieDetail(movie, Routes.VOD)+ },+ onSeriesClick = { series ->+ navController.navigateToSeriesDetail(series, Routes.VOD)+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.VOD+ )+ }+composable(Routes.DOWNLOADS) {DownloadsScreen(onNavigate = { route -> tabNavigate(route) },diff --git a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.ktindex b1f3b8a4..158df00b 100644--- a/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt+++ b/app/src/main/java/com/streamvault/app/tv/LauncherRecommendationsManager.kt@@ -340,7 +340,8 @@ class LauncherRecommendationsManager @Inject constructor(}private fun previewProgramType(contentType: ContentType): Int = when (contentType) {- ContentType.MOVIE -> TvContract.PreviewPrograms.TYPE_MOVIE+ ContentType.MOVIE,+ ContentType.VOD -> TvContract.PreviewPrograms.TYPE_MOVIEContentType.SERIES,ContentType.SERIES_EPISODE -> TvContract.PreviewPrograms.TYPE_TV_EPISODEContentType.LIVE -> TvContract.PreviewPrograms.TYPE_CLIP@@ -452,4 +453,4 @@ class LauncherRecommendationsManager @Inject constructor(const val PREVIEW_COLUMN_LAST_PLAYBACK_POSITION_MILLIS = "last_playback_position_millis"const val PREVIEW_COLUMN_DURATION_MILLIS = "duration_millis"}-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.ktindex a22b6a41..96341ffc 100644--- a/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt+++ b/app/src/main/java/com/streamvault/app/tv/WatchNextManager.kt@@ -117,7 +117,8 @@ class WatchNextManager @Inject constructor(}private fun watchNextProgramType(contentType: ContentType): Int = when (contentType) {- ContentType.MOVIE -> TvContract.PreviewPrograms.TYPE_MOVIE+ ContentType.MOVIE,+ ContentType.VOD -> TvContract.PreviewPrograms.TYPE_MOVIEContentType.SERIES,ContentType.SERIES_EPISODE -> TvContract.PreviewPrograms.TYPE_TV_EPISODEContentType.LIVE -> TvContract.PreviewPrograms.TYPE_CLIPdiff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.ktindex 2ad6163d..0c3a366d 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@@ -350,6 +350,7 @@ fun MovieCard(modifier: Modifier = Modifier,onLongClick: (() -> Unit)? = null,isLocked: Boolean = false,+ showTypeBadge: Boolean = false,watchProgress: Float = 0f,isReorderMode: Boolean = false,isDragging: Boolean = false,@@ -413,6 +414,19 @@ fun MovieCard(}if (!isLocked) {+ if (showTypeBadge) {+ StatusPill(+ label = stringResource(R.string.badge_movie),+ containerColor = Color.Black.copy(alpha = 0.72f),+ cornerRadius = 4.dp,+ horizontalPadding = 6.dp,+ verticalPadding = 2.dp,+ modifier = Modifier+ .align(Alignment.BottomStart)+ .padding(start = 8.dp, bottom = 8.dp)+ )+ }+if (movie.rating > 0f) {Box(modifier = Modifier@@ -456,6 +470,7 @@ fun SeriesCard(modifier: Modifier = Modifier,onLongClick: (() -> Unit)? = null,isLocked: Boolean = false,+ showTypeBadge: Boolean = false,watchProgress: Float = 0f,subtitle: String? = null,isReorderMode: Boolean = false,@@ -523,6 +538,19 @@ fun SeriesCard(}if (!isLocked) {+ if (showTypeBadge) {+ StatusPill(+ label = stringResource(R.string.badge_series),+ containerColor = Color.Black.copy(alpha = 0.72f),+ cornerRadius = 4.dp,+ horizontalPadding = 6.dp,+ verticalPadding = 2.dp,+ modifier = Modifier+ .align(Alignment.BottomStart)+ .padding(start = 8.dp, bottom = 8.dp)+ )+ }+if (series.rating > 0f) {Box(modifier = Modifierdiff --git a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.ktindex 2a44773f..2189da5f 100644--- a/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/ContinueWatchingRow.kt@@ -108,7 +108,8 @@ private fun ContinueWatchingTile(Text(text = when (history.contentType) {ContentType.LIVE -> stringResource(R.string.card_live_badge)- ContentType.MOVIE -> stringResource(R.string.nav_movies)+ ContentType.MOVIE,+ ContentType.VOD -> stringResource(R.string.nav_vod)ContentType.SERIES, ContentType.SERIES_EPISODE -> stringResource(R.string.nav_series)},style = MaterialTheme.typography.titleLarge,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.ktindex 732bcd08..d6bd1693 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@@ -86,6 +86,7 @@ import com.streamvault.app.ui.interaction.TvIconButtonimport com.streamvault.app.ui.design.LocalAppShapesimport com.streamvault.app.ui.design.LocalAppSpacingimport com.streamvault.domain.model.AppTopLevelDestination+import com.streamvault.domain.model.CatalogLayoutenum class AppNavigationChrome {Rail,@@ -843,6 +844,26 @@ private fun findActiveDestinationItem(private fun buildDestinationItems(): List<DestinationItem> =AppTopLevelDestination.defaultOrder.map { it.toDestinationItem() }+private fun buildDestinationItems(+ configured: List<AppTopLevelDestination>,+ layout: CatalogLayout+): List<DestinationItem> {+ if (layout == CatalogLayout.SPLIT) return configured.map { it.toDestinationItem() }+ var insertedVod = false+ return buildList {+ configured.forEach { destination ->+ when (destination) {+ AppTopLevelDestination.MOVIES,+ AppTopLevelDestination.SERIES -> if (!insertedVod) {+ add(DestinationItem(Routes.VOD, R.string.nav_vod, Icons.Default.Star))+ insertedVod = true+ }+ else -> add(destination.toDestinationItem())+ }+ }+ }+}+@Composableprivate fun rememberDestinationItems(): List<DestinationItem> {val context = LocalContext.current@@ -851,8 +872,13 @@ private fun rememberDestinationItems(): List<DestinationItem> {?.collectAsStateWithLifecycle(initialValue = AppTopLevelDestination.defaultOrder)?.value?: AppTopLevelDestination.defaultOrder- return remember(configuredDestinations) {- configuredDestinations.map { it.toDestinationItem() }+ val catalogLayout = mainActivity?.providerRepository?.getActiveProvider()+ ?.collectAsStateWithLifecycle(initialValue = null)+ ?.value+ ?.catalogLayout+ ?: CatalogLayout.SPLIT+ return remember(configuredDestinations, catalogLayout) {+ buildDestinationItems(configuredDestinations, catalogLayout)}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.ktindex fb466eac..be790680 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt@@ -657,7 +657,8 @@ class DashboardViewModel @Inject constructor(val resumeItem = continueWatching.firstOrNull()if (resumeItem != null) {val detail = when (resumeItem.contentType) {- ContentType.MOVIE -> appContext.getString(R.string.dashboard_resume_movie)+ ContentType.MOVIE,+ ContentType.VOD -> appContext.getString(R.string.dashboard_resume_movie)ContentType.SERIES -> appContext.getString(R.string.dashboard_resume_series)ContentType.SERIES_EPISODE -> {if (resumeItem.seasonNumber != null && resumeItem.episodeNumber != null) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.ktindex 16583aa2..c1270ac6 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt@@ -503,6 +503,7 @@ fun FavoritesScreen(ContentType.LIVE -> viewModel.selectPreset(SavedLibraryPreset.LIVE_RECALL)ContentType.MOVIE -> viewModel.selectPreset(SavedLibraryPreset.MOVIES)ContentType.SERIES -> viewModel.selectPreset(SavedLibraryPreset.SERIES)+ ContentType.VOD,ContentType.SERIES_EPISODE -> Unit}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.ktindex 46a3ae57..de1b169a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt@@ -634,6 +634,7 @@ class FavoritesViewModel @Inject constructor()}+ ContentType.VOD,ContentType.SERIES_EPISODE -> null}}@@ -691,7 +692,8 @@ class FavoritesViewModel @Inject constructor(history = entry,title = entry.title,subtitle = when (entry.contentType) {- ContentType.MOVIE -> appContext.getString(R.string.favorites_content_type_movie)+ ContentType.MOVIE,+ ContentType.VOD -> appContext.getString(R.string.nav_vod)ContentType.SERIES -> appContext.getString(R.string.favorites_content_type_series)ContentType.SERIES_EPISODE -> buildString {val s = entry.seasonNumber@@ -743,6 +745,7 @@ class FavoritesViewModel @Inject constructor(get() = when (this) {ContentType.LIVE -> "Live"ContentType.MOVIE -> "Movie"+ ContentType.VOD -> "VOD"ContentType.SERIES -> "Series"ContentType.SERIES_EPISODE -> "Episode"}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.ktindex 5f176e46..09957884 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@@ -737,7 +737,8 @@ private fun MoviesVodContent(gridState = modernGridState,enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,canLoadMore = uiState.canLoadMoreSelectedCategory,- isLoading = uiState.isLoadingSelectedCategory,+ isLoading = uiState.isLoadingSelectedCategory || uiState.isLoadingMoreSelectedCategory,+ prefetchDistance = uiState.selectedCategoryRawPageSize.coerceAtLeast(6),onLoadMore = onLoadMore)LazyVerticalGrid(@@ -895,7 +896,7 @@ private fun MoviesVodContent()}}- if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory && !uiState.isLoadingMoreSelectedCategory &&!uiState.vodInfiniteScroll && !uiState.isReorderMode) {item(key = "load_next_movie_batch", span = { GridItemSpan(maxLineSpan) }) {@@ -1173,7 +1174,8 @@ private fun MoviesVodClassicContent(gridState = classicGridState,enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,canLoadMore = uiState.canLoadMoreSelectedCategory,- isLoading = uiState.isLoadingSelectedCategory,+ isLoading = uiState.isLoadingSelectedCategory || uiState.isLoadingMoreSelectedCategory,+ prefetchDistance = uiState.selectedCategoryRawPageSize.coerceAtLeast(6),onLoadMore = onLoadMore)LazyVerticalGrid(@@ -1241,7 +1243,7 @@ private fun MoviesVodClassicContent()}}- if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory && !uiState.isLoadingMoreSelectedCategory &&!uiState.vodInfiniteScroll && !uiState.isReorderMode) {item(key = "load_next_movie_batch_classic", span = { GridItemSpan(maxLineSpan) }) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.ktindex 64907761..ba7f2732 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt@@ -17,6 +17,7 @@ import com.streamvault.domain.model.Movieimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.VodCategoryHydrationRequestimport com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepository@@ -58,6 +59,7 @@ import kotlinx.coroutines.flow.filterNotNullimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch@@ -103,6 +105,8 @@ class MoviesViewModel @Inject constructor(private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)private val _previewBatchSize = MutableStateFlow(INITIAL_PREVIEW_BATCH_SIZE)private var activeProviderId: Long? = null+ private var remotePageRequestInFlight = false+ private var initialRemoteRequestInFlight = falseprivate data class PreviewLoadResult(val snapshot: MovieCatalogSnapshot,@@ -405,7 +409,7 @@ class MoviesViewModel @Inject constructor(selectedCategoryLoadedCount = snapshot.loadedCount,selectedCategoryTotalCount = snapshot.totalCount,canLoadMoreSelectedCategory = snapshot.canLoadMore,- isLoadingSelectedCategory = false+ isLoadingSelectedCategory = initialRemoteRequestInFlight && snapshot.items.isEmpty())}}@@ -553,6 +557,45 @@ class MoviesViewModel @Inject constructor(isLoadingSelectedCategory = isLoadingSelectedCategory)}+ val providerId = activeProviderId ?: return+ val categoryId = resolveProviderCategoryId(categoryName) ?: return+ initialRemoteRequestInFlight = true+ _uiState.update { it.copy(isLoadingSelectedCategory = true) }+ viewModelScope.launch {+ try {+ movieRepository.requestCategoryHydration(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.OPEN+ )+ } finally {+ initialRemoteRequestInFlight = false+ _uiState.update { it.copy(isLoadingSelectedCategory = false) }+ }+ }++ viewModelScope.launch {+ combine(+ providerRepository.getActiveProvider(),+ _uiState.map { state ->+ state.providerCategories.firstOrNull { it.name == state.selectedCategory }?.id+ }.distinctUntilChanged()+ ) { provider, categoryId -> provider?.id to categoryId }+ .flatMapLatest { (providerId, categoryId) ->+ if (providerId == null || categoryId == null) flowOf(null)+ else movieRepository.observeCategoryHydration(providerId, categoryId)+ }+ .collectLatest { hydration ->+ hydration ?: return@collectLatest+ _uiState.update {+ it.copy(+ isLoadingSelectedCategory = hydration.isInitialLoading || initialRemoteRequestInFlight,+ isLoadingMoreSelectedCategory = hydration.isAppending || remotePageRequestInFlight,+ selectedCategoryRawPageSize = hydration.pageSize+ )+ }+ }+ }}fun selectFullLibraryBrowse() {@@ -560,10 +603,30 @@ class MoviesViewModel @Inject constructor(}fun loadMoreSelectedCategory() {+ val needsRemotePage = _uiState.value.selectedCategoryLoadedCount >=+ _uiState.value.selectedCategoryTotalCountincrementVodSelectedCategoryLoadLimit(canLoadMore = _uiState.value.canLoadMoreSelectedCategory,selectedCategoryLoadLimit = _selectedCategoryLoadLimit)+ if (!needsRemotePage) return+ val providerId = activeProviderId ?: return+ val categoryId = resolveProviderCategoryId(_uiState.value.selectedCategory) ?: return+ if (remotePageRequestInFlight) return+ remotePageRequestInFlight = true+ _uiState.update { it.copy(isLoadingMoreSelectedCategory = true) }+ viewModelScope.launch {+ try {+ movieRepository.requestCategoryHydration(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ } finally {+ remotePageRequestInFlight = false+ _uiState.update { it.copy(isLoadingMoreSelectedCategory = false) }+ }+ }}fun loadMorePreviewRows() {@@ -897,6 +960,15 @@ class MoviesViewModel @Inject constructor(fun enterCategoryReorderMode(category: Category) {dismissCategoryOptions()viewModelScope.launch {+ if (_uiState.value.providerCategories.any { it.id == category.id }) {+ activeProviderId?.let { providerId ->+ movieRepository.requestCategoryHydration(+ providerId,+ category.id,+ VodCategoryHydrationRequest.COMPLETE+ )+ }+ }val moviesInView = loadReorderMovies(category)_uiState.update {it.copy(@@ -1320,6 +1392,8 @@ data class MoviesUiState(val selectedCategoryTotalCount: Int = 0,val canLoadMoreSelectedCategory: Boolean = false,val isLoadingSelectedCategory: Boolean = false,+ val isLoadingMoreSelectedCategory: Boolean = false,+ val selectedCategoryRawPageSize: Int = 0,val searchQuery: String = "",val selectedLibraryFilterType: LibraryFilterType = LibraryFilterType.ALL,val selectedLibrarySortBy: LibrarySortBy = LibrarySortBy.LIBRARY,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.ktindex 785caa23..a0a08f11 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt@@ -99,7 +99,8 @@ internal suspend fun resolvePlayerPlaybackStreamInfo(}}- ContentType.MOVIE -> {+ ContentType.MOVIE,+ ContentType.VOD -> {movieRepository.getMovie(internalContentId)?.let { movie ->fallbackStreamId = movie.streamId.takeIf { it > 0L }fallbackContainerExtension = movie.containerExtensiondiff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.ktindex 8901624c..b49e5032 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerNoticeActions.kt@@ -109,7 +109,11 @@ fun PlayerViewModel.retryStream(streamUrl: String, epgChannelId: String?) {}return}- val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L+ val currentId = if (currentContentType == ContentType.LIVE) {+ if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L+ } else {+ currentContentId+ }prepare(streamUrl = streamUrl,epgChannelId = epgChannelId,@@ -120,6 +124,11 @@ fun PlayerViewModel.retryStream(streamUrl: String, epgChannelId: String?) {combinedProfileId = currentCombinedProfileId,combinedSourceFilterProviderId = currentCombinedSourceFilterProviderId,contentType = currentContentType.name,- title = currentTitle+ title = currentTitle,+ artworkUrl = currentArtworkUrl,+ seriesId = currentSeriesId,+ seasonNumber = currentSeasonNumber,+ episodeNumber = currentEpisodeNumber,+ episodeId = currentStableEpisodeId)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex 3a3c6ce7..930a16a9 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@@ -168,6 +168,7 @@ fun PlayerScreen(val showControls by viewModel.showControls.collectAsStateWithLifecycle()val videoFormat by viewModel.videoFormat.collectAsStateWithLifecycle()val playerError by viewModel.playerError.collectAsStateWithLifecycle()+ val playbackResolutionUiState by viewModel.playbackResolutionUiState.collectAsStateWithLifecycle()val currentProgram by viewModel.currentProgram.collectAsStateWithLifecycle()val nextProgram by viewModel.nextProgram.collectAsStateWithLifecycle()val programHistory by viewModel.programHistory.collectAsStateWithLifecycle()@@ -970,14 +971,39 @@ fun PlayerScreen(}}- // Error overlay- if (playbackState == PlaybackState.ERROR) {+ when (val resolutionState = playbackResolutionUiState) {+ PlaybackResolutionUiState.Resolving -> Box(+ modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.82f)),+ contentAlignment = Alignment.Center+ ) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(14.dp)+ ) {+ CircularProgressIndicator(color = Primary)+ Text("Resolving playback…", color = Color.White)+ }+ }+ is PlaybackResolutionUiState.Failure -> PlayerErrorOverlay(+ playerError = PlayerError.SourceError(resolutionState.message),+ contentType = contentType,+ hasAlternateStream = false,+ hasLastChannel = false,+ onAction = handlePlayerNoticeAction,+ onBack = onBack+ )+ PlaybackResolutionUiState.Idle -> Unit+ }++ // Engine error overlay+ if (playbackResolutionUiState == PlaybackResolutionUiState.Idle && playbackState == PlaybackState.ERROR) {PlayerErrorOverlay(playerError = playerError,contentType = contentType,hasAlternateStream = viewModel.hasAlternateStream(),hasLastChannel = viewModel.hasLastChannel(),- onAction = handlePlayerNoticeAction+ onAction = handlePlayerNoticeAction,+ onBack = onBack)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.ktindex 86983a65..30c6b536 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@@ -248,6 +248,11 @@ class PlayerViewModel @Inject constructor(val playerPreferencesUiState: StateFlow<PlayerPreferencesUiState> = _playerPreferencesUiState.asStateFlow()private val _externalPlaybackUrl = MutableStateFlow("")val externalPlaybackUrl: StateFlow<String> = _externalPlaybackUrl.asStateFlow()+ private val _playbackResolutionUiState = MutableStateFlow<PlaybackResolutionUiState>(+ PlaybackResolutionUiState.Idle+ )+ val playbackResolutionUiState: StateFlow<PlaybackResolutionUiState> =+ _playbackResolutionUiState.asStateFlow()internal var channelInfoHideJob: Job? = nullinternal var liveOverlayHideJob: Job? = null@@ -1449,6 +1454,13 @@ class PlayerViewModel @Inject constructor(archiveStartMs = archiveStartMs,archiveEndMs = archiveEndMs)+ _playbackResolutionUiState.value = if (+ hasArchiveRequest || contentType.equals(ContentType.LIVE.name, ignoreCase = true)+ ) {+ PlaybackResolutionUiState.Idle+ } else {+ PlaybackResolutionUiState.Resolving+ }val requestVersion = beginPlaybackSession()val shouldReloadPlaylist = applyPrepareSessionState(streamUrl = streamUrl,@@ -1519,13 +1531,13 @@ class PlayerViewModel @Inject constructor(if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launchif (streamInfo == null) {if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch- showPlayerNotice(- message = lastResolutionFailureMessage?.takeIf { it.isNotBlank() }- ?: "No playable stream URL was available.",- recoveryType = PlayerRecoveryType.SOURCE+ _playbackResolutionUiState.value = PlaybackResolutionUiState.Failure(+ lastResolutionFailureMessage?.takeIf { it.isNotBlank() }+ ?: "No playable stream URL was available.")return@launch}+ _playbackResolutionUiState.value = PlaybackResolutionUiState.IdlecurrentStreamUrl = playbackLogicalUrlcurrentContentId = playbackContentIdif (!isActivePlaybackSession(requestVersion, playbackLogicalUrl)) return@launchdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.ktindex a46213d9..139ee04e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt@@ -211,7 +211,8 @@ internal suspend fun PlayerViewModel.buildCastRequestResult(): PlayerCastRequest)}- ContentType.MOVIE -> {+ ContentType.MOVIE,+ ContentType.VOD -> {val movie = movieRepository.getMovie(currentContentId)val repositoryStreamInfo = movie?.let { movieRepository.getStreamInfo(it).getOrNull() }val streamInfo = selectPreferredVodCastStreamInfo(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.ktindex b26254a9..d7fdd4f9 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelModels.kt@@ -216,6 +216,12 @@ enum class PlayerNoticeAction {OPEN_GUIDE}+sealed interface PlaybackResolutionUiState {+ data object Idle : PlaybackResolutionUiState+ data object Resolving : PlaybackResolutionUiState+ data class Failure(val message: String) : PlaybackResolutionUiState+}+enum class AspectRatio(val modeName: String) {FIT("Fit"),FILL("Stretch"),diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.ktindex 8ce7f643..503bafb0 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt@@ -162,6 +162,7 @@ fun PlayerErrorOverlay(hasAlternateStream: Boolean,hasLastChannel: Boolean,onAction: (PlayerNoticeAction) -> Unit,+ onBack: (() -> Unit)? = null,modifier: Modifier = Modifier) {val fallbackMessage = when (playerError) {@@ -218,6 +219,22 @@ fun PlayerErrorOverlay()}}+ onBack?.let { back ->+ TvClickableSurface(+ onClick = back,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.18f)+ )+ ) {+ Text(+ text = "Back",+ color = Color.White,+ modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)+ )+ }+ }}Spacer(modifier = Modifier.height(8.dp))Text(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.ktindex eda23d11..0cabbde4 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@@ -744,7 +744,8 @@ private fun SeriesVodContent(gridState = modernGridState,enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,canLoadMore = uiState.canLoadMoreSelectedCategory,- isLoading = uiState.isLoadingSelectedCategory,+ isLoading = uiState.isLoadingSelectedCategory || uiState.isLoadingMoreSelectedCategory,+ prefetchDistance = uiState.selectedCategoryRawPageSize.coerceAtLeast(6),onLoadMore = onLoadMore)LazyVerticalGrid(@@ -902,7 +903,7 @@ private fun SeriesVodContent()}}- if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory && !uiState.isLoadingMoreSelectedCategory &&!uiState.vodInfiniteScroll && !uiState.isReorderMode) {item(key = "load_next_series_batch", span = { GridItemSpan(maxLineSpan) }) {@@ -1181,7 +1182,8 @@ private fun SeriesVodClassicContent(gridState = classicGridState,enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,canLoadMore = uiState.canLoadMoreSelectedCategory,- isLoading = uiState.isLoadingSelectedCategory,+ isLoading = uiState.isLoadingSelectedCategory || uiState.isLoadingMoreSelectedCategory,+ prefetchDistance = uiState.selectedCategoryRawPageSize.coerceAtLeast(6),onLoadMore = onLoadMore)LazyVerticalGrid(@@ -1249,7 +1251,7 @@ private fun SeriesVodClassicContent()}}- if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory && !uiState.isLoadingMoreSelectedCategory &&!uiState.vodInfiniteScroll && !uiState.isReorderMode) {item(key = "load_next_series_batch_classic", span = { GridItemSpan(maxLineSpan) }) {diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.ktindex 8979742d..2f3d7f0d 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt@@ -16,6 +16,7 @@ import com.streamvault.domain.model.LibrarySortByimport com.streamvault.domain.model.PlaybackHistoryimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.VodCategoryHydrationRequestimport com.streamvault.domain.model.Seriesimport com.streamvault.domain.repository.FavoriteRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepository@@ -58,6 +59,7 @@ import kotlinx.coroutines.flow.filterNotNullimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flatMapLatestimport kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch@@ -103,6 +105,8 @@ class SeriesViewModel @Inject constructor(private val _selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)private val _previewBatchSize = MutableStateFlow(INITIAL_PREVIEW_BATCH_SIZE)private var activeProviderId: Long? = null+ private var remotePageRequestInFlight = false+ private var initialRemoteRequestInFlight = falseprivate data class PreviewLoadResult(val snapshot: SeriesCatalogSnapshot,@@ -396,7 +400,7 @@ class SeriesViewModel @Inject constructor(selectedCategoryLoadedCount = snapshot.loadedCount,selectedCategoryTotalCount = snapshot.totalCount,canLoadMoreSelectedCategory = snapshot.canLoadMore,- isLoadingSelectedCategory = false+ isLoadingSelectedCategory = initialRemoteRequestInFlight && snapshot.items.isEmpty())}}@@ -546,6 +550,45 @@ class SeriesViewModel @Inject constructor(isLoadingSelectedCategory = isLoadingSelectedCategory)}+ val providerId = activeProviderId ?: return+ val categoryId = resolveProviderCategoryId(categoryName) ?: return+ initialRemoteRequestInFlight = true+ _uiState.update { it.copy(isLoadingSelectedCategory = true) }+ viewModelScope.launch {+ try {+ seriesRepository.requestCategoryHydration(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.OPEN+ )+ } finally {+ initialRemoteRequestInFlight = false+ _uiState.update { it.copy(isLoadingSelectedCategory = false) }+ }+ }++ viewModelScope.launch {+ combine(+ providerRepository.getActiveProvider(),+ _uiState.map { state ->+ state.providerCategories.firstOrNull { it.name == state.selectedCategory }?.id+ }.distinctUntilChanged()+ ) { provider, categoryId -> provider?.id to categoryId }+ .flatMapLatest { (providerId, categoryId) ->+ if (providerId == null || categoryId == null) flowOf(null)+ else seriesRepository.observeCategoryHydration(providerId, categoryId)+ }+ .collectLatest { hydration ->+ hydration ?: return@collectLatest+ _uiState.update {+ it.copy(+ isLoadingSelectedCategory = hydration.isInitialLoading || initialRemoteRequestInFlight,+ isLoadingMoreSelectedCategory = hydration.isAppending || remotePageRequestInFlight,+ selectedCategoryRawPageSize = hydration.pageSize+ )+ }+ }+ }}fun selectFullLibraryBrowse() {@@ -553,10 +596,30 @@ class SeriesViewModel @Inject constructor(}fun loadMoreSelectedCategory() {+ val needsRemotePage = _uiState.value.selectedCategoryLoadedCount >=+ _uiState.value.selectedCategoryTotalCountincrementVodSelectedCategoryLoadLimit(canLoadMore = _uiState.value.canLoadMoreSelectedCategory,selectedCategoryLoadLimit = _selectedCategoryLoadLimit)+ if (!needsRemotePage) return+ val providerId = activeProviderId ?: return+ val categoryId = resolveProviderCategoryId(_uiState.value.selectedCategory) ?: return+ if (remotePageRequestInFlight) return+ remotePageRequestInFlight = true+ _uiState.update { it.copy(isLoadingMoreSelectedCategory = true) }+ viewModelScope.launch {+ try {+ seriesRepository.requestCategoryHydration(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ } finally {+ remotePageRequestInFlight = false+ _uiState.update { it.copy(isLoadingMoreSelectedCategory = false) }+ }+ }}fun loadMorePreviewRows() {@@ -890,6 +953,15 @@ class SeriesViewModel @Inject constructor(fun enterCategoryReorderMode(category: Category) {dismissCategoryOptions()viewModelScope.launch {+ if (_uiState.value.providerCategories.any { it.id == category.id }) {+ activeProviderId?.let { providerId ->+ seriesRepository.requestCategoryHydration(+ providerId,+ category.id,+ VodCategoryHydrationRequest.COMPLETE+ )+ }+ }val seriesInView = loadReorderSeries(category)_uiState.update {it.copy(@@ -1322,6 +1394,8 @@ data class SeriesUiState(val selectedCategoryTotalCount: Int = 0,val canLoadMoreSelectedCategory: Boolean = false,val isLoadingSelectedCategory: Boolean = false,+ val isLoadingMoreSelectedCategory: Boolean = false,+ val selectedCategoryRawPageSize: Int = 0,val searchQuery: String = "",val selectedLibraryFilterType: LibraryFilterType = LibraryFilterType.ALL,val selectedLibrarySortBy: LibrarySortBy = LibrarySortBy.LIBRARY,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBrowsingSection.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBrowsingSection.ktindex 59c557b7..093f1290 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBrowsingSection.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBrowsingSection.kt@@ -254,6 +254,19 @@ internal fun LazyListScope.settingsBrowsingSection(value = stringResource(uiState.vodViewMode.labelResId()),onClick = { onShowVodViewModeDialogChange(true) })+ SwitchSettingsRow(+ label = stringResource(R.string.settings_vod_complete_on_open),+ value = stringResource(+ if (uiState.vodCategoryLoadMode == com.streamvault.domain.model.VodCategoryLoadMode.COMPLETE_ON_OPEN) {+ R.string.settings_vod_complete_on_open_on+ } else {+ R.string.settings_vod_complete_on_open_off+ }+ ),+ checked = uiState.vodCategoryLoadMode == com.streamvault.domain.model.VodCategoryLoadMode.COMPLETE_ON_OPEN,+ onCheckedChange = { viewModel.setVodCompleteOnOpen(it) },+ indent = 24.dp+ )SwitchSettingsRow(label = stringResource(R.string.settings_vod_infinite_scroll),value = stringResource(@@ -262,7 +275,6 @@ internal fun LazyListScope.settingsBrowsingSection(),checked = uiState.vodInfiniteScroll,onCheckedChange = { viewModel.setVodInfiniteScroll(it) },- enabled = uiState.vodViewMode == VodViewMode.MODERN,indent = 24.dp)ClickableSettingsRow(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.ktindex 4ffca178..12c18843 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsFormatting.kt@@ -230,7 +230,8 @@ internal fun formatCategorySortModeLabel(mode: CategorySortMode, context: androiinternal fun categoryTypeLabel(type: ContentType, context: android.content.Context): String {return when (type) {ContentType.LIVE -> context.getString(R.string.settings_category_sort_live)- ContentType.MOVIE -> context.getString(R.string.settings_category_sort_movies)+ ContentType.MOVIE,+ ContentType.VOD -> context.getString(R.string.nav_vod)ContentType.SERIES -> context.getString(R.string.settings_category_sort_series)ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_sort_series)}@@ -239,7 +240,8 @@ internal fun categoryTypeLabel(type: ContentType, context: android.content.Conteinternal fun categoryTypeDescription(type: ContentType, context: android.content.Context): String {return when (type) {ContentType.LIVE -> context.getString(R.string.settings_category_type_live_description)- ContentType.MOVIE -> context.getString(R.string.settings_category_type_movies_description)+ ContentType.MOVIE,+ ContentType.VOD -> context.getString(R.string.settings_category_type_movies_description)ContentType.SERIES -> context.getString(R.string.settings_category_type_series_description)ContentType.SERIES_EPISODE -> context.getString(R.string.settings_category_type_series_description)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.ktindex ae0035cf..690ccca2 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceModels.kt@@ -11,6 +11,7 @@ import com.streamvault.domain.model.AppLandingDestinationimport com.streamvault.domain.model.AppTopLevelDestinationimport com.streamvault.domain.model.AudioOutputPreferenceimport com.streamvault.domain.model.Category+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.model.ExternalPlaybackModeimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.DecoderMode@@ -105,6 +106,7 @@ internal data class SettingsPreferenceSnapshot(val groupedChannelLabelMode: GroupedChannelLabelMode,val liveVariantPreferenceMode: LiveVariantPreferenceMode,val vodViewMode: VodViewMode,+ val vodCategoryLoadMode: VodCategoryLoadMode,val vodInfiniteScroll: Boolean,val vodDuplicateHandlingMode: VodDuplicateHandlingMode,val vodVariantPreferenceMode: VodVariantPreferenceMode,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.ktindex 8fb45984..9638284c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsPreferenceSnapshotMapper.kt@@ -70,6 +70,7 @@ internal fun SettingsUiState.applyPreferenceSnapshot(snapshot: SettingsPreferencgroupedChannelLabelMode = snapshot.groupedChannelLabelMode,liveVariantPreferenceMode = snapshot.liveVariantPreferenceMode,vodViewMode = snapshot.vodViewMode,+ vodCategoryLoadMode = snapshot.vodCategoryLoadMode,vodInfiniteScroll = snapshot.vodInfiniteScroll,vodDuplicateHandlingMode = snapshot.vodDuplicateHandlingMode,vodVariantPreferenceMode = snapshot.vodVariantPreferenceMode,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.ktindex b75cea1c..9b249584 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsStateBindings.kt@@ -14,6 +14,7 @@ import com.streamvault.domain.model.AudioOutputPreferenceimport com.streamvault.domain.model.ChannelNumberingModeimport com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.ExternalPlaybackMode+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.model.GroupedChannelLabelModeimport com.streamvault.domain.model.LiveChannelGroupingModeimport com.streamvault.domain.model.LiveVariantPreferenceMode@@ -103,6 +104,7 @@ internal fun observeSettingsPreferenceSnapshot(groupedChannelLabelMode = GroupedChannelLabelMode.HYBRID,liveVariantPreferenceMode = LiveVariantPreferenceMode.BALANCED,vodViewMode = VodViewMode.MODERN,+ vodCategoryLoadMode = VodCategoryLoadMode.PAGED,vodInfiniteScroll = true,vodDuplicateHandlingMode = VodDuplicateHandlingMode.SHOW_ALL,vodVariantPreferenceMode = VodVariantPreferenceMode.BALANCED,@@ -242,6 +244,8 @@ internal fun observeSettingsPreferenceSnapshot(snapshot.copy(liveVariantPreferenceMode = liveVariantPreferenceMode)}.combine(preferencesRepository.vodViewMode) { snapshot, vodViewMode ->snapshot.copy(vodViewMode = VodViewMode.fromStorage(vodViewMode))+ }.combine(preferencesRepository.vodCategoryLoadMode) { snapshot, vodCategoryLoadMode ->+ snapshot.copy(vodCategoryLoadMode = vodCategoryLoadMode)}.combine(preferencesRepository.vodInfiniteScroll) { snapshot, vodInfiniteScroll ->snapshot.copy(vodInfiniteScroll = vodInfiniteScroll)}.combine(preferencesRepository.vodDuplicateHandlingMode) { snapshot, vodDuplicateHandlingMode ->diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.ktindex bd0834c6..88ec0b63 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt@@ -10,6 +10,7 @@ import com.streamvault.domain.manager.DriveSignInRequestimport com.streamvault.domain.manager.DriveSyncStatusimport com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.model.AppHomeDashboardShelfimport com.streamvault.domain.model.AppLandingDestinationimport com.streamvault.domain.model.AppTopLevelDestination@@ -146,6 +147,7 @@ data class SettingsUiState(val groupedChannelLabelMode: GroupedChannelLabelMode = GroupedChannelLabelMode.HYBRID,val liveVariantPreferenceMode: LiveVariantPreferenceMode = LiveVariantPreferenceMode.BALANCED,val vodViewMode: VodViewMode = VodViewMode.MODERN,+ val vodCategoryLoadMode: VodCategoryLoadMode = VodCategoryLoadMode.PAGED,val vodInfiniteScroll: Boolean = true,val vodDuplicateHandlingMode: VodDuplicateHandlingMode = VodDuplicateHandlingMode.SHOW_ALL,val vodVariantPreferenceMode: VodVariantPreferenceMode = VodVariantPreferenceMode.BALANCED,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktindex 98c64ae3..220db949 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@@ -24,6 +24,7 @@ import com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.preferences.PreferencesRepositoryimport com.streamvault.data.sync.SyncManagerimport com.streamvault.data.sync.SyncRepairSection+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.manager.BackupConflictStrategyimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupManager@@ -626,6 +627,14 @@ class SettingsViewModel @Inject constructor(}}+ fun setVodCompleteOnOpen(enabled: Boolean) {+ viewModelScope.launch {+ preferencesRepository.setVodCategoryLoadMode(+ if (enabled) VodCategoryLoadMode.COMPLETE_ON_OPEN else VodCategoryLoadMode.PAGED+ )+ }+ }+fun setVodDuplicateHandlingMode(mode: VodDuplicateHandlingMode) {viewModelScope.launch {preferencesRepository.setVodDuplicateHandlingMode(mode)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.ktindex f2050c82..116a6e37 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt@@ -288,6 +288,7 @@ private fun ContentTypeSelectorRow(private fun contentTypeTabLabel(type: ContentType): String = when (type) {ContentType.LIVE -> stringResource(R.string.nav_live_tv)ContentType.MOVIE -> stringResource(R.string.nav_movies)+ ContentType.VOD -> stringResource(R.string.nav_vod)ContentType.SERIES,ContentType.SERIES_EPISODE -> stringResource(R.string.nav_series)}@@ -649,6 +650,7 @@ private fun TypeBadge(type: ContentType) {val (label, background, contentColor) = when (type) {ContentType.LIVE -> Triple("LIVE", MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.onPrimary)ContentType.MOVIE -> Triple("MOVIE", MaterialTheme.colorScheme.secondary, MaterialTheme.colorScheme.onSecondary)+ ContentType.VOD -> Triple("VOD", MaterialTheme.colorScheme.secondary, MaterialTheme.colorScheme.onSecondary)ContentType.SERIES,ContentType.SERIES_EPISODE -> Triple("SERIES", MaterialTheme.colorScheme.tertiary, MaterialTheme.colorScheme.onTertiary)}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.ktindex 24f7278d..e78471f7 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupViewModel.kt@@ -58,12 +58,14 @@ class ParentalControlGroupViewModel @Inject constructor(private val hiddenCategoriesByType = combine(preferencesRepository.getHiddenCategoryIds(providerId, ContentType.LIVE),preferencesRepository.getHiddenCategoryIds(providerId, ContentType.MOVIE),- preferencesRepository.getHiddenCategoryIds(providerId, ContentType.SERIES)- ) { hiddenLive: Set<Long>, hiddenMovies: Set<Long>, hiddenSeries: Set<Long> ->+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.SERIES),+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.VOD)+ ) { hiddenLive: Set<Long>, hiddenMovies: Set<Long>, hiddenSeries: Set<Long>, hiddenVod: Set<Long> ->mapOf(ContentType.LIVE to hiddenLive,ContentType.MOVIE to hiddenMovies,- ContentType.SERIES to hiddenSeries+ ContentType.SERIES to hiddenSeries,+ ContentType.VOD to hiddenVod)}@@ -217,6 +219,7 @@ private fun categoryControlKey(category: Category): String = "${category.type.naprivate fun contentTypeMessageLabel(type: ContentType): String = when (type) {ContentType.LIVE -> "Live TV"ContentType.MOVIE -> "Movie"+ ContentType.VOD -> "VOD"ContentType.SERIES,ContentType.SERIES_EPISODE -> "Series"}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodScreen.ktnew file mode 100644index 00000000..c476011e--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodScreen.kt@@ -0,0 +1,402 @@+package com.streamvault.app.ui.screens.vod++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.GridItemSpan+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.MovieCard+import com.streamvault.app.ui.components.SearchInput+import com.streamvault.app.ui.components.SelectionChip+import com.streamvault.app.ui.components.SeriesCard+import com.streamvault.app.ui.components.shell.AppMessageState+import com.streamvault.app.ui.components.shell.AppNavigationChrome+import com.streamvault.app.ui.components.shell.AppScreenScaffold+import com.streamvault.app.ui.components.shell.InfiniteScrollEffect+import com.streamvault.app.ui.components.shell.LoadMoreCard+import com.streamvault.app.ui.components.shell.VodActionChip+import com.streamvault.app.ui.components.shell.VodActionChipRow+import com.streamvault.app.ui.components.shell.VodBrowseOptionsDialog+import com.streamvault.app.ui.components.shell.VodCategoryOption+import com.streamvault.app.ui.components.shell.VodCategoryPickerDialog+import com.streamvault.app.ui.components.shell.VodSectionHeader+import com.streamvault.app.ui.model.VodViewMode+import com.streamvault.domain.model.LibraryFilterType+import com.streamvault.domain.model.LibrarySortBy+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.VodCatalogItem++@Composable+fun VodScreen(+ onMovieClick: (Movie) -> Unit,+ onSeriesClick: (Series) -> Unit,+ onNavigate: (String) -> Unit,+ currentRoute: String,+ viewModel: VodViewModel = hiltViewModel()+) {+ val state by viewModel.uiState.collectAsStateWithLifecycle()+ BackHandler(enabled = state.selectedCategory != null) { viewModel.selectCategory(null) }++ AppScreenScaffold(+ currentRoute = currentRoute,+ onNavigate = onNavigate,+ title = stringResource(R.string.nav_vod),+ navigationChrome = AppNavigationChrome.TopBar,+ compactHeader = true,+ showScreenHeader = false+ ) {+ when {+ state.isLoading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Text(stringResource(R.string.movies_loading))+ }+ !state.isUnifiedProvider -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ AppMessageState(+ title = stringResource(R.string.vod_unavailable_title),+ subtitle = stringResource(R.string.vod_unavailable_subtitle)+ )+ }+ state.selectedCategory != null -> SelectedVodCategory(+ title = state.selectedCategory!!.name,+ items = state.selectedItems,+ onMovieClick = onMovieClick,+ onSeriesClick = onSeriesClick,+ canLoadMore = state.canLoadMoreSelectedCategory,+ isInitialLoading = state.isLoadingSelectedCategory,+ isAppending = state.isLoadingMoreSelectedCategory,+ infiniteScroll = state.vodInfiniteScroll,+ loadedCount = state.selectedLoadedCount,+ totalCount = state.selectedTotalCount,+ rawPageSize = state.selectedRawPageSize,+ searchQuery = state.searchQuery,+ selectedFilterType = state.selectedLibraryFilterType,+ selectedSortBy = state.selectedLibrarySortBy,+ onSearchQueryChange = viewModel::setSearchQuery,+ onFilterTypeChange = viewModel::setSelectedLibraryFilterType,+ onSortByChange = viewModel::setSelectedLibrarySortBy,+ onBack = { viewModel.selectCategory(null) },+ onLoadMore = viewModel::loadMoreSelectedCategory+ )+ state.rows.isEmpty() -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ AppMessageState(+ title = stringResource(R.string.movies_no_found),+ subtitle = stringResource(R.string.movies_no_found_subtitle)+ )+ }+ state.viewMode == VodViewMode.CLASSIC -> VodClassicCategories(+ state.rows,+ viewModel::selectCategory,+ viewModel::loadMoreCategories,+ state.canLoadMoreCategories+ )+ else -> VodModernShelves(+ state.rows,+ viewModel::selectCategory,+ onMovieClick,+ onSeriesClick,+ viewModel::loadMoreCategories,+ state.canLoadMoreCategories+ )+ }+ }+}++@Composable+private fun VodModernShelves(+ rows: List<VodCategoryRow>,+ onCategoryClick: (com.streamvault.domain.model.Category) -> Unit,+ onMovieClick: (Movie) -> Unit,+ onSeriesClick: (Series) -> Unit,+ onLoadMore: () -> Unit,+ canLoadMore: Boolean+) {+ var showCategoryPicker by rememberSaveable { mutableStateOf(false) }+ val listState = rememberLazyListState()+ InfiniteScrollEffect(listState, true, canLoadMore, false, onLoadMore = onLoadMore)+ LazyColumn(+ state = listState,+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(18.dp)+ ) {+ item(key = "vod_actions") {+ VodActionChipRow(+ actions = listOf(+ VodActionChip(+ key = "categories",+ label = stringResource(R.string.movies_categories_title),+ detail = "${rows.size} groups",+ onClick = { showCategoryPicker = true }+ )+ )+ )+ }+ items(rows, key = { it.category.id }) { row ->+ if (row.items.isNotEmpty()) {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ androidx.tv.material3.Surface(+ onClick = { onCategoryClick(row.category) }+ ) {+ Text(+ text = row.category.name,+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp)+ )+ }+ LazyRow(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ items(row.items, key = VodCatalogItem::stableId) { item ->+ VodItemCard(item, onMovieClick, onSeriesClick)+ }+ }+ }+ }+ }+ }+ if (showCategoryPicker) {+ VodCategoryPickerDialog(+ title = stringResource(R.string.vod_category_picker_title),+ subtitle = stringResource(R.string.vod_category_picker_subtitle),+ categories = rows.map { row ->+ VodCategoryOption(+ name = row.category.name,+ count = row.items.size,+ onClick = { onCategoryClick(row.category) }+ )+ },+ onDismiss = { showCategoryPicker = false }+ )+ }+}++@Composable+private fun VodClassicCategories(+ rows: List<VodCategoryRow>,+ onCategoryClick: (com.streamvault.domain.model.Category) -> Unit,+ onLoadMore: () -> Unit,+ canLoadMore: Boolean+) {+ var showCategoryPicker by rememberSaveable { mutableStateOf(false) }+ val listState = rememberLazyListState()+ InfiniteScrollEffect(listState, true, canLoadMore, false, onLoadMore = onLoadMore)+ LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {+ item(key = "vod_classic_actions") {+ VodActionChipRow(+ actions = listOf(+ VodActionChip(+ key = "categories",+ label = stringResource(R.string.movies_categories_title),+ detail = "${rows.size} groups",+ onClick = { showCategoryPicker = true }+ )+ )+ )+ }+ items(rows, key = { it.category.id }) { row ->+ androidx.tv.material3.Surface(+ onClick = { onCategoryClick(row.category) },+ modifier = Modifier.fillMaxWidth().padding(vertical = 5.dp)+ ) {+ Text(+ text = row.category.name,+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(18.dp)+ )+ }+ }+ }+ if (showCategoryPicker) {+ VodCategoryPickerDialog(+ title = stringResource(R.string.vod_category_picker_title),+ subtitle = stringResource(R.string.vod_category_picker_subtitle),+ categories = rows.map { row ->+ VodCategoryOption(row.category.name, row.items.size, { onCategoryClick(row.category) })+ },+ onDismiss = { showCategoryPicker = false }+ )+ }+}++@Composable+private fun SelectedVodCategory(+ title: String,+ items: List<VodCatalogItem>,+ onMovieClick: (Movie) -> Unit,+ onSeriesClick: (Series) -> Unit,+ canLoadMore: Boolean,+ isInitialLoading: Boolean,+ isAppending: Boolean,+ infiniteScroll: Boolean,+ loadedCount: Int,+ totalCount: Int,+ rawPageSize: Int,+ searchQuery: String,+ selectedFilterType: LibraryFilterType,+ selectedSortBy: LibrarySortBy,+ onSearchQueryChange: (String) -> Unit,+ onFilterTypeChange: (LibraryFilterType) -> Unit,+ onSortByChange: (LibrarySortBy) -> Unit,+ onBack: () -> Unit,+ onLoadMore: () -> Unit+) {+ var showSearchBar by rememberSaveable(title) { mutableStateOf(searchQuery.isNotBlank()) }+ var showBrowseOptions by rememberSaveable(title) { mutableStateOf(false) }+ if (showBrowseOptions) {+ VodBrowseOptionsDialog(+ title = title,+ filterTitle = stringResource(R.string.library_filter_title),+ filterChips = unifiedVodFilterChips(),+ selectedFilterKey = selectedFilterType.name,+ onFilterSelected = { key ->+ LibraryFilterType.entries.firstOrNull { it.name == key }?.let(onFilterTypeChange)+ },+ sortTitle = stringResource(R.string.library_sort_title),+ sortChips = unifiedVodSortChips(),+ selectedSortKey = selectedSortBy.name,+ onSortSelected = { key ->+ LibrarySortBy.entries.firstOrNull { it.name == key }?.let(onSortByChange)+ },+ onDismiss = { showBrowseOptions = false }+ )+ }+ val gridState = rememberLazyGridState()+ InfiniteScrollEffect(+ gridState = gridState,+ enabled = infiniteScroll,+ canLoadMore = canLoadMore,+ isLoading = isInitialLoading || isAppending,+ prefetchDistance = rawPageSize.coerceAtLeast(6),+ onLoadMore = onLoadMore+ )+ Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ VodSectionHeader(title = title)+ VodActionChipRow(+ actions = listOf(+ VodActionChip("back", stringResource(R.string.nav_vod), onClick = onBack),+ VodActionChip(+ "search",+ stringResource(if (showSearchBar) R.string.library_action_hide_search else R.string.search_title),+ onClick = { showSearchBar = !showSearchBar }+ ),+ VodActionChip(+ "browse_options",+ stringResource(R.string.library_action_filters_sort),+ detail = vodActiveFilterSortDetail(selectedFilterType, selectedSortBy),+ onClick = { showBrowseOptions = true }+ )+ ),+ selectedKey = "browse_options".takeIf {+ selectedFilterType != LibraryFilterType.ALL || selectedSortBy != LibrarySortBy.LIBRARY+ }+ )+ if (showSearchBar) {+ SearchInput(+ value = searchQuery,+ onValueChange = onSearchQueryChange,+ placeholder = stringResource(R.string.movies_search_placeholder),+ onSearch = {},+ modifier = Modifier.padding(horizontal = 20.dp)+ )+ }+ LazyVerticalGrid(+ state = gridState,+ columns = GridCells.Adaptive(136.dp),+ modifier = Modifier.fillMaxSize(),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ if (isInitialLoading) {+ item(key = "vod_category_loading", span = { GridItemSpan(maxLineSpan) }) {+ Box(+ modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),+ contentAlignment = Alignment.Center+ ) {+ CircularProgressIndicator()+ }+ }+ } else {+ items(items, key = VodCatalogItem::stableId) { item ->+ VodItemCard(item, onMovieClick, onSeriesClick)+ }+ }+ if (canLoadMore && !infiniteScroll && !isInitialLoading && !isAppending) {+ item(key = "load_next_vod_page", span = { GridItemSpan(maxLineSpan) }) {+ LoadMoreCard(+ label = stringResource(R.string.library_load_more, loadedCount, totalCount),+ onClick = onLoadMore,+ modifier = Modifier.padding(vertical = 12.dp)+ )+ }+ }+ }+ }+}++private fun unifiedVodFilterChips(): List<SelectionChip> = listOf(+ SelectionChip(LibraryFilterType.ALL.name, "All"),+ SelectionChip(LibraryFilterType.FAVORITES.name, "Favorites"),+ SelectionChip(LibraryFilterType.IN_PROGRESS.name, "Resume"),+ SelectionChip(LibraryFilterType.UNWATCHED.name, "Unwatched"),+ SelectionChip(LibraryFilterType.RECENTLY_UPDATED.name, "Recent"),+ SelectionChip(LibraryFilterType.TOP_RATED.name, "Top Rated")+)++private fun unifiedVodSortChips(): List<SelectionChip> = LibrarySortBy.entries.map { sort ->+ SelectionChip(+ sort.name,+ when (sort) {+ LibrarySortBy.LIBRARY -> "Library Order"+ LibrarySortBy.TITLE -> "A-Z"+ LibrarySortBy.RELEASE -> "Newest"+ LibrarySortBy.UPDATED -> "Recently Updated"+ LibrarySortBy.RATING -> "Rating"+ LibrarySortBy.WATCH_COUNT -> "Recent Activity"+ }+ )+}++@Composable+private fun VodItemCard(+ item: VodCatalogItem,+ onMovieClick: (Movie) -> Unit,+ onSeriesClick: (Series) -> Unit+) {+ when (item) {+ is VodCatalogItem.MovieItem -> MovieCard(+ movie = item.movie,+ onClick = { onMovieClick(item.movie) },+ isLocked = item.movie.isUserProtected,+ showTypeBadge = true+ )+ is VodCatalogItem.SeriesItem -> SeriesCard(+ series = item.series,+ onClick = { onSeriesClick(item.series) },+ isLocked = item.series.isUserProtected,+ showTypeBadge = true+ )+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/vod/VodViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodViewModel.ktnew file mode 100644index 00000000..ebf6338f--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/vod/VodViewModel.kt@@ -0,0 +1,395 @@+package com.streamvault.app.ui.screens.vod++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.app.ui.model.VodViewMode+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.LibraryFilterType+import com.streamvault.domain.model.LibrarySortBy+import com.streamvault.domain.model.PlaybackHistory+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.VodCatalogItem+import com.streamvault.domain.model.VodCategoryKind+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.PlaybackHistoryRepository+import com.streamvault.domain.repository.VodRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import javax.inject.Inject+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.channelFlow+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.Job+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++data class VodCategoryRow(+ val category: Category,+ val items: List<VodCatalogItem>,+ val kind: VodCategoryKind = VodCategoryKind.from(items)+)++data class VodUiState(+ val provider: Provider? = null,+ val rows: List<VodCategoryRow> = emptyList(),+ val totalCategoryCount: Int = 0,+ val selectedCategory: Category? = null,+ val selectedItems: List<VodCatalogItem> = emptyList(),+ val selectedLoadedCount: Int = 0,+ val selectedTotalCount: Int = 0,+ val selectedRawPageSize: Int = 0,+ val canLoadMoreSelectedCategory: Boolean = false,+ val isLoadingSelectedCategory: Boolean = false,+ val isLoadingMoreSelectedCategory: Boolean = false,+ val vodInfiniteScroll: Boolean = true,+ val searchQuery: String = "",+ val selectedLibraryFilterType: LibraryFilterType = LibraryFilterType.ALL,+ val selectedLibrarySortBy: LibrarySortBy = LibrarySortBy.LIBRARY,+ val viewMode: VodViewMode = VodViewMode.MODERN,+ val isLoading: Boolean = true+) {+ val canLoadMoreCategories: Boolean get() = rows.size < totalCategoryCount+ val isUnifiedProvider: Boolean get() = provider?.catalogLayout == CatalogLayout.UNIFIED_VOD+}++private data class UnifiedVodCatalogSnapshot(+ val rows: List<VodCategoryRow>,+ val totalCategoryCount: Int+)++private data class SelectedVodSnapshot(+ val category: Category? = null,+ val items: List<VodCatalogItem> = emptyList(),+ val localTotal: Int = 0,+ val hydration: VodCategoryHydration? = null+)++@HiltViewModel+@OptIn(ExperimentalCoroutinesApi::class)+class VodViewModel @Inject constructor(+ providerRepository: ProviderRepository,+ private val vodRepository: VodRepository,+ private val playbackHistoryRepository: PlaybackHistoryRepository,+ preferencesRepository: PreferencesRepository+) : ViewModel() {+ private companion object {+ const val INITIAL_CATEGORY_COUNT = 12+ const val CATEGORY_LOAD_INCREMENT = 8+ const val PREVIEW_ITEM_COUNT = 20+ const val SELECTED_PAGE_SIZE = 60+ }++ private val visibleCategoryCount = MutableStateFlow(INITIAL_CATEGORY_COUNT)+ private val selectedCategoryId = MutableStateFlow<Long?>(null)+ private val selectedItemLimit = MutableStateFlow(SELECTED_PAGE_SIZE)+ private val searchQuery = MutableStateFlow("")+ private val selectedLibraryFilterType = MutableStateFlow(LibraryFilterType.ALL)+ private val selectedLibrarySortBy = MutableStateFlow(LibrarySortBy.LIBRARY)+ private var remotePageRequestInFlight = false+ private var completeHydrationJob: Job? = null+ private val cachedRows = mutableMapOf<Long, VodCategoryRow>()+ private val completedEmptyCategoryIds = mutableSetOf<Long>()+ private var cachedProviderId: Long? = null++ private val activeProvider = providerRepository.getActiveProvider()+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)++ private val catalog: Flow<UnifiedVodCatalogSnapshot> = combine(+ activeProvider,+ visibleCategoryCount+ ) { provider, limit -> provider to limit }+ .flatMapLatest { (provider, limit) ->+ if (provider == null || provider.catalogLayout != CatalogLayout.UNIFIED_VOD) {+ flowOf(UnifiedVodCatalogSnapshot(emptyList(), 0))+ } else {+ if (cachedProviderId != provider.id) {+ cachedRows.clear()+ completedEmptyCategoryIds.clear()+ cachedProviderId = provider.id+ }+ vodRepository.getCategories(provider.id).flatMapLatest { categories ->+ val visible = categories.take(limit)+ if (visible.isEmpty()) {+ flowOf(UnifiedVodCatalogSnapshot(emptyList(), categories.size))+ } else {+ progressiveCategoryRows(provider.id, visible, categories.size)+ }+ }+ }+ }++ private val selected: Flow<SelectedVodSnapshot> = combine(+ activeProvider,+ selectedCategoryId,+ catalog,+ selectedItemLimit,+ searchQuery,+ selectedLibraryFilterType,+ selectedLibrarySortBy+ ) { values -> values }+ .flatMapLatest { values ->+ val provider = values[0] as Provider?+ val categoryId = values[1] as Long?+ val snapshot = values[2] as UnifiedVodCatalogSnapshot+ val limit = values[3] as Int+ val query = values[4] as String+ val filterType = values[5] as LibraryFilterType+ val sortBy = values[6] as LibrarySortBy+ val category = snapshot.rows.firstOrNull { it.category.id == categoryId }?.category+ if (provider == null || category == null) {+ flowOf(SelectedVodSnapshot())+ } else {+ combine(+ vodRepository.getCategoryItems(provider.id, category.id),+ vodRepository.observeHydration(provider.id, category.id),+ playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 500)+ ) { items, hydration, history ->+ val browsed = applyBrowse(items, history, filterType, sortBy, query)+ SelectedVodSnapshot(category, browsed.take(limit), browsed.size, hydration)+ }+ }+ }++ val uiState: StateFlow<VodUiState> = combine(+ activeProvider,+ catalog,+ selected,+ preferencesRepository.vodViewMode,+ preferencesRepository.vodInfiniteScroll,+ searchQuery,+ selectedLibraryFilterType,+ selectedLibrarySortBy+ ) { values ->+ val provider = values[0] as Provider?+ val snapshot = values[1] as UnifiedVodCatalogSnapshot+ val selectedContent = values[2] as SelectedVodSnapshot+ val viewMode = values[3] as String?+ val infiniteScroll = values[4] as Boolean+ val query = values[5] as String+ val filterType = values[6] as LibraryFilterType+ val sortBy = values[7] as LibrarySortBy+ val requiresCompleteCatalog = query.isNotBlank() ||+ filterType != LibraryFilterType.ALL || sortBy != LibrarySortBy.LIBRARY+ val isCompletingBrowse = selectedContent.category != null && requiresCompleteCatalog &&+ selectedContent.hydration?.isComplete != true+ VodUiState(+ provider = provider,+ rows = snapshot.rows,+ totalCategoryCount = snapshot.totalCategoryCount,+ selectedCategory = selectedContent.category,+ selectedItems = selectedContent.items,+ selectedLoadedCount = selectedContent.items.size,+ selectedTotalCount = selectedContent.localTotal,+ selectedRawPageSize = selectedContent.hydration?.pageSize ?: 0,+ canLoadMoreSelectedCategory = selectedContent.items.size < selectedContent.localTotal ||+ selectedContent.hydration?.hasMoreRemote == true,+ isLoadingSelectedCategory = selectedContent.hydration?.isInitialLoading == true || isCompletingBrowse,+ isLoadingMoreSelectedCategory = selectedContent.hydration?.isAppending == true,+ vodInfiniteScroll = infiniteScroll,+ searchQuery = query,+ selectedLibraryFilterType = filterType,+ selectedLibrarySortBy = sortBy,+ viewMode = VodViewMode.fromStorage(viewMode),+ isLoading = provider == null || provider.catalogLayout == CatalogLayout.UNKNOWN+ )+ }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), VodUiState())++ fun loadMoreCategories() {+ visibleCategoryCount.value += CATEGORY_LOAD_INCREMENT+ }++ fun selectCategory(category: Category?) {+ completeHydrationJob?.cancel()+ completeHydrationJob = null+ selectedItemLimit.value = SELECTED_PAGE_SIZE+ selectedCategoryId.value = category?.id+ if (category == null) return+ val providerId = activeProvider.value?.id ?: return+ viewModelScope.launch {+ if (searchQuery.value.isNotBlank() ||+ selectedLibraryFilterType.value != LibraryFilterType.ALL ||+ selectedLibrarySortBy.value != LibrarySortBy.LIBRARY+ ) {+ vodRepository.hydrateCompletely(providerId, category.id)+ } else {+ vodRepository.requestCategoryHydration(providerId, category.id, VodCategoryHydrationRequest.OPEN)+ }+ }+ }++ fun loadMoreSelectedCategory() {+ val state = uiState.value+ val category = state.selectedCategory ?: return+ val providerId = state.provider?.id ?: return+ if (!state.canLoadMoreSelectedCategory || remotePageRequestInFlight) return+ val needsRemotePage = state.selectedLoadedCount >= state.selectedTotalCount+ selectedItemLimit.value += SELECTED_PAGE_SIZE+ if (!needsRemotePage) return+ remotePageRequestInFlight = true+ viewModelScope.launch {+ try {+ vodRepository.requestCategoryHydration(+ providerId,+ category.id,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ } finally {+ remotePageRequestInFlight = false+ }+ }+ }++ fun setSearchQuery(query: String) {+ searchQuery.value = query+ selectedItemLimit.value = SELECTED_PAGE_SIZE+ if (query.isNotBlank()) ensureCompleteForBrowseOperation()+ }++ fun setSelectedLibraryFilterType(filterType: LibraryFilterType) {+ selectedLibraryFilterType.value = filterType+ selectedItemLimit.value = SELECTED_PAGE_SIZE+ if (filterType != LibraryFilterType.ALL) ensureCompleteForBrowseOperation()+ }++ fun setSelectedLibrarySortBy(sortBy: LibrarySortBy) {+ selectedLibrarySortBy.value = sortBy+ selectedItemLimit.value = SELECTED_PAGE_SIZE+ if (sortBy != LibrarySortBy.LIBRARY) ensureCompleteForBrowseOperation()+ }++ private fun ensureCompleteForBrowseOperation() {+ val state = uiState.value+ val providerId = state.provider?.id ?: return+ val categoryId = state.selectedCategory?.id ?: return+ if (completeHydrationJob?.isActive == true) return+ completeHydrationJob = viewModelScope.launch {+ vodRepository.hydrateCompletely(providerId, categoryId)+ }+ }++ private fun applyBrowse(+ items: List<VodCatalogItem>,+ history: List<PlaybackHistory>,+ filterType: LibraryFilterType,+ sortBy: LibrarySortBy,+ query: String+ ): List<VodCatalogItem> {+ val normalizedQuery = query.trim()+ val historyIds = history.mapTo(mutableSetOf()) { it.seriesId ?: it.contentId }+ val completedIds = history+ .filter { it.totalDurationMs > 0 && it.resumePositionMs >= (it.totalDurationMs * 0.95f).toLong() }+ .mapTo(mutableSetOf()) { it.seriesId ?: it.contentId }+ val watchCounts = history.groupingBy { it.seriesId ?: it.contentId }.eachCount()+ val searched = if (normalizedQuery.isBlank()) items else items.filter { item ->+ when (item) {+ is VodCatalogItem.MovieItem -> item.movie.name.contains(normalizedQuery, true) ||+ item.movie.plot?.contains(normalizedQuery, true) == true ||+ item.movie.genre?.contains(normalizedQuery, true) == true+ is VodCatalogItem.SeriesItem -> item.series.name.contains(normalizedQuery, true) ||+ item.series.plot?.contains(normalizedQuery, true) == true ||+ item.series.genre?.contains(normalizedQuery, true) == true+ }+ }+ val filtered = when (filterType) {+ LibraryFilterType.ALL -> searched+ LibraryFilterType.FAVORITES -> searched.filter(::isFavorite)+ LibraryFilterType.IN_PROGRESS -> searched.filter { item -> item.historyId in historyIds }+ LibraryFilterType.UNWATCHED -> searched.filter { item -> item.historyId !in completedIds }+ LibraryFilterType.RECENTLY_UPDATED -> searched.filter { it.sortTimestamp > 0L }+ LibraryFilterType.TOP_RATED -> searched.filter { it.rating > 0f }+ }+ return when (sortBy) {+ LibrarySortBy.LIBRARY -> filtered+ LibrarySortBy.TITLE -> filtered.sortedBy { it.title.lowercase() }+ LibrarySortBy.RELEASE -> filtered.sortedByDescending { it.releaseScore }+ LibrarySortBy.UPDATED -> filtered.sortedByDescending(VodCatalogItem::sortTimestamp)+ LibrarySortBy.RATING -> filtered.sortedByDescending { it.rating }+ LibrarySortBy.WATCH_COUNT -> filtered.sortedByDescending { watchCounts[it.historyId] ?: 0 }+ }+ }++ private val VodCatalogItem.historyId: Long get() = when (this) {+ is VodCatalogItem.MovieItem -> movie.id+ is VodCatalogItem.SeriesItem -> series.id+ }++ private val VodCatalogItem.rating: Float get() = when (this) {+ is VodCatalogItem.MovieItem -> movie.rating+ is VodCatalogItem.SeriesItem -> series.rating+ }++ private val VodCatalogItem.releaseScore: Long get() = when (this) {+ is VodCatalogItem.MovieItem -> movie.releaseDate?.filter(Char::isDigit)?.take(8)?.toLongOrNull() ?: movie.addedAt+ is VodCatalogItem.SeriesItem -> series.releaseDate?.filter(Char::isDigit)?.take(8)?.toLongOrNull() ?: series.lastModified+ }++ private fun isFavorite(item: VodCatalogItem): Boolean = when (item) {+ is VodCatalogItem.MovieItem -> item.movie.isFavorite+ is VodCatalogItem.SeriesItem -> item.series.isFavorite+ }++ private fun progressiveCategoryRows(+ providerId: Long,+ categories: List<Category>,+ totalCategoryCount: Int+ ): Flow<UnifiedVodCatalogSnapshot> = channelFlow {+ val mutex = Mutex()+ val rows = categories.mapNotNull { category ->+ cachedRows[category.id]+ ?.takeUnless { category.id in completedEmptyCategoryIds }+ ?.let { category.id to it }+ }.toMap().toMutableMap()+ send(UnifiedVodCatalogSnapshot(categories.mapNotNull { rows[it.id] }, totalCategoryCount))+ categories.forEach { category ->+ launch {+ combine(+ vodRepository.getCategoryPreview(providerId, category.id, PREVIEW_ITEM_COUNT),+ vodRepository.observeHydration(providerId, category.id)+ ) { items, hydration -> items to hydration }+ .collect { (items, hydration) ->+ mutex.withLock {+ val completedEmpty = items.isEmpty() && hydration?.isComplete == true+ if (completedEmpty) {+ rows.remove(category.id)+ cachedRows.remove(category.id)+ if (completedEmptyCategoryIds.add(category.id) && categories.size < totalCategoryCount) {+ visibleCategoryCount.value += 1+ }+ } else {+ val row = VodCategoryRow(category, items, hydration.toCategoryKind(items))+ rows[category.id] = row+ cachedRows[category.id] = row+ }+ send(+ UnifiedVodCatalogSnapshot(+ rows = categories.mapNotNull { rows[it.id] },+ totalCategoryCount = totalCategoryCount+ )+ )+ }+ }+ }+ }+ }++ private fun VodCategoryHydration?.toCategoryKind(items: List<VodCatalogItem>): VodCategoryKind = when {+ this == null -> VodCategoryKind.from(items)+ hasMovies && hasSeries -> VodCategoryKind.MIXED+ hasMovies -> VodCategoryKind.MOVIES+ hasSeries -> VodCategoryKind.SERIES+ else -> VodCategoryKind.UNKNOWN+ }+}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 61f13653..92dedb0c 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -556,8 +556,11 @@<string name="settings_vod_view_mode_classic">Classic</string><string name="settings_vod_view_mode_classic_desc">Category list on the left with a stacked poster grid on the right.</string><string name="settings_vod_infinite_scroll">Infinite scroll</string>- <string name="settings_vod_infinite_scroll_on">Auto-load more category rows as you scroll near the end.</string>- <string name="settings_vod_infinite_scroll_off">Show a Load more button to fetch the next batch of category rows.</string>+ <string name="settings_vod_infinite_scroll_on">Load the next page as you scroll near the end.</string>+ <string name="settings_vod_infinite_scroll_off">Show a Load more button for the next page.</string>+ <string name="settings_vod_complete_on_open">Load entire VOD category on open</string>+ <string name="settings_vod_complete_on_open_on">Fetch every Stalker page before finishing the initial load.</string>+ <string name="settings_vod_complete_on_open_off">Show the first Stalker page immediately, then load more as needed.</string><string name="settings_vod_duplicate_handling_mode">VOD duplicate handling</string><string name="settings_vod_duplicate_handling_mode_subtitle">Choose whether movie versions stay separate or appear as grouped title variants.</string><string name="settings_vod_duplicate_handling_show_all">Show All Versions</string>@@ -1799,4 +1802,7 @@<string name="stalker_verification_inconclusive_body" translatable="false">The provider accepted your login, but the Live TV check did not finish. You can save it with verification pending; it will remain inactive until a sync confirms playable Live TV.</string><string name="stalker_save_without_verification" translatable="false">Save without verification</string><string name="stalker_repair_connection" translatable="false">Repair connection</string>+ <string name="nav_vod">VOD</string>+ <string name="vod_unavailable_title">VOD is unavailable</string>+ <string name="vod_unavailable_subtitle">This provider exposes separate Movies and Series catalogs.</string></resources>diff --git a/app/src/test/java/com/streamvault/app/navigation/CatalogRouteResolverTest.kt b/app/src/test/java/com/streamvault/app/navigation/CatalogRouteResolverTest.ktnew file mode 100644index 00000000..3064a7ea--- /dev/null+++ b/app/src/test/java/com/streamvault/app/navigation/CatalogRouteResolverTest.kt@@ -0,0 +1,24 @@+package com.streamvault.app.navigation++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.ContentType+import org.junit.Test++class CatalogRouteResolverTest {+ @Test+ fun unifiedAndUnknownLayoutsUseVodRoute() {+ assertThat(resolveCatalogRoute(CatalogLayout.UNIFIED_VOD, Routes.MOVIES, ContentType.MOVIE, true))+ .isEqualTo(Routes.VOD)+ assertThat(resolveCatalogRoute(CatalogLayout.UNKNOWN, Routes.SERIES, ContentType.SERIES, true))+ .isEqualTo(Routes.VOD)+ }++ @Test+ fun splitLayoutWaitsForDestinationPreferenceBeforeRedirecting() {+ assertThat(resolveCatalogRoute(CatalogLayout.SPLIT, Routes.VOD, ContentType.SERIES, false))+ .isEqualTo(Routes.VOD)+ assertThat(resolveCatalogRoute(CatalogLayout.SPLIT, Routes.VOD, ContentType.SERIES, true))+ .isEqualTo(Routes.SERIES)+ }+}diff --git a/data/build.gradle.kts b/data/build.gradle.ktsindex 81255e4d..010be2bd 100644--- a/data/build.gradle.kts+++ b/data/build.gradle.kts@@ -14,6 +14,7 @@ android {defaultConfig {minSdk = 25+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"}compileOptions {diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/66.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/66.jsonnew file mode 100644index 00000000..45439d77--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/66.json@@ -0,0 +1,6138 @@+{+ "formatVersion": 1,+ "database": {+ "version": 66,+ "identityHash": "a98ad529d15bc601af11349f2fdc16b6",+ "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, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_protocol_preference` TEXT NOT NULL, `stalker_transport_mode` TEXT NOT NULL, `stalker_transport_origin` TEXT NOT NULL, `stalker_tls_spki_sha256` TEXT NOT NULL, `stalker_transport_consent_at` INTEGER NOT NULL, `stalker_configuration_generation` INTEGER NOT NULL, `stalker_discovery_summary` TEXT NOT NULL, `stalker_capabilities_json` TEXT NOT NULL, `stalker_requested_profile_id` TEXT NOT NULL, `stalker_learned_profile_id` TEXT NOT NULL, `stalker_profile_revision` INTEGER NOT NULL, `stalker_profile_verification` TEXT NOT NULL, `stalker_protocol_family` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `stalker_catalog_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpUserAgent",+ "columnName": "http_user_agent",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "httpHeaders",+ "columnName": "http_headers",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacAddress",+ "columnName": "stalker_mac_address",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceProfile",+ "columnName": "stalker_device_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceTimezone",+ "columnName": "stalker_device_timezone",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceLocale",+ "columnName": "stalker_device_locale",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSerialNumber",+ "columnName": "stalker_serial_number",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId",+ "columnName": "stalker_device_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDeviceId2",+ "columnName": "stalker_device_id2",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerSignature",+ "columnName": "stalker_signature",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAdvancedOptionsJson",+ "columnName": "stalker_advanced_options_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerAuthMode",+ "columnName": "stalker_auth_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalProfile",+ "columnName": "stalker_portal_profile",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPortalFingerprint",+ "columnName": "stalker_portal_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMagPreset",+ "columnName": "stalker_mag_preset",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerProtocolPreference",+ "columnName": "stalker_protocol_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerTransportMode",+ "columnName": "stalker_transport_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerTransportOrigin",+ "columnName": "stalker_transport_origin",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerTlsSpkiSha256",+ "columnName": "stalker_tls_spki_sha256",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerTransportConsentAt",+ "columnName": "stalker_transport_consent_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerConfigurationGeneration",+ "columnName": "stalker_configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerDiscoverySummary",+ "columnName": "stalker_discovery_summary",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCapabilitiesJson",+ "columnName": "stalker_capabilities_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRequestedProfileId",+ "columnName": "stalker_requested_profile_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLearnedProfileId",+ "columnName": "stalker_learned_profile_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerProfileRevision",+ "columnName": "stalker_profile_revision",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerProfileVerification",+ "columnName": "stalker_profile_verification",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerProtocolFamily",+ "columnName": "stalker_protocol_family",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastBootstrapRecipe",+ "columnName": "stalker_last_bootstrap_recipe",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerEndpointPreference",+ "columnName": "stalker_endpoint_preference",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCookieMode",+ "columnName": "stalker_cookie_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerPlaybackBackendHint",+ "columnName": "stalker_playback_backend_hint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerLastPlaybackMode",+ "columnName": "stalker_last_playback_mode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "stalkerCredentialsRequired",+ "columnName": "stalker_credentials_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerMacRequired",+ "columnName": "stalker_mac_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerUsesTemporaryLinks",+ "columnName": "stalker_uses_temp_links",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerModuleRestricted",+ "columnName": "stalker_module_restricted",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerStrictFingerprintRequired",+ "columnName": "stalker_strict_fingerprint_required",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeFallbackUsed",+ "columnName": "stalker_recipe_fallback_used",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stalkerRecipeRediscoveryAttempts",+ "columnName": "stalker_recipe_rediscovery_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stalkerCatalogMode",+ "columnName": "stalker_catalog_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "guideSourcePolicy",+ "columnName": "guide_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelLogoSourcePolicy",+ "columnName": "channel_logo_source_policy",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xtreamLiveSyncMode",+ "columnName": "xtream_live_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayout",+ "columnName": "catalog_layout",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "catalogLayoutDetectionVersion",+ "columnName": "catalog_layout_detection_version",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username_stalker_mac_address",+ "unique": true,+ "columnNames": [+ "server_url",+ "username",+ "stalker_mac_address"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"+ }+ ]+ },+ {+ "tableName": "channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `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": "audioVideoOffsetMs",+ "columnName": "audio_video_offset_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ },+ {+ "name": "index_movies_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_movies_provider_id_added_at_release_date_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "added_at",+ "release_date",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `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, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, `catalog_origin` TEXT NOT NULL, `episode_playback_template_url` 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": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cacheState",+ "columnName": "cache_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteStaleAt",+ "columnName": "remote_stale_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catalogOrigin",+ "columnName": "catalog_origin",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodePlaybackTemplateUrl",+ "columnName": "episode_playback_template_url",+ "affinity": "TEXT"+ }+ ],+ "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`)"+ },+ {+ "name": "index_series_provider_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_category_id_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_rating_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "rating",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"+ },+ {+ "name": "index_series_provider_id_last_modified_name_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "last_modified",+ "name",+ "id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `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, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerSeriesId",+ "columnName": "provider_series_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "providerSeriesKey",+ "columnName": "provider_series_key",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "provider_series_key"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_order` INTEGER NOT NULL DEFAULT 0, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerOrder",+ "columnName": "provider_order",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_end_time_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "end_time",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "groupKey",+ "columnName": "group_key",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_provider_id_content_id_content_type_group_key",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_id",+ "content_type",+ "group_key"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"+ },+ {+ "name": "index_favorites_provider_id_content_type_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "playback_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"+ },+ {+ "name": "index_playback_history_provider_id_content_type_last_watched_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "tmdb_identity",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "canonicalProviderId",+ "columnName": "canonical_provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "firstSeenAt",+ "columnName": "first_seen_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "tmdb_id",+ "content_type"+ ]+ },+ "indices": [+ {+ "name": "index_tmdb_identity_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"+ },+ {+ "name": "index_tmdb_identity_canonical_provider_id",+ "unique": false,+ "columnNames": [+ "canonical_provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "canonical_provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "search_history",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "query",+ "columnName": "query",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentScope",+ "columnName": "content_scope",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "usedAt",+ "columnName": "used_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "useCount",+ "columnName": "use_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_search_history_content_scope_provider_id_used_at",+ "unique": false,+ "columnNames": [+ "content_scope",+ "provider_id",+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"+ },+ {+ "name": "index_search_history_used_at",+ "unique": false,+ "columnNames": [+ "used_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"+ },+ {+ "name": "index_search_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_search_history_query_content_scope_provider_id",+ "unique": true,+ "columnNames": [+ "query",+ "content_scope",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSuccess",+ "columnName": "last_live_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSuccess",+ "columnName": "last_series_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSuccess",+ "columnName": "last_epg_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `has_movies` INTEGER NOT NULL, `has_series` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLoadedPage",+ "columnName": "last_loaded_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptedPage",+ "columnName": "last_attempted_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessfulPage",+ "columnName": "last_successful_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalPages",+ "columnName": "total_pages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "pageSize",+ "columnName": "page_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isComplete",+ "columnName": "is_complete",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasMovies",+ "columnName": "has_movies",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "hasSeries",+ "columnName": "has_series",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "retryAfterMs",+ "columnName": "retry_after_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryBudgetRemaining",+ "columnName": "retry_budget_remaining",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastPageFingerprint",+ "columnName": "last_page_fingerprint",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "vod_catalog_entries",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `raw_item_id` TEXT NOT NULL, `item_type` TEXT NOT NULL, `target_id` INTEGER NOT NULL, `raw_page` INTEGER NOT NULL, `raw_index` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`, `raw_item_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawItemId",+ "columnName": "raw_item_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "itemType",+ "columnName": "item_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "targetId",+ "columnName": "target_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawPage",+ "columnName": "raw_page",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rawIndex",+ "columnName": "raw_index",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_item_id"+ ]+ },+ "indices": [+ {+ "name": "index_vod_catalog_entries_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "raw_page",+ "raw_index"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `raw_page`, `raw_index`)"+ },+ {+ "name": "index_vod_catalog_entries_provider_id_item_type_target_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "item_type",+ "target_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_item_type_target_id` ON `${TABLE_NAME}` (`provider_id`, `item_type`, `target_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "etag",+ "columnName": "etag",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModifiedHeader",+ "columnName": "last_modified_header",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "matchedAt",+ "columnName": "matched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedAttempts",+ "columnName": "failed_attempts",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "source",+ "columnName": "source",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "combined_m3u_profiles",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "combined_m3u_profile_members",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "profileId",+ "columnName": "profile_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_combined_m3u_profile_members_profile_id",+ "unique": false,+ "columnNames": [+ "profile_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",+ "unique": true,+ "columnNames": [+ "profile_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "combined_m3u_profiles",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "profile_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "program_reminders",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programStartTime",+ "columnName": "program_start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remindAt",+ "columnName": "remind_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "leadTimeMinutes",+ "columnName": "lead_time_minutes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isDismissed",+ "columnName": "is_dismissed",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "notifiedAt",+ "columnName": "notified_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_program_reminders_provider_id_remind_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",+ "unique": false,+ "columnNames": [+ "is_dismissed",+ "notified_at",+ "remind_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"+ },+ {+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "program_title",+ "program_start_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "playback_compatibility_records",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deviceFingerprint",+ "columnName": "device_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "deviceModel",+ "columnName": "device_model",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "androidSdk",+ "columnName": "android_sdk",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamType",+ "columnName": "stream_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "videoMimeType",+ "columnName": "video_mime_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolutionBucket",+ "columnName": "resolution_bucket",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "decoderName",+ "columnName": "decoder_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surfaceType",+ "columnName": "surface_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureType",+ "columnName": "failure_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastFailedAt",+ "columnName": "last_failed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSucceededAt",+ "columnName": "last_succeeded_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failureCount",+ "columnName": "failure_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "successCount",+ "columnName": "success_count",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",+ "unique": true,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket",+ "decoder_name",+ "surface_type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"+ },+ {+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",+ "unique": false,+ "columnNames": [+ "device_fingerprint",+ "stream_type",+ "video_mime_type",+ "resolution_bucket"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"+ },+ {+ "name": "index_playback_compatibility_records_last_failed_at",+ "unique": false,+ "columnNames": [+ "last_failed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"+ },+ {+ "name": "index_playback_compatibility_records_last_succeeded_at",+ "unique": false,+ "columnNames": [+ "last_succeeded_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"+ }+ ]+ },+ {+ "tableName": "xtream_content_index",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_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": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "remoteId",+ "columnName": "remote_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "localContentId",+ "columnName": "local_content_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "remoteUpdatedAt",+ "columnName": "remote_updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedAt",+ "columnName": "indexed_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "detailHydratedAt",+ "columnName": "detail_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "staleState",+ "columnName": "stale_state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorState",+ "columnName": "error_state",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "remote_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_content_index_provider_id_content_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_name",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "local_content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"+ },+ {+ "name": "index_xtream_content_index_provider_id_indexed_at",+ "unique": false,+ "columnNames": [+ "provider_id",+ "indexed_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"+ },+ {+ "name": "index_xtream_content_index_stale_state",+ "unique": false,+ "columnNames": [+ "stale_state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), 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": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priorityCategoryId",+ "columnName": "priority_category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "priorityRequestedAt",+ "columnName": "priority_requested_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_index_jobs_section",+ "unique": false,+ "columnNames": [+ "section"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"+ },+ {+ "name": "index_xtream_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_xtream_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "xtream_live_onboarding_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, 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": "providerType",+ "columnName": "provider_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "phase",+ "columnName": "phase",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "stagedSessionId",+ "columnName": "staged_session_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "importStrategy",+ "columnName": "import_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "acceptedRowCount",+ "columnName": "accepted_row_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stagedFlushCount",+ "columnName": "staged_flush_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileTier",+ "columnName": "sync_profile_tier",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileBatchSize",+ "columnName": "sync_profile_batch_size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileStrategy",+ "columnName": "sync_profile_strategy",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncProfileLowMemory",+ "columnName": "sync_profile_low_memory",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileMemoryClassMb",+ "columnName": "sync_profile_memory_class_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncProfileAvailableMemMb",+ "columnName": "sync_profile_available_mem_mb",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_xtream_live_onboarding_state_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_phase",+ "unique": false,+ "columnNames": [+ "phase"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ },+ {+ "name": "index_xtream_live_onboarding_state_staged_session_id",+ "unique": false,+ "columnNames": [+ "staged_session_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_index_jobs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), 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": "section",+ "columnName": "section",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "state",+ "columnName": "state",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "totalCategories",+ "columnName": "total_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedCategories",+ "columnName": "completed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nextCategoryIndex",+ "columnName": "next_category_index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "failedCategories",+ "columnName": "failed_categories",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "indexedRows",+ "columnName": "indexed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "skippedMalformedRows",+ "columnName": "skipped_malformed_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "deletedPrunedRows",+ "columnName": "deleted_pruned_rows",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "last_attempt_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "section"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_index_jobs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_index_jobs_state",+ "unique": false,+ "columnNames": [+ "state"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"+ },+ {+ "name": "index_stalker_index_jobs_updated_at",+ "unique": false,+ "columnNames": [+ "updated_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_portal_state",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` 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": "workingEndpoint",+ "columnName": "working_endpoint",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bootstrapRecipe",+ "columnName": "bootstrap_recipe",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bulkLiveSupported",+ "columnName": "bulk_live_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "bulkLiveCategoryFidelity",+ "columnName": "bulk_live_category_fidelity",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "movieWildcardSupported",+ "columnName": "movie_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seriesWildcardSupported",+ "columnName": "series_wildcard_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "epgSupported",+ "columnName": "epg_supported",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "safeMetadataConcurrency",+ "columnName": "safe_metadata_concurrency",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "stressCooldownUntil",+ "columnName": "stress_cooldown_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endpointHealthJson",+ "columnName": "endpoint_health_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "endpointFailedUntil",+ "columnName": "endpoint_failed_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "validatedAt",+ "columnName": "validated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "schemaVersion",+ "columnName": "schema_version",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_portal_state_provider_id",+ "unique": true,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_remote_identities",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_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": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rawId",+ "columnName": "raw_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "surrogateId",+ "columnName": "surrogate_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "content_type",+ "raw_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_remote_identities_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "content_type",+ "surrogate_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "stalker_discovery_staging",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`discovery_id` TEXT NOT NULL, `provider_id` INTEGER, `configuration_generation` INTEGER NOT NULL, `sanitized_summary` TEXT NOT NULL, `categories_json` TEXT NOT NULL, `channels_json` TEXT NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`discovery_id`))",+ "fields": [+ {+ "fieldPath": "discoveryId",+ "columnName": "discovery_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "configurationGeneration",+ "columnName": "configuration_generation",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sanitizedSummary",+ "columnName": "sanitized_summary",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "categoriesJson",+ "columnName": "categories_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "channelsJson",+ "columnName": "channels_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "discovery_id"+ ]+ },+ "indices": [+ {+ "name": "index_stalker_discovery_staging_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_stalker_discovery_staging_created_at",+ "unique": false,+ "columnNames": [+ "created_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_created_at` ON `${TABLE_NAME}` (`created_at`)"+ }+ ]+ },+ {+ "tableName": "downloads",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentName",+ "columnName": "content_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceStreamUrl",+ "columnName": "source_stream_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourceStreamId",+ "columnName": "source_stream_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalBytes",+ "columnName": "total_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "supportsResume",+ "columnName": "supports_resume",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "completedAt",+ "columnName": "completed_at",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_downloads_status",+ "unique": false,+ "columnNames": [+ "status"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"+ },+ {+ "name": "index_downloads_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_downloads_content_type_content_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "content_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_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, 'a98ad529d15bc601af11349f2fdc16b6')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.ktindex 52957b56..7ecff002 100644--- a/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/CatalogSyncDaoSeriesStageTest.kt@@ -6,12 +6,15 @@ import androidx.test.core.app.ApplicationProviderimport androidx.test.ext.junit.runners.AndroidJUnit4import com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.dao.CatalogSyncDao+import com.streamvault.data.local.dao.EpisodeDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.entity.EpisodeEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.SeriesEntityimport com.streamvault.data.local.entity.SeriesImportStageEntityimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.SeriesCatalogOriginimport kotlinx.coroutines.test.runTestimport org.junit.Afterimport org.junit.Before@@ -24,6 +27,7 @@ class CatalogSyncDaoSeriesStageTest {private lateinit var db: StreamVaultDatabaseprivate lateinit var providerDao: ProviderDaoprivate lateinit var seriesDao: SeriesDao+ private lateinit var episodeDao: EpisodeDaoprivate lateinit var catalogSyncDao: CatalogSyncDao@Before@@ -32,6 +36,7 @@ class CatalogSyncDaoSeriesStageTest {db = Room.inMemoryDatabaseBuilder(context, StreamVaultDatabase::class.java).build()providerDao = db.providerDao()seriesDao = db.seriesDao()+ episodeDao = db.episodeDao()catalogSyncDao = db.catalogSyncDao()}@@ -103,10 +108,68 @@ class CatalogSyncDaoSeriesStageTest {assertThat(updated?.syncFingerprint).isEqualTo("new-fingerprint")}+ @Test+ fun upsertCategoryPage_preservesHydratedDetailsAndEpisodes() = runTest {+ providerDao.insert(provider(1L))+ seriesDao.insertAll(+ listOf(+ SeriesEntity(+ seriesId = 331741L,+ providerSeriesId = "331741",+ name = "The Apartment Job",+ plot = "Hydrated plot",+ providerId = 1L,+ cacheState = "DETAIL_HYDRATED",+ detailHydratedAt = 1234L,+ catalogOrigin = SeriesCatalogOrigin.VOD_DERIVED,+ episodePlaybackTemplateUrl = "stalker://1/episode/331741?cmd=parent"+ )+ )+ )+ val persisted = requireNotNull(seriesDao.getBySeriesId(1L, 331741L))+ episodeDao.insertAll(+ listOf(+ EpisodeEntity(+ episodeId = 2535382L,+ title = "Episode 8",+ episodeNumber = 8,+ seasonNumber = 1,+ streamUrl = "stalker://1/episode/2535382?series=8",+ seriesId = persisted.id,+ providerId = 1L+ )+ )+ )++ seriesDao.upsertCategoryPage(+ providerId = 1L,+ series = listOf(+ SeriesEntity(+ seriesId = 331741L,+ providerSeriesId = "331741",+ name = "The Apartment Job (catalog refresh)",+ providerId = 1L,+ cacheState = "SUMMARY_ONLY",+ detailHydratedAt = 0L,+ catalogOrigin = SeriesCatalogOrigin.VOD_DERIVED+ )+ )+ )++ val refreshed = requireNotNull(seriesDao.getBySeriesId(1L, 331741L))+ assertThat(refreshed.id).isEqualTo(persisted.id)+ assertThat(refreshed.name).isEqualTo("The Apartment Job (catalog refresh)")+ assertThat(refreshed.plot).isEqualTo("Hydrated plot")+ assertThat(refreshed.cacheState).isEqualTo("DETAIL_HYDRATED")+ assertThat(refreshed.detailHydratedAt).isEqualTo(1234L)+ assertThat(episodeDao.getBySeriesSync(refreshed.id).map { it.episodeId })+ .containsExactly(2535382L)+ }+private fun provider(id: Long) = ProviderEntity(id = id,name = "Provider $id",type = ProviderType.STALKER_PORTAL,serverUrl = "https://provider$id.example.com")-}\ No newline at end of file+}diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.ktindex 14fa0383..9a51535c 100644--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt@@ -1437,6 +1437,90 @@ class StreamVaultDatabaseMigrationTest {migratedDb.close()}+ @Test+ fun migrate65To66_addsProviderCatalogLayoutAndUnifiedHydration() {+ migrationTestHelper.createDatabase("streamvault-65-66-test", 65).close()++ val migratedDb = migrationTestHelper.runMigrationsAndValidate(+ "streamvault-65-66-test",+ 66,+ true,+ StreamVaultDatabase.MIGRATION_65_66+ )++ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'catalog_layout' AND dflt_value = '''SPLIT'''"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'catalog_layout_detection_version' AND dflt_value = '0'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('categories') WHERE name = 'provider_order' AND dflt_value = '0'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('category_import_stage') WHERE name = 'provider_order' AND dflt_value = '0'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'vod_category_hydration'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_vod_category_hydration_provider_id'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('series') WHERE name = 'catalog_origin' AND dflt_value = '''NATIVE'''"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('series') WHERE name = 'episode_playback_template_url' AND type = 'TEXT'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'vod_catalog_entries'"+ )+ )+ assertEquals(+ 1,+ countRows(+ migratedDb,+ "SELECT COUNT(*) FROM pragma_table_info('vod_category_hydration') WHERE name = 'last_successful_page'"+ )+ )+ migratedDb.close()+ }+private fun countRows(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Int {db.query(sql).use { cursor ->if (!cursor.moveToFirst()) return 0diff --git a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.ktindex 7ccad946..664fa5b1 100644--- a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt+++ b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt@@ -2,6 +2,8 @@ package com.streamvault.data.localimport androidx.room.TypeConverterimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.SeriesCatalogOriginimport com.streamvault.domain.model.ChannelLogoSourcePolicyimport com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.ProviderEpgSyncMode@@ -167,6 +169,20 @@ class RoomEnumConverters {fun toContentType(value: String?): ContentType? =enumValueOrDefault(value, ContentType.LIVE, contentTypeAliases())+ @TypeConverter+ fun fromCatalogLayout(value: CatalogLayout?): String? = value?.name++ @TypeConverter+ fun toCatalogLayout(value: String?): CatalogLayout? =+ enumValueOrDefault(value, CatalogLayout.SPLIT)++ @TypeConverter+ fun fromSeriesCatalogOrigin(value: SeriesCatalogOrigin?): String? = value?.name++ @TypeConverter+ fun toSeriesCatalogOrigin(value: String?): SeriesCatalogOrigin? =+ enumValueOrDefault(value, SeriesCatalogOrigin.NATIVE)+private inline fun <reified T : Enum<T>> enumValueOrDefault(value: String?,defaultValue: T,@@ -223,7 +239,6 @@ class RoomEnumConverters {private fun contentTypeAliases(): Map<String, ContentType> = mapOf("EPISODE" to ContentType.SERIES_EPISODE,"SHOW" to ContentType.SERIES,- "VOD" to ContentType.MOVIE,"CHANNEL" to ContentType.LIVE)}diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex a9ad832b..7fa423df 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -33,6 +33,8 @@ import com.streamvault.data.local.entity.*SyncMetadataEntity::class,MovieCategoryHydrationEntity::class,SeriesCategoryHydrationEntity::class,+ VodCategoryHydrationEntity::class,+ VodCatalogEntryEntity::class,EpgSourceEntity::class,ProviderEpgSourceEntity::class,EpgChannelEntity::class,@@ -54,7 +56,7 @@ import com.streamvault.data.local.entity.*StalkerDiscoveryStageEntity::class,DownloadEntity::class],- version = 65,+ version = 66,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -77,6 +79,8 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun syncMetadataDao(): SyncMetadataDaoabstract fun movieCategoryHydrationDao(): MovieCategoryHydrationDaoabstract fun seriesCategoryHydrationDao(): SeriesCategoryHydrationDao+ abstract fun vodCategoryHydrationDao(): VodCategoryHydrationDao+ abstract fun vodCatalogEntryDao(): VodCatalogEntryDaoabstract fun epgSourceDao(): EpgSourceDaoabstract fun providerEpgSourceDao(): ProviderEpgSourceDaoabstract fun epgChannelDao(): EpgChannelDao@@ -2926,6 +2930,95 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ val MIGRATION_65_66 = object : Migration(65, 66) {+ override fun migrate(database: SupportSQLiteDatabase) {+ addColumnIfMissing(+ database,+ "providers",+ "catalog_layout",+ "TEXT NOT NULL DEFAULT 'SPLIT'"+ )+ addColumnIfMissing(+ database,+ "providers",+ "catalog_layout_detection_version",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "categories",+ "provider_order",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "category_import_stage",+ "provider_order",+ "INTEGER NOT NULL DEFAULT 0"+ )+ addColumnIfMissing(+ database,+ "series",+ "catalog_origin",+ "TEXT NOT NULL DEFAULT 'NATIVE'"+ )+ addColumnIfMissing(+ database,+ "series",+ "episode_playback_template_url",+ "TEXT"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_category_hydration (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ last_loaded_page INTEGER NOT NULL DEFAULT 0,+ last_attempted_page INTEGER NOT NULL DEFAULT 0,+ last_successful_page INTEGER NOT NULL DEFAULT 0,+ total_pages INTEGER NOT NULL DEFAULT 0,+ page_size INTEGER NOT NULL DEFAULT 0,+ item_count INTEGER NOT NULL DEFAULT 0,+ is_complete INTEGER NOT NULL DEFAULT 0,+ has_movies INTEGER NOT NULL DEFAULT 0,+ has_series INTEGER NOT NULL DEFAULT 0,+ last_hydrated_at INTEGER NOT NULL DEFAULT 0,+ last_status TEXT NOT NULL DEFAULT 'IDLE',+ last_error TEXT,+ retry_after_ms INTEGER NOT NULL DEFAULT 0,+ failure_count INTEGER NOT NULL DEFAULT 0,+ retry_budget_remaining INTEGER NOT NULL DEFAULT 3,+ last_page_fingerprint TEXT,+ PRIMARY KEY(provider_id, category_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL(+ "CREATE INDEX IF NOT EXISTS index_vod_category_hydration_provider_id ON vod_category_hydration(provider_id)"+ )+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS vod_catalog_entries (+ provider_id INTEGER NOT NULL,+ category_id INTEGER NOT NULL,+ raw_item_id TEXT NOT NULL,+ item_type TEXT NOT NULL,+ target_id INTEGER NOT NULL,+ raw_page INTEGER NOT NULL,+ raw_index INTEGER NOT NULL,+ PRIMARY KEY(provider_id, category_id, raw_item_id),+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id ON vod_catalog_entries(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index ON vod_catalog_entries(provider_id, category_id, raw_page, raw_index)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_vod_catalog_entries_provider_id_item_type_target_id ON vod_catalog_entries(provider_id, item_type, target_id)")+ validateForeignKeys(database, "providers", "vod_category_hydration", "vod_catalog_entries")+ }+ }+val MIGRATION_52_53 = object : Migration(52, 53) {override fun migrate(database: SupportSQLiteDatabase) {addStalkerHardeningColumns(database, "movie_category_hydration")diff --git a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.ktindex a7dfd903..9c45a808 100644--- a/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/CatalogSyncDao.kt@@ -114,6 +114,14 @@ interface CatalogSyncDao {AND stage.type = :typeAND stage.category_id = categories.category_id),+ provider_order = (+ SELECT stage.provider_order+ FROM category_import_stage AS stage+ WHERE stage.session_id = :sessionId+ AND stage.provider_id = :providerId+ AND stage.type = :type+ AND stage.category_id = categories.category_id+ ),is_adult = (SELECT stage.is_adultFROM category_import_stage AS stage@@ -153,6 +161,7 @@ interface CatalogSyncDao {parent_id,type,provider_id,+ provider_order,is_adult,is_user_protected,sync_fingerprint@@ -163,6 +172,7 @@ interface CatalogSyncDao {stage.parent_id,stage.type,stage.provider_id,+ stage.provider_order,stage.is_adult,0,stage.sync_fingerprintdiff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex 92ca6c90..90ea852f 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@@ -67,6 +67,16 @@ abstract class ProviderDao {@Query("UPDATE providers SET epg_url = :epgUrl WHERE id = :id")abstract suspend fun updateEpgUrl(id: Long, epgUrl: String)+ @Query("UPDATE providers SET catalog_layout_detection_version = 0 WHERE id = :id")+ abstract suspend fun invalidateCatalogLayoutDetection(id: Long)++ @Query("UPDATE providers SET catalog_layout = :layout, catalog_layout_detection_version = :version WHERE id = :id")+ abstract suspend fun updateCatalogLayout(+ id: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ version: Int+ )+@Transactionopen suspend fun insert(provider: ProviderEntity): Long {if (provider.isActive) {@@ -1587,6 +1597,9 @@ interface MovieDao {@Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id IN (:streamIds)")suspend fun getByStreamIds(providerId: Long, streamIds: List<Long>): List<MovieEntity>+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND stream_id IN (:streamIds)")+ fun observeByStreamIds(providerId: Long, streamIds: List<Long>): Flow<List<MovieEntity>>+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun insertAll(movies: List<MovieEntity>)@@ -2588,10 +2601,24 @@ interface SeriesDao {@Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id IN (:seriesIds)")suspend fun getBySeriesIds(providerId: Long, seriesIds: List<Long>): List<SeriesEntity>+ @Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId AND category_id = :categoryId AND catalog_origin = :origin")+ suspend fun countByCategoryAndOrigin(+ providerId: Long,+ categoryId: Long,+ origin: com.streamvault.domain.model.SeriesCatalogOrigin+ ): Int++ @Query("SELECT * FROM series WHERE provider_id = :providerId AND series_id IN (:seriesIds)")+ fun observeBySeriesIds(providerId: Long, seriesIds: List<Long>): Flow<List<SeriesEntity>>+@Query("SELECT * FROM series WHERE provider_id = :providerId AND provider_series_id = :providerSeriesId LIMIT 1")suspend fun getByProviderSeriesId(providerId: Long, providerSeriesId: String): SeriesEntity?- @Insert(onConflict = OnConflictStrategy.REPLACE)+ // REPLACE deletes the existing parent row before inserting it again. Because+ // episodes reference series with ON DELETE CASCADE, a catalog-page refresh+ // could silently erase already-hydrated episodes. UPSERT updates matched+ // primary keys in place and keeps those children intact.+ @Upsertsuspend fun insertAll(series: List<SeriesEntity>)@Update@@ -2670,11 +2697,46 @@ interface SeriesDao {@Transactionsuspend fun upsertCategoryPage(providerId: Long, series: List<SeriesEntity>) {if (series.isEmpty()) return- val existingByRemoteId = getIdMappings(providerId).associate { it.remoteId to it.id }+ val existing = getByProviderSync(providerId)+ val existingByRemoteId = existing.associateBy {+ it.providerSeriesId?.takeIf(String::isNotBlank) ?: it.seriesId.toString()+ }fun SeriesEntity.remoteKey(): String = providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesId.toString()val remapped = series.distinctBy { it.remoteKey() }- .map { entity -> entity.copy(id = existingByRemoteId[entity.remoteKey()] ?: 0L) }+ .map { incoming ->+ val current = existingByRemoteId[incoming.remoteKey()]+ when {+ current == null -> incoming+ current.catalogOrigin == com.streamvault.domain.model.SeriesCatalogOrigin.NATIVE &&+ incoming.catalogOrigin == com.streamvault.domain.model.SeriesCatalogOrigin.VOD_DERIVED ->+ current.copy(+ episodePlaybackTemplateUrl = current.episodePlaybackTemplateUrl+ ?: incoming.episodePlaybackTemplateUrl+ )+ else -> {+ val preserveDetails = current.cacheState == "DETAIL_HYDRATED" &&+ current.detailHydratedAt > 0L+ incoming.copy(+ id = current.id,+ backdropUrl = if (preserveDetails) current.backdropUrl else incoming.backdropUrl,+ plot = if (preserveDetails) current.plot else incoming.plot,+ cast = if (preserveDetails) current.cast else incoming.cast,+ director = if (preserveDetails) current.director else incoming.director,+ releaseDate = if (preserveDetails) current.releaseDate else incoming.releaseDate,+ tmdbId = incoming.tmdbId ?: current.tmdbId,+ youtubeTrailer = incoming.youtubeTrailer ?: current.youtubeTrailer,+ episodeRunTime = if (preserveDetails) current.episodeRunTime else incoming.episodeRunTime,+ isUserProtected = current.isUserProtected,+ cacheState = if (preserveDetails) current.cacheState else incoming.cacheState,+ detailHydratedAt = if (preserveDetails) current.detailHydratedAt else incoming.detailHydratedAt,+ remoteStaleAt = if (preserveDetails) current.remoteStaleAt else incoming.remoteStaleAt,+ episodePlaybackTemplateUrl = incoming.episodePlaybackTemplateUrl+ ?: current.episodePlaybackTemplateUrl+ )+ }+ }+ }insertAll(remapped)}@@ -2833,10 +2895,10 @@ interface EpisodeDao {@Daointerface CategoryDao {- @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY id ASC")+ @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY provider_order ASC, id ASC")fun getByProviderAndType(providerId: Long, type: String): Flow<List<CategoryEntity>>- @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY id ASC")+ @Query("SELECT * FROM categories WHERE provider_id = :providerId AND type = :type ORDER BY provider_order ASC, id ASC")suspend fun getByProviderAndTypeSync(providerId: Long, type: String): List<CategoryEntity>@Insert(onConflict = OnConflictStrategy.REPLACE)@@ -3485,6 +3547,9 @@ interface MovieCategoryHydrationDao {@Query("SELECT * FROM movie_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun get(providerId: Long, categoryId: Long): MovieCategoryHydrationEntity?+ @Query("SELECT * FROM movie_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ fun observe(providerId: Long, categoryId: Long): Flow<MovieCategoryHydrationEntity?>+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun upsert(metadata: MovieCategoryHydrationEntity)@@ -3500,6 +3565,9 @@ interface SeriesCategoryHydrationDao {@Query("SELECT * FROM series_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")suspend fun get(providerId: Long, categoryId: Long): SeriesCategoryHydrationEntity?+ @Query("SELECT * FROM series_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ fun observe(providerId: Long, categoryId: Long): Flow<SeriesCategoryHydrationEntity?>+@Insert(onConflict = OnConflictStrategy.REPLACE)suspend fun upsert(metadata: SeriesCategoryHydrationEntity)@@ -3510,6 +3578,48 @@ interface SeriesCategoryHydrationDao {suspend fun deleteByProvider(providerId: Long)}+@Dao+interface VodCategoryHydrationDao {+ @Query("SELECT * FROM vod_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ suspend fun get(providerId: Long, categoryId: Long): VodCategoryHydrationEntity?++ @Query("SELECT * FROM vod_category_hydration WHERE provider_id = :providerId AND category_id = :categoryId")+ fun observe(providerId: Long, categoryId: Long): Flow<VodCategoryHydrationEntity?>++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(metadata: VodCategoryHydrationEntity)++ @Query("DELETE FROM vod_category_hydration WHERE provider_id = :providerId")+ suspend fun deleteByProvider(providerId: Long)+}++@Dao+abstract class VodCatalogEntryDao {+ @Query("SELECT * FROM vod_catalog_entries WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY raw_page ASC, raw_index ASC")+ abstract fun observeByCategory(providerId: Long, categoryId: Long): Flow<List<VodCatalogEntryEntity>>++ @Query("SELECT COUNT(*) FROM vod_catalog_entries WHERE provider_id = :providerId AND category_id = :categoryId")+ abstract suspend fun countByCategory(providerId: Long, categoryId: Long): Int++ @Query("DELETE FROM vod_catalog_entries WHERE provider_id = :providerId AND category_id = :categoryId AND raw_page = :page")+ abstract suspend fun deletePage(providerId: Long, categoryId: Long, page: Int)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ abstract suspend fun insertAll(entries: List<VodCatalogEntryEntity>)++ @Transaction+ open suspend fun replacePage(providerId: Long, categoryId: Long, page: Int, entries: List<VodCatalogEntryEntity>) {+ deletePage(providerId, categoryId, page)+ if (entries.isNotEmpty()) insertAll(entries)+ }++ @Query("DELETE FROM vod_catalog_entries WHERE provider_id = :providerId AND category_id = :categoryId")+ abstract suspend fun deleteByCategory(providerId: Long, categoryId: Long)++ @Query("DELETE FROM vod_catalog_entries WHERE provider_id = :providerId")+ abstract suspend fun deleteByProvider(providerId: Long)+}+// ── EPG Source DAOs ────────────────────────────────────────────────@Daodiff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.ktindex 61e58f4d..ef2cc764 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@@ -7,9 +7,11 @@ import androidx.room.Fts4import androidx.room.Indeximport androidx.room.PrimaryKeyimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ProviderEpgSyncModeimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.SeriesCatalogOriginimport com.streamvault.domain.model.StalkerAuthModeimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.ChannelLogoSourcePolicy@@ -94,6 +96,8 @@ data class ProviderEntity(@ColumnInfo(name = "xtream_fast_sync_enabled") val xtreamFastSyncEnabled: Boolean = false,@ColumnInfo(name = "xtream_live_sync_mode") val xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,@ColumnInfo(name = "m3u_vod_classification_enabled") val m3uVodClassificationEnabled: Boolean = false,+ @ColumnInfo(name = "catalog_layout") val catalogLayout: CatalogLayout = CatalogLayout.SPLIT,+ @ColumnInfo(name = "catalog_layout_detection_version") val catalogLayoutDetectionVersion: Int = 0,val status: ProviderStatus = ProviderStatus.UNKNOWN,@ColumnInfo(name = "last_synced_at") val lastSyncedAt: Long = 0,@ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis()@@ -350,7 +354,9 @@ data class SeriesEntity(@ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "",@ColumnInfo(name = "cache_state") val cacheState: String = "DETAIL_HYDRATED",@ColumnInfo(name = "detail_hydrated_at") val detailHydratedAt: Long = 0L,- @ColumnInfo(name = "remote_stale_at") val remoteStaleAt: Long = 0L+ @ColumnInfo(name = "remote_stale_at") val remoteStaleAt: Long = 0L,+ @ColumnInfo(name = "catalog_origin") val catalogOrigin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE,+ @ColumnInfo(name = "episode_playback_template_url") val episodePlaybackTemplateUrl: String? = null)data class SeriesBrowseEntity(@@ -368,7 +374,9 @@ data class SeriesBrowseEntity(@ColumnInfo(name = "last_modified") val lastModified: Long = 0L,@ColumnInfo(name = "provider_id") val providerId: Long = 0,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,- @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false+ @ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,+ @ColumnInfo(name = "catalog_origin") val catalogOrigin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE,+ @ColumnInfo(name = "episode_playback_template_url") val episodePlaybackTemplateUrl: String? = null)@Fts4(contentEntity = ChannelEntity::class)@@ -478,6 +486,7 @@ data class CategoryEntity(@ColumnInfo(name = "parent_id") val parentId: Long? = null,val type: ContentType = ContentType.LIVE,@ColumnInfo(name = "provider_id") val providerId: Long = 0,+ @ColumnInfo(name = "provider_order", defaultValue = "0") val providerOrder: Int = 0,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false,@ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = ""@@ -620,6 +629,7 @@ data class CategoryImportStageEntity(val name: String,@ColumnInfo(name = "parent_id") val parentId: Long? = null,val type: ContentType = ContentType.LIVE,+ @ColumnInfo(name = "provider_order", defaultValue = "0") val providerOrder: Int = 0,@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,@ColumnInfo(name = "sync_fingerprint") val syncFingerprint: String = "")@@ -927,6 +937,63 @@ data class SeriesCategoryHydrationEntity(@ColumnInfo(name = "last_page_fingerprint") val lastPageFingerprint: String? = null)+@Entity(+ tableName = "vod_category_hydration",+ primaryKeys = ["provider_id", "category_id"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [Index(value = ["provider_id"])]+)+data class VodCategoryHydrationEntity(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "category_id") val categoryId: Long,+ @ColumnInfo(name = "last_loaded_page") val lastLoadedPage: Int = 0,+ @ColumnInfo(name = "last_attempted_page") val lastAttemptedPage: Int = 0,+ @ColumnInfo(name = "last_successful_page") val lastSuccessfulPage: Int = 0,+ @ColumnInfo(name = "total_pages") val totalPages: Int = 0,+ @ColumnInfo(name = "page_size") val pageSize: Int = 0,+ @ColumnInfo(name = "item_count") val itemCount: Int = 0,+ @ColumnInfo(name = "is_complete") val isComplete: Boolean = false,+ @ColumnInfo(name = "has_movies") val hasMovies: Boolean = false,+ @ColumnInfo(name = "has_series") val hasSeries: Boolean = false,+ @ColumnInfo(name = "last_hydrated_at") val lastHydratedAt: Long = 0L,+ @ColumnInfo(name = "last_status") val lastStatus: String = "IDLE",+ @ColumnInfo(name = "last_error") val lastError: String? = null,+ @ColumnInfo(name = "retry_after_ms") val retryAfterMs: Long = 0L,+ @ColumnInfo(name = "failure_count") val failureCount: Int = 0,+ @ColumnInfo(name = "retry_budget_remaining") val retryBudgetRemaining: Int = 3,+ @ColumnInfo(name = "last_page_fingerprint") val lastPageFingerprint: String? = null+)++@Entity(+ tableName = "vod_catalog_entries",+ primaryKeys = ["provider_id", "category_id", "raw_item_id"],+ foreignKeys = [ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )],+ indices = [+ Index(value = ["provider_id"]),+ Index(value = ["provider_id", "category_id", "raw_page", "raw_index"]),+ Index(value = ["provider_id", "item_type", "target_id"])+ ]+)+data class VodCatalogEntryEntity(+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "category_id") val categoryId: Long,+ @ColumnInfo(name = "raw_item_id") val rawItemId: String,+ @ColumnInfo(name = "item_type") val itemType: ContentType,+ @ColumnInfo(name = "target_id") val targetId: Long,+ @ColumnInfo(name = "raw_page") val rawPage: Int,+ @ColumnInfo(name = "raw_index") val rawIndex: Int+)+// ── External EPG Source ────────────────────────────────────────────@Entity(diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.ktindex 2c8e9c6f..99f9e8d0 100644--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt@@ -76,6 +76,8 @@ fun ProviderEntity.toDomain() = Provider(xtreamFastSyncEnabled = xtreamFastSyncEnabled,xtreamLiveSyncMode = xtreamLiveSyncMode,m3uVodClassificationEnabled = m3uVodClassificationEnabled,+ catalogLayout = catalogLayout,+ catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,status = status,lastSyncedAt = lastSyncedAt,createdAt = createdAt@@ -142,6 +144,8 @@ fun Provider.toEntity() = ProviderEntity(xtreamFastSyncEnabled = xtreamFastSyncEnabled,xtreamLiveSyncMode = xtreamLiveSyncMode,m3uVodClassificationEnabled = m3uVodClassificationEnabled,+ catalogLayout = catalogLayout,+ catalogLayoutDetectionVersion = catalogLayoutDetectionVersion,status = status,lastSyncedAt = lastSyncedAt,createdAt = createdAt@@ -366,7 +370,9 @@ fun SeriesEntity.toDomain() = Series(isAdult = isAdult,isUserProtected = isUserProtected,seriesId = seriesId,- providerSeriesId = providerSeriesId+ providerSeriesId = providerSeriesId,+ catalogOrigin = catalogOrigin,+ episodePlaybackTemplateUrl = episodePlaybackTemplateUrl)fun SeriesBrowseEntity.toDomain() = Series(@@ -390,7 +396,9 @@ fun SeriesBrowseEntity.toDomain() = Series(isAdult = isAdult,isUserProtected = isUserProtected,seriesId = seriesId,- providerSeriesId = providerSeriesId+ providerSeriesId = providerSeriesId,+ catalogOrigin = catalogOrigin,+ episodePlaybackTemplateUrl = episodePlaybackTemplateUrl)fun Series.toEntity() = SeriesEntity(@@ -416,7 +424,9 @@ fun Series.toEntity() = SeriesEntity(lastModified = lastModified,providerId = providerId,isAdult = isAdult,- isUserProtected = isUserProtected+ isUserProtected = isUserProtected,+ catalogOrigin = catalogOrigin,+ episodePlaybackTemplateUrl = episodePlaybackTemplateUrl)// ── Episode ────────────────────────────────────────────────────────@@ -495,6 +505,7 @@ fun CategoryEntity.toDomain() = com.streamvault.domain.model.Category(name = name,parentId = parentId,type = type,+ providerOrder = providerOrder,isAdult = isAdult,isUserProtected = isUserProtected)@@ -505,6 +516,7 @@ fun com.streamvault.domain.model.Category.toEntity(providerId: Long) = CategoryEparentId = parentId,type = type,providerId = providerId,+ providerOrder = providerOrder,isAdult = isAdult,isUserProtected = isUserProtected)diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.ktindex a1564577..89d18a0b 100644--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt@@ -135,6 +135,7 @@ class PreferencesRepository @Inject constructor(val LIVE_VARIANT_OBSERVATIONS = stringPreferencesKey("live_variant_observations")val VOD_VIEW_MODE = stringPreferencesKey("vod_view_mode")val VOD_INFINITE_SCROLL = booleanPreferencesKey("vod_infinite_scroll")+ val VOD_CATEGORY_LOAD_MODE = stringPreferencesKey("vod_category_load_mode")val VOD_DUPLICATE_HANDLING_MODE = stringPreferencesKey("vod_duplicate_handling_mode")val VOD_VARIANT_PREFERENCE_MODE = stringPreferencesKey("vod_variant_preference_mode")val VOD_VARIANT_SELECTIONS = stringPreferencesKey("vod_variant_selections")@@ -1319,6 +1320,24 @@ class PreferencesRepository @Inject constructor(}}+ fun getLastSplitCatalogType(providerId: Long): Flow<ContentType> {+ val key = stringPreferencesKey("last_split_catalog_type_$providerId")+ return context.dataStore.data.map { preferences ->+ when (preferences[key]) {+ ContentType.SERIES.name -> ContentType.SERIES+ else -> ContentType.MOVIE+ }+ }+ }++ suspend fun setLastSplitCatalogType(providerId: Long, type: ContentType) {+ require(type == ContentType.MOVIE || type == ContentType.SERIES)+ val key = stringPreferencesKey("last_split_catalog_type_$providerId")+ context.dataStore.edit { preferences ->+ preferences[key] = type.name+ }+ }+val appLanguage: Flow<String> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.APP_LANGUAGE] ?: "system"}@@ -1660,6 +1679,19 @@ class PreferencesRepository @Inject constructor(}}+ val vodCategoryLoadMode: Flow<com.streamvault.domain.model.VodCategoryLoadMode> =+ context.dataStore.data.map { preferences ->+ com.streamvault.domain.model.VodCategoryLoadMode.fromStorage(+ preferences[PreferencesKeys.VOD_CATEGORY_LOAD_MODE]+ )+ }++ suspend fun setVodCategoryLoadMode(mode: com.streamvault.domain.model.VodCategoryLoadMode) {+ context.dataStore.edit { preferences ->+ preferences[PreferencesKeys.VOD_CATEGORY_LOAD_MODE] = mode.storageValue+ }+ }+val guideDensity: Flow<String?> = context.dataStore.data.map { preferences ->preferences[PreferencesKeys.GUIDE_DENSITY]}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.ktindex 6585331e..b81084de 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt@@ -26,12 +26,15 @@ import java.io.InputStreamReaderimport java.net.URIimport java.net.InetSocketAddressimport java.net.Proxy+import java.net.SocketTimeoutException+import java.net.UnknownHostExceptionimport java.net.URLEncoderimport java.security.MessageDigestimport java.time.Instantimport java.time.LocalDateimport java.time.LocalDateTimeimport java.time.OffsetDateTime+import java.time.ZonedDateTimeimport java.time.ZoneIdimport java.time.ZoneOffsetimport java.time.format.DateTimeFormatter@@ -47,6 +50,7 @@ import javax.inject.Singletonimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.currentCoroutineContextimport kotlinx.coroutines.delayimport kotlinx.coroutines.launchimport kotlinx.coroutines.suspendCancellableCoroutine@@ -81,10 +85,14 @@ import kotlin.coroutines.resumeWithExceptionclass OkHttpStalkerApiService @Inject constructor(private val okHttpClient: OkHttpClient,private val json: Json,- private val transportFactory: StalkerTransportFactory = StalkerTransportFactory(okHttpClient)+ private val transportFactory: StalkerTransportFactory = StalkerTransportFactory(okHttpClient),+ private val requestCoordinator: StalkerRequestCoordinator = StalkerRequestCoordinator()) : StalkerApiService {+ private class DirectCreateLinkResponse(val playbackUrl: String) : IOException()+private data class SessionScope(val cookieJar: InMemoryStalkerCookieJar = InMemoryStalkerCookieJar(),+ @Volatile var macQueryRequired: Boolean = false,@Volatile var lastAccessAt: Long = System.currentTimeMillis())@@ -155,8 +163,13 @@ class OkHttpStalkerApiService @Inject constructor(val evidence = mutableListOf<String>()val recipeEvidence = mutableListOf("recipe:${recipe.recipe.name}", "preset:${recipe.magPreset.name}")val attemptProfile = profile.withRecipe(recipe, effectiveAuthMode)- val cookieJar = cookieJarFor(attemptProfile)- cookieJar.clear()+ val sessionScope = sessionScopeFor(attemptProfile)+ sessionScope.cookieJar.clear()+ val cookieJar = sessionScope.cookieJar+ // Compatibility discovery is per authentication scope. A portal may+ // change its request contract between profiles/endpoints, so do not+ // carry a MAC-query decision across a fresh authentication attempt.+ sessionScope.macQueryRequired = falseval handshakePayload = runCatching {requestJson(url = loadUrl,@@ -776,6 +789,29 @@ class OkHttpStalkerApiService @Inject constructor(session: StalkerSession,profile: StalkerDeviceProfile,seriesId: String+ ): Result<StalkerSeriesDetails> = getSeriesDetailsForType(+ session = session,+ profile = profile,+ seriesId = seriesId,+ contentType = "series"+ )++ override suspend fun getVodSeriesDetails(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ seriesId: String+ ): Result<StalkerSeriesDetails> = getSeriesDetailsForType(+ session = session,+ profile = profile,+ seriesId = seriesId,+ contentType = "vod"+ )++ private suspend fun getSeriesDetailsForType(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ seriesId: String,+ contentType: String): Result<StalkerSeriesDetails> = runApiCall("Failed to load series details") {val seriesPayload = requestJson(url = session.loadUrl,@@ -783,7 +819,7 @@ class OkHttpStalkerApiService @Inject constructor(referer = session.portalReferer,token = session.token,query = mapOf(- "type" to "series",+ "type" to contentType,"action" to "get_ordered_list","JsHttpRequest" to "1-xml","movie_id" to seriesId,@@ -791,7 +827,35 @@ class OkHttpStalkerApiService @Inject constructor("episode_id" to "0"))- val seedEntries = seriesPayload.extractItemEntries()+ val seedEntries = seriesPayload.extractItemEntries().toMutableList()+ if (contentType == "vod") {+ val seedFingerprints = mutableSetOf(+ seedEntries.joinToString("|") { it.findString("id").orEmpty() }+ )+ val seedTotalPages = seriesPayload.totalPages()+ for (page in 2..seedTotalPages) {+ val pagePayload = requestJson(+ url = session.loadUrl,+ profile = profile,+ referer = session.portalReferer,+ token = session.token,+ query = mapOf(+ "type" to contentType,+ "action" to "get_ordered_list",+ "JsHttpRequest" to "1-xml",+ "movie_id" to seriesId,+ "season_id" to "0",+ "episode_id" to "0",+ "p" to page.toString()+ )+ )+ val pageEntries = pagePayload.extractItemEntries()+ val fingerprint = pageEntries.joinToString("|") { it.findString("id").orEmpty() }+ if (fingerprint.isNotEmpty() && !seedFingerprints.add(fingerprint)) break+ seedEntries += pageEntries+ if (pageEntries.isEmpty()) break+ }+ }val seriesItems = seriesPayload.toItemRecords()val series = seriesItems.firstOrNull { item -> !item.looksLikeSeasonShell() }?: StalkerItemRecord(@@ -800,11 +864,12 @@ class OkHttpStalkerApiService @Inject constructor()val seasonRows = seedEntries.mapNotNull { entry ->- entry.findString("season_id")- ?.takeIf { it.isNotBlank() && it != "0" }- ?.let { seasonId ->- seasonId to entry- }+ val seasonId = if (contentType == "vod") {+ entry.findString("id")?.takeIf { entry.looksLikeVodSeasonShell() }+ } else {+ entry.findString("season_id")?.takeIf { it.isNotBlank() && it != "0" }+ }+ seasonId?.let { it to entry }}.distinctBy { it.first }val shellSeasonRows = seedEntries.mapIndexedNotNull { index, entry ->@@ -812,25 +877,22 @@ class OkHttpStalkerApiService @Inject constructor(?.let { season -> season.seasonNumber.toString() to entry }}+ val paginationEvidence = mutableListOf<StalkerEpisodePaginationEvidence>()val seasons = if (seasonRows.isNotEmpty()) {- seasonRows.map { (seasonId, entry) ->- val episodesPayload = requestJson(- url = session.loadUrl,+ seasonRows.mapIndexed { index, (seasonId, entry) ->+ val pages = fetchSeriesEpisodePages(+ session = session,profile = profile,- referer = session.portalReferer,- token = session.token,- query = mapOf(- "type" to "series",- "action" to "get_ordered_list",- "JsHttpRequest" to "1-xml",- "movie_id" to seriesId,- "season_id" to seasonId,- "episode_id" to "0"- )+ contentType = contentType,+ seriesId = seriesId,+ seasonSelector = seasonId)+ paginationEvidence += pages.evidenceentry.toSeasonRecord(- episodeEntries = episodesPayload.extractItemEntries(),- fallbackSeasonNumber = seasonId.toIntOrNull()+ episodeEntries = pages.entries,+ fallbackSeasonNumber = entry.findString("season_number")?.toIntOrNull()+ ?: entry.findString("season_id")?.toIntOrNull()+ ?: index + 1)}} else if (shellSeasonRows.isNotEmpty()) {@@ -841,7 +903,7 @@ class OkHttpStalkerApiService @Inject constructor(referer = session.portalReferer,token = session.token,query = mapOf(- "type" to "series",+ "type" to contentType,"action" to "get_ordered_list","JsHttpRequest" to "1-xml","movie_id" to seriesId,@@ -866,7 +928,86 @@ class OkHttpStalkerApiService @Inject constructor().filter { it.episodes.isNotEmpty() }}- StalkerSeriesDetails(series = series, seasons = seasons)+ StalkerSeriesDetails(+ series = series,+ seasons = seasons,+ paginationEvidence = paginationEvidence+ )+ }++ private data class EpisodePages(+ val entries: List<JsonObject>,+ val evidence: StalkerEpisodePaginationEvidence+ )++ private suspend fun fetchSeriesEpisodePages(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ contentType: String,+ seriesId: String,+ seasonSelector: String+ ): EpisodePages {+ val entries = mutableListOf<JsonObject>()+ val fingerprints = mutableSetOf<String>()+ var page = 1+ var successfulPages = 0+ var advertisedPages: Int? = null+ var repeated = false+ var malformed = false+ while (page <= (advertisedPages ?: 1).coerceAtMost(MAX_PAGE_COUNT)) {+ val payload = requestJson(+ url = session.loadUrl,+ profile = profile,+ referer = session.portalReferer,+ token = session.token,+ query = mapOf(+ "type" to contentType,+ "action" to "get_ordered_list",+ "JsHttpRequest" to "1-xml",+ "movie_id" to seriesId,+ "season_id" to seasonSelector,+ "episode_id" to "0",+ "p" to page.toString()+ )+ )+ val pageEntries = payload.extractItemEntries()+ val fingerprint = pageEntries.joinToString("|") { entry ->+ listOf(+ entry.findString("id").orEmpty(),+ entry.findString("series_number").orEmpty(),+ entry.findString("name").orEmpty()+ ).joinToString(":")+ }+ if (page > 1 && fingerprint.isNotEmpty() && !fingerprints.add(fingerprint)) {+ repeated = true+ break+ }+ if (fingerprint.isNotEmpty()) fingerprints += fingerprint+ entries += pageEntries+ successfulPages += 1+ val reported = payload.advertisedTotalPages()+ if (reported != null) {+ if (advertisedPages != null && advertisedPages != reported) malformed = true+ advertisedPages = maxOf(advertisedPages ?: 1, reported)+ }+ if (pageEntries.isEmpty()) {+ if (page < (advertisedPages ?: 1)) malformed = true+ break+ }+ if (page >= (advertisedPages ?: 1)) break+ page += 1+ }+ return EpisodePages(+ entries = entries,+ evidence = StalkerEpisodePaginationEvidence(+ seasonSelector = seasonSelector,+ attemptedPages = page,+ successfulPages = successfulPages,+ advertisedTotalPages = advertisedPages,+ repeatedPageDetected = repeated,+ malformedPagination = malformed+ )+ )}override suspend fun getShortEpg(@@ -1012,22 +1153,39 @@ class OkHttpStalkerApiService @Inject constructor(StalkerStreamKind.EPISODE -> "0"}val playbackLoadUrl = createLinkLoadUrl(session)- val payload = requestJson(- url = playbackLoadUrl,- profile = profile,- referer = session.portalReferer,- token = session.token,- query = mapOf(- "type" to type,- "action" to "create_link",- "JsHttpRequest" to "1-xml",- "cmd" to cmd,- "series" to seriesSelector,- "forced_storage" to forcedStorage,- "disable_ad" to "0",- "download" to "0"+ val payload = try {+ requestJson(+ url = playbackLoadUrl,+ profile = profile,+ referer = session.portalReferer,+ token = session.token,+ query = mapOf(+ "type" to type,+ "action" to "create_link",+ "JsHttpRequest" to "1-xml",+ "cmd" to cmd,+ "series" to seriesSelector,+ "forced_storage" to forcedStorage,+ "disable_ad" to "0",+ "download" to "0"+ ))- )+ } catch (direct: DirectCreateLinkResponse) {+ return@runApiCall direct.playbackUrl+ }+ val portalError = payload.findString("error")+ ?.trim()+ ?.takeIf { it.isNotBlank() && !it.equals("false", ignoreCase = true) && it != "0" }+ if (portalError != null) {+ val normalized = portalError.lowercase(Locale.ROOT)+ if (normalized == "nothing_to_play" || normalized.contains("nothing to play")) {+ throw StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")+ }+ if (isStalkerAuthorizationFailure(portalError, null)) {+ throw StalkerApiError.Authorization(portalReason = normalized)+ }+ throw StalkerApiError.Malformed("Portal returned a playback error.")+ }payload.findString("cmd")?.substringAfter(' ', missingDelimiterValue = payload.findString("cmd").orEmpty())?.trim()@@ -1043,11 +1201,13 @@ class OkHttpStalkerApiService @Inject constructor(resolved}if (!StreamEntryUrlPolicy.isAllowed(playbackUrl)) {- throw IOException("Portal returned an unsupported playback URL scheme for create_link.")+ throw StalkerApiError.UnsupportedProtocol(+ "Portal returned an unsupported playback URL scheme."+ )}playbackUrl}- ?: throw IOException("Portal did not return a playable URL.")+ ?: throw StalkerApiError.Malformed("Portal did not return a playable URL.")}private fun createLinkLoadUrl(session: StalkerSession): String {@@ -1158,53 +1318,102 @@ class OkHttpStalkerApiService @Inject constructor(body: String? = null): JsonElement = withContext(Dispatchers.IO) {val effectiveQuery = prepareQuery(profile, query)- val action = effectiveQuery["action"]- val fullUrl = buildUrl(url, effectiveQuery)- val requestBuilder = Request.Builder()- .url(fullUrl)- .header("User-Agent", profile.userAgent)- .header("X-User-Agent", profile.xUserAgent)- .header("Referer", referer)- .header("Accept", "*/*")- .header("Cookie", buildCookieHeader(fullUrl, profile))- .apply {- token?.takeIf { it.isNotBlank() }?.let { header("Authorization", "Bearer $it") }- }- .applyStalkerHeaderOverrides(- headerOverrides = profile.headerOverrides,- preserveUserAgent = profile.advancedOptions.apiUserAgent.isNotBlank()- )val requestBody = body?.toRequestBody(FORM_URL_ENCODED_MEDIA_TYPE)- val request = requestBuilder- .method(method, requestBody)- .build()+ val action = effectiveQuery["action"]+ val sessionScope = sessionScopeFor(profile)- runCatching {- executeJsonRequest(request, action, profile)- }.recoverCatching { error ->- if (error is CancellationException) throw error- if (!allowAlternateEndpointRetry) throw error- val alternateUrl = siblingLoadUrl(url)- ?.takeIf { it != url }- ?: throw error- Log.w(- TAG,- "Retrying Stalker ${action.orEmpty()} via alternate endpoint $alternateUrl after ${error.message}"- )- val alternateRequest = request.newBuilder()- .url(buildUrl(alternateUrl, effectiveQuery))- .header("Referer", StalkerUrlFactory.portalReferer(alternateUrl))- .header("Cookie", buildCookieHeader(buildUrl(alternateUrl, effectiveQuery), profile))+ suspend fun executeRequest(requestQuery: Map<String, String>): JsonElement {+ val fullUrl = buildUrl(url, requestQuery)+ val requestBuilder = Request.Builder()+ .url(fullUrl)+ .header("User-Agent", profile.userAgent)+ .header("X-User-Agent", profile.xUserAgent)+ .header("Referer", referer)+ .header("Accept", "*/*")+ .header("Cookie", buildCookieHeader(fullUrl, profile))+ .apply {+ token?.takeIf { it.isNotBlank() }?.let { header("Authorization", "Bearer $it") }+ }.applyStalkerHeaderOverrides(headerOverrides = profile.headerOverrides,preserveUserAgent = profile.advancedOptions.apiUserAgent.isNotBlank())+ val request = requestBuilder.method(method, requestBody).build()- executeJsonRequest(alternateRequest, action, profile)- }.getOrElse { throw it }++ return runCatching {+ executeJsonRequest(request, action, profile)+ }.recoverCatching { error ->+ if (error is CancellationException) throw error+ if (!allowAlternateEndpointRetry) throw error+ val alternateUrl = siblingLoadUrl(url)+ ?.takeIf { it != url }+ ?: throw error+ Log.w(+ TAG,+ "Retrying Stalker ${action.orEmpty()} via alternate endpoint $alternateUrl after ${error.message}"+ )+ val alternateFullUrl = buildUrl(alternateUrl, requestQuery)+ val alternateRequest = request.newBuilder()+ .url(alternateFullUrl)+ .header("Referer", StalkerUrlFactory.portalReferer(alternateUrl))+ .header("Cookie", buildCookieHeader(alternateFullUrl, profile))+ .applyStalkerHeaderOverrides(+ headerOverrides = profile.headerOverrides,+ preserveUserAgent = profile.advancedOptions.apiUserAgent.isNotBlank()+ )+ .method(method, requestBody)+ .build()+ executeJsonRequest(alternateRequest, action, profile)+ }.getOrElse { throw it }+ }++ val initialQuery = if (+ sessionScope.macQueryRequired &&+ profile.macAddress.isNotBlank() &&+ !effectiveQuery.containsKey("mac")+ ) {+ effectiveQuery.withMacQuery(profile)+ } else {+ effectiveQuery+ }++ try {+ executeRequest(initialQuery)+ } catch (error: StalkerApiError.EmptyBody) {+ // A few MAG/Ministra deployments reject the normal MAG cookie-only form by+ // returning HTTP 200 with an empty body, while accepting the same request when+ // the MAC is also present as a query parameter. Retry only this unambiguous+ // signal, learn it for the current auth scope, and leave other portal behavior+ // untouched.+ if (+ profile.macAddress.isBlank() ||+ initialQuery.containsKey("mac") ||+ sessionScope.macQueryRequired ||+ !shouldRetryWithMacQuery(action)+ ) {+ throw error+ }+ sessionScope.macQueryRequired = true+ Log.i(+ TAG,+ "Stalker portal requires MAC query authentication; retrying action=${action.orEmpty()}"+ )+ executeRequest(effectiveQuery.withMacQuery(profile))+ }}+ private fun Map<String, String>.withMacQuery(profile: StalkerDeviceProfile): Map<String, String> =+ LinkedHashMap(this).apply { put("mac", profile.macAddress) }++ private fun shouldRetryWithMacQuery(action: String?): Boolean =+ action.equals("handshake", ignoreCase = true) ||+ action.equals("get_profile", ignoreCase = true) ||+ action.equals("get_account_info", ignoreCase = true) ||+ action.equals("do_auth", ignoreCase = true) ||+ action.equals("create_link", ignoreCase = true)+private suspend fun executeJsonRequest(request: Request, action: String?, profile: StalkerDeviceProfile): JsonElement {profile.discoveryRuntime.consumeRequest()val startedAt = System.currentTimeMillis()@@ -1231,8 +1440,40 @@ class OkHttpStalkerApiService @Inject constructor(throw response.toStalkerHttpError(htmlErrorPage)}val responseBody = response.body- ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")+ ?: throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")+ if (responseBody.contentLength() == 0L) {+ responseBody.close()+ throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")+ }+ if (action.equals("create_link", ignoreCase = true) && response.isDirectMediaResponse()) {+ Log.i(+ TAG,+ "Stalker create_link returned a direct media response; handing the authenticated endpoint to playback " ++ "type=${response.header("Content-Type").orEmpty().substringBefore(';').ifBlank { "unknown" }}"+ )+ throw DirectCreateLinkResponse(request.url.toString())+ }val charset = responseBody.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8+ if (action.equals("create_link", ignoreCase = true)) {+ // Some Ministra portals put the small, authoritative `js` result first and+ // then append a very large diagnostic `text` field (stack traces, storage+ // timeout details, and repeated backend output). Parsing the entire document+ // both delays playback resolution and can hide `nothing_to_play` behind the+ // generic response-size guard. Read only the `js` value and close the response;+ // the trailing diagnostic text is not part of the playback contract.+ val parsed = parseCreateLinkEnvelope(responseBody.byteStream(), charset.name(), action)+ parsed.ensureNoPortalError()+ StalkerTelemetry.httpResponse(+ providerId = profile.providerId,+ endpointFamily = endpointFamily(request),+ action = action,+ durationMillis = System.currentTimeMillis() - startedAt,+ responseBytes = responseBody.contentLength().coerceAtLeast(0L),+ status = response.code,+ outcome = "SUCCESS"+ )+ return@withTransportAwareStalkerCall parsed+ }val raw = readBodyBounded(stream = responseBody.byteStream(),charsetName = charset.name(),@@ -1240,7 +1481,7 @@ class OkHttpStalkerApiService @Inject constructor(action = action)if (raw.isBlank()) {- throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")+ throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")}val parsed = parsePortalJson(raw, action)parsed.ensureNoPortalError()@@ -1257,6 +1498,55 @@ class OkHttpStalkerApiService @Inject constructor(}}+ private fun parseCreateLinkEnvelope(+ stream: InputStream,+ charsetName: String,+ action: String?+ ): JsonElement {+ val charset = runCatching { java.nio.charset.Charset.forName(charsetName) }+ .getOrDefault(Charsets.UTF_8)+ val reader = JsonReader(InputStreamReader(stream, charset)).apply { isLenient = true }+ try {+ if (reader.peek() == JsonToken.END_DOCUMENT) {+ throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")+ }+ if (reader.peek() != JsonToken.BEGIN_OBJECT) {+ throw StalkerApiError.Malformed(+ "Portal returned an unreadable playback response${actionSuffix(action)}."+ )+ }+ reader.beginObject()+ while (reader.hasNext()) {+ when (reader.nextName()) {+ "js" -> {+ val jsValue = JsonParser.parseReader(reader)+ return parsePortalJson("{\"js\":${jsValue}}", action)+ }+ "error" -> {+ val rawError = reader.nextStringOrSkip()+ rawError?.let(::portalError)?.let { throw it }+ }+ "not_valid_token" -> {+ val marker = reader.nextStringOrSkip()+ if (marker != null && !isPlaceholderErrorValue(marker)) {+ throw invalidTokenError()+ }+ }+ else -> reader.skipValue()+ }+ }+ throw StalkerApiError.Malformed("Portal did not return a playback result.")+ } catch (error: StalkerApiError) {+ throw error+ } catch (error: IOException) {+ throw error+ } catch (error: RuntimeException) {+ throw StalkerApiError.Malformed(+ "Portal returned an unreadable playback response${actionSuffix(action)}."+ )+ }+ }+/*** Reads [stream] into a String, throwing [IOException] if the body exceeds [maxBytes].* This prevents unbounded heap allocation when portals return unexpectedly large responses.@@ -1347,7 +1637,7 @@ class OkHttpStalkerApiService @Inject constructor(if (!response.isSuccessful) {throw response.toStalkerHttpError()}- val body = response.body ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")+ val body = response.body ?: throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8val reader = JsonReader(InputStreamReader(body.byteStream(), charset))reader.isLenient = true@@ -1498,7 +1788,7 @@ class OkHttpStalkerApiService @Inject constructor(if (!response.isSuccessful) {throw response.toStalkerHttpError()}- val body = response.body ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")+ val body = response.body ?: throw StalkerApiError.EmptyBody("Portal returned an empty response${actionSuffix(action)}.")val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8val limited = ByteSizeLimitInputStream(delegate = body.byteStream(),@@ -1676,6 +1966,15 @@ class OkHttpStalkerApiService @Inject constructor(if (findBoolean("not_valid_token") == true) {throw invalidTokenError()}+ // Some Ministra/Stalker families return workflow failures as a scalar `js`+ // payload instead of the usual `{ "js": { "error": ... } }` envelope.+ // Treat that scalar as a portal outcome so create_link cannot degrade+ // `nothing_to_play` into the misleading "no playable URL" error.+ rootObjectOrNull()+ ?.get("js")+ ?.let { it as? JsonPrimitive }+ ?.contentOrNull+ ?.let { portalError(it)?.let { error -> throw error } }val raw = rootObjectOrNull()?.findString("error")?: findString("error")raw?.let { portalError(it)?.let { error -> throw error } }@@ -1946,6 +2245,8 @@ class OkHttpStalkerApiService @Inject constructor(if (raw.isBlank() || isPlaceholderErrorValue(raw)) return nullval normalized = raw.lowercase(Locale.ROOT)return when {+ normalized == "nothing_to_play" || normalized.contains("nothing to play") ->+ StalkerApiError.ContentUnavailable(portalReason = "nothing_to_play")listOf("not valid mac", "invalid mac").any(normalized::contains) ->StalkerApiError.InvalidMac(raw, raw)listOf("not_valid_token", "invalid token", "empty token").any(normalized::contains) ->@@ -1988,16 +2289,16 @@ class OkHttpStalkerApiService @Inject constructor(else -> error}attempt += 1- val retryable = typed is StalkerApiError.RateLimited ||- typed is StalkerApiError.Transport ||+ // A 429 opens the provider-wide circuit breaker. Retrying inside the+ // individual API operation would defeat that cooldown.+ val retryable = typed is StalkerApiError.Transport ||(typed is StalkerApiError.Server && (typed.httpStatus ?: 500) >= 500)if (!retryable || attempt >= MAX_OPERATION_ATTEMPTS) {return Result.error(typed.message ?: message, typed)}- val retryAfter = (typed as? StalkerApiError.RateLimited)?.retryAfterMillisval exponential = 250L shl (attempt - 1)val jitter = kotlin.random.Random.nextLong(100L, 401L)- delay((retryAfter ?: (exponential + jitter)).coerceIn(100L, MAX_RETRY_DELAY_MILLIS))+ delay((exponential + jitter).coerceIn(100L, MAX_RETRY_DELAY_MILLIS))}}}@@ -2107,7 +2408,12 @@ class OkHttpStalkerApiService @Inject constructor(is StalkerApiError.ModelRejected -> "MODEL_REJECTED"is StalkerApiError.Server -> "SERVER_ERROR"is StalkerApiError.Transport -> "TRANSPORT_ERROR"+ is StalkerApiError.EmptyBody -> "EMPTY_BODY"+ is StalkerApiError.TransportConsentRequired -> "TRANSPORT_CONSENT"is StalkerApiError.Malformed -> "MALFORMED_RESPONSE"+ is SocketTimeoutException -> "TIMEOUT"+ is UnknownHostException -> "DNS_ERROR"+ is IOException -> "IO_ERROR"else -> "FAILED"}@@ -2160,6 +2466,22 @@ class OkHttpStalkerApiService @Inject constructor(profile: StalkerDeviceProfile,block: suspend (Response) -> T): T {+ val requestPriority = when {+ request.url.queryParameter("action").equals("create_link", ignoreCase = true) ->+ StalkerNetworkPriority.INTERACTIVE+ currentCoroutineContext()[StalkerRequestPriorityContext]?.priority in setOf(+ com.streamvault.domain.model.StalkerRequestPriority.EPG,+ com.streamvault.domain.model.StalkerRequestPriority.BACKGROUND_INDEX+ ) -> StalkerNetworkPriority.BACKGROUND+ currentCoroutineContext()[StalkerRequestPriorityContext]?.priority ==+ com.streamvault.domain.model.StalkerRequestPriority.VISIBLE_PREVIEW ->+ StalkerNetworkPriority.PREFETCH+ request.url.queryParameter("action").equals("get_epg_info", ignoreCase = true) ->+ StalkerNetworkPriority.BACKGROUND+ else -> StalkerNetworkPriority.FOREGROUND+ }+ val permit = requestCoordinator.acquireNetworkPermit(profile.providerId, requestPriority)+ var nonRateLimitedResponseObserved = falsereturn try {val baseClient = stalkerHttpClientFor(profile, request.url.toString())val remainingMillis = profile.discoveryRuntime.remainingMillis()@@ -2170,18 +2492,57 @@ class OkHttpStalkerApiService @Inject constructor(.callTimeout(remainingMillis, TimeUnit.MILLISECONDS).build()}- withCancellableStalkerCall(client.newCall(request), block)+ withCancellableStalkerCall(client.newCall(request)) { response ->+ if (response.code != 429) {+ nonRateLimitedResponseObserved = true+ requestCoordinator.recordNetworkSuccess(permit)+ }+ block(response)+ }} catch (error: CancellationException) {throw error} catch (error: Throwable) {+ if (!nonRateLimitedResponseObserved) {+ requestCoordinator.recordNetworkFailure(permit, error)+ }if (error is StalkerApiError.TransportConsentRequired) throw errortransportFactory.challengeForTlsFailure(request.url.toString(), error)?.let { challenge ->throw StalkerApiError.TransportConsentRequired(challenge)}throw error+ } finally {+ requestCoordinator.releaseNetworkPermit(permit)}}+ private fun Response.isDirectMediaResponse(): Boolean {+ val prefix = runCatching { peekBody(CREATE_LINK_SNIFF_BYTES).bytes() }.getOrDefault(byteArrayOf())+ val firstNonWhitespace = prefix.firstOrNull { byte ->+ byte.toInt().toChar() !in setOf(' ', '\t', '\r', '\n')+ }?.toInt()?.and(0xff)+ // Incorrect application/octet-stream headers are common. JSON, XML, and HTML+ // envelopes must still go through the semantic parser.+ if (firstNonWhitespace in setOf('{'.code, '['.code, '<'.code)) return false++ val mime = header("Content-Type").orEmpty().substringBefore(';').trim().lowercase(Locale.ROOT)+ if (mime.startsWith("video/") || mime.startsWith("audio/") || mime in setOf(+ "application/octet-stream",+ "application/vnd.apple.mpegurl",+ "application/x-mpegurl"+ )+ ) return true++ fun startsWith(vararg expected: Int): Boolean = expected.indices.all { index ->+ prefix.getOrNull(index)?.toInt()?.and(0xff) == expected[index]+ }+ val mpegProgramStream = startsWith(0x00, 0x00, 0x01, 0xba)+ val matroska = startsWith(0x1a, 0x45, 0xdf, 0xa3)+ val mp4 = prefix.size >= 8 && prefix.copyOfRange(4, 8).contentEquals("ftyp".toByteArray())+ val transportStream = prefix.firstOrNull()?.toInt()?.and(0xff) == 0x47 &&+ (prefix.getOrNull(188)?.toInt()?.and(0xff) == 0x47 || prefix.size < 189)+ return mpegProgramStream || matroska || mp4 || transportStream+ }+private fun stalkerHttpClientFor(profile: StalkerDeviceProfile, url: String): OkHttpClient {val proxy = profile.advancedOptions.proxyval scopeKey = sessionScopeKey(profile)@@ -2342,9 +2703,16 @@ class OkHttpStalkerApiService @Inject constructor(private fun Response.toStalkerHttpError(htmlErrorPage: Boolean = false): StalkerApiError {val retryAfterMillis = header("Retry-After")?.trim()- ?.toLongOrNull()- ?.coerceAtLeast(0L)- ?.times(1000L)+ ?.let { raw ->+ raw.toLongOrNull()+ ?.coerceAtLeast(0L)+ ?.times(1000L)+ ?: runCatching {+ (ZonedDateTime.parse(raw, DateTimeFormatter.RFC_1123_DATE_TIME)+ .toInstant()+ .toEpochMilli() - System.currentTimeMillis()).coerceAtLeast(0L)+ }.getOrNull()+ }return when (code) {401, 403 -> if (htmlErrorPage) {StalkerApiError.BlockedOrConfiguration(@@ -2371,7 +2739,7 @@ class OkHttpStalkerApiService @Inject constructor(}}- private fun cookieJarFor(profile: StalkerDeviceProfile): InMemoryStalkerCookieJar {+ private fun sessionScopeFor(profile: StalkerDeviceProfile): SessionScope {val now = System.currentTimeMillis()val key = sessionScopeKey(profile)val scope = sessionScopes.computeIfAbsent(key) { SessionScope(lastAccessAt = now) }@@ -2392,9 +2760,12 @@ class OkHttpStalkerApiService @Inject constructor(stalkerHttpClients.keys.removeIf { clientKey -> clientKey.startsWith("$staleKey|") }}}- return scope.cookieJar+ return scope}+ private fun cookieJarFor(profile: StalkerDeviceProfile): InMemoryStalkerCookieJar =+ sessionScopeFor(profile).cookieJar+private fun sessionScopeKey(profile: StalkerDeviceProfile): String {val normalized = listOf(StalkerUrlFactory.normalizePortalUrl(profile.portalUrl),@@ -2661,7 +3032,9 @@ class OkHttpStalkerApiService @Inject constructor(),addedAt = parseDateTime(findString("added")) ?: 0L,isAdult = findBoolean("censored") == true,- isSeries = findBoolean("is_series") == true || findString("is_series") == "1"+ isSeries = findBoolean("is_series") == true || findString("is_series") == "1",+ hasSeriesMarker = findString("is_series")?.trim()?.lowercase() in+ setOf("0", "1", "true", "false"))}@@ -2737,7 +3110,9 @@ class OkHttpStalkerApiService @Inject constructor(),addedAt = parseDateTime(findString("added")) ?: 0L,isAdult = findBoolean("censored") == true,- isSeries = findBoolean("is_series") == true || findString("is_series") == "1"+ isSeries = findBoolean("is_series") == true || findString("is_series") == "1",+ hasSeriesMarker = findString("is_series")?.trim()?.lowercase() in+ setOf("0", "1", "true", "false"))}@@ -2787,8 +3162,8 @@ class OkHttpStalkerApiService @Inject constructor(episodeEntries: List<JsonObject>,fallbackSeasonNumber: Int? = null): StalkerSeasonRecord {- val seasonNumber = findString("season_id")?.toIntOrNull()- ?: findString("season_number")?.toIntOrNull()+ val seasonNumber = findString("season_number")?.toIntOrNull()+ ?: findString("season_id")?.toIntOrNull()?: extractSeasonNumberFromCmd(findString("cmd"))?: fallbackSeasonNumber?: 1@@ -2798,12 +3173,13 @@ class OkHttpStalkerApiService @Inject constructor(val explicitEpisodes = episodeEntries.filterNot { entry -> entry.looksLikeSeasonShellRow() }.mapIndexedNotNull { index, entry ->- entry.toEpisodeRecord(index + 1, seasonNumber)+ entry.toEpisodeRecord(index + 1, seasonNumber)?.copy(seasonNumber = seasonNumber)}return StalkerSeasonRecord(seasonNumber = seasonNumber,name = seasonName,coverUrl = sanitizeUrl(findString("screenshot_uri")) ?: sanitizeUrl(findString("cover")),+ cmd = findString("cmd"),episodes = explicitEpisodes.takeUnless { it.isEmpty() || it.isSeasonShellOnly() }?: buildEpisodesFromSeriesShell(seasonNumber, seasonName))@@ -2826,6 +3202,7 @@ class OkHttpStalkerApiService @Inject constructor(seasonNumber = seasonNumber,name = seasonName,coverUrl = sanitizeUrl(findString("screenshot_uri")) ?: sanitizeUrl(findString("cover")),+ cmd = findString("cmd"),episodes = buildEpisodesFromSeriesShell(seasonNumber, seasonName))}@@ -2851,6 +3228,8 @@ class OkHttpStalkerApiService @Inject constructor(?: findString("season_number")?.toIntOrNull()?: fallbackSeasonNumber,cmd = findString("cmd"),+ playbackSelector = findString("series_number")?.toIntOrNull()+ ?: findString("episode_number")?.toIntOrNull(),coverUrl = sanitizeUrl(findString("screenshot_uri")) ?: sanitizeUrl(findString("cover")),plot = findString("description") ?: findString("plot"),durationSeconds = findString("duration")?.toIntOrNull() ?: 0,@@ -2878,6 +3257,12 @@ class OkHttpStalkerApiService @Inject constructor(return extractSeasonNumberFromCmd(findString("cmd")) != null}+ private fun JsonObject.looksLikeVodSeasonShell(): Boolean {+ if (findBoolean("is_season") == true || findString("is_season") == "1") return true+ if (findString("video_id") != null && findString("series_number") == null) return true+ return looksLikeSeasonShellRow()+ }+private fun JsonObject.buildEpisodesFromSeriesShell(fallbackSeasonNumber: Int,fallbackSeasonName: String@@ -3502,6 +3887,7 @@ class OkHttpStalkerApiService @Inject constructor(private const val MAX_OPERATION_ATTEMPTS = 3private const val MAX_RETRY_DELAY_MILLIS = 30_000Lprivate const val HTML_ERROR_SNIFF_BYTES = 2_048L+ private const val CREATE_LINK_SNIFF_BYTES = 512Lprivate const val PORTAL_BASE_HINT_TIMEOUT_MILLIS = 8_000Lprivate const val SESSION_SCOPE_IDLE_MILLIS = 30 * 60_000Lprivate const val DEFAULT_PROGRAM_DURATION_MILLIS = 30 * 60_000Ldiff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.ktindex 3713cbad..22f58b48 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt@@ -74,6 +74,12 @@ sealed class StalkerApiError(val challenge: StalkerTransportChallenge) : StalkerApiError("Transport consent is required for ${challenge.displayHost}.")class Malformed(message: String, cause: Throwable? = null) : StalkerApiError(message, cause)+ class EmptyBody(message: String) : StalkerApiError(message)+ class ContentUnavailable(+ override val portalReason: String? = null,+ message: String = "The provider reported that this item is currently unavailable."+ ) : StalkerApiError(message, portalReason = portalReason)+ class UnsupportedProtocol(message: String) : StalkerApiError(message)class ResponseTooLarge(message: String) : StalkerApiError(message)class DiscoveryBudgetExceeded(message: String) : StalkerApiError(message)class ReadinessInconclusive(diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.ktindex 78d453f2..1f0ed007 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt@@ -208,7 +208,8 @@ data class StalkerItemRecord(val archiveAvailable: Boolean? = null,val addedAt: Long = 0L,val isAdult: Boolean = false,- val isSeries: Boolean = false+ val isSeries: Boolean = false,+ val hasSeriesMarker: Boolean = false)data class StalkerPagedItems(@@ -226,13 +227,24 @@ data class StalkerPagedItems(data class StalkerSeriesDetails(val series: StalkerItemRecord,- val seasons: List<StalkerSeasonRecord>+ val seasons: List<StalkerSeasonRecord>,+ val paginationEvidence: List<StalkerEpisodePaginationEvidence> = emptyList()+)++data class StalkerEpisodePaginationEvidence(+ val seasonSelector: String,+ val attemptedPages: Int,+ val successfulPages: Int,+ val advertisedTotalPages: Int?,+ val repeatedPageDetected: Boolean = false,+ val malformedPagination: Boolean = false)data class StalkerSeasonRecord(val seasonNumber: Int,val name: String,val coverUrl: String? = null,+ val cmd: String? = null,val episodes: List<StalkerEpisodeRecord>)@@ -242,6 +254,7 @@ data class StalkerEpisodeRecord(val episodeNumber: Int,val seasonNumber: Int,val cmd: String? = null,+ val playbackSelector: Int? = null,val coverUrl: String? = null,val plot: String? = null,val durationSeconds: Int = 0,@@ -323,6 +336,12 @@ interface StalkerApiService {seriesId: String): Result<StalkerSeriesDetails>+ suspend fun getVodSeriesDetails(+ session: StalkerSession,+ profile: StalkerDeviceProfile,+ seriesId: String+ ): Result<StalkerSeriesDetails> = getSeriesDetails(session, profile, seriesId)+suspend fun getShortEpg(session: StalkerSession,profile: StalkerDeviceProfile,diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerContentCapabilities.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerContentCapabilities.ktnew file mode 100644index 00000000..cba16a85--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerContentCapabilities.kt@@ -0,0 +1,87 @@+package com.streamvault.data.remote.stalker++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.decodeFromJsonElement+import kotlinx.serialization.json.encodeToJsonElement+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.put++@Serializable+enum class StalkerSeriesDetailDialect {+ UNKNOWN,+ NATIVE_SERIES,+ VOD_SEASON_SHELLS,+ INLINE_EPISODES+}++@Serializable+enum class StalkerEpisodeSelectorDialect {+ UNKNOWN,+ EPISODE_COMMAND,+ PARENT_COMMAND_WITH_SERIES_NUMBER+}++@Serializable+enum class StalkerVodPlaybackDialect {+ UNKNOWN,+ DIRECT,+ CREATE_LINK,+ PORTAL_MOVIE_ENDPOINT+}++@Serializable+data class StalkerContentCapabilities(+ val version: Int = CURRENT_VERSION,+ val revision: Int = CURRENT_REVISION,+ val configurationGeneration: Int = 0,+ val seriesDetailDialect: StalkerSeriesDetailDialect = StalkerSeriesDetailDialect.UNKNOWN,+ val episodeSelectorDialect: StalkerEpisodeSelectorDialect = StalkerEpisodeSelectorDialect.UNKNOWN,+ val vodPlaybackDialect: StalkerVodPlaybackDialect = StalkerVodPlaybackDialect.UNKNOWN,+ val validationEvidence: List<String> = emptyList()+) {+ fun validFor(generation: Int): Boolean =+ version == CURRENT_VERSION && configurationGeneration == generation++ companion object {+ const val CURRENT_VERSION = 1+ const val CURRENT_REVISION = 1+ }+}++object StalkerContentCapabilitiesCodec {+ private const val CONTENT_KEY = "contentCapabilities"+ private val json = Json {+ ignoreUnknownKeys = true+ encodeDefaults = true+ }++ fun decode(raw: String?, configurationGeneration: Int): StalkerContentCapabilities {+ if (raw.isNullOrBlank()) return StalkerContentCapabilities(configurationGeneration = configurationGeneration)+ val root = runCatching { json.parseToJsonElement(raw).jsonObject }.getOrNull()+ ?: return StalkerContentCapabilities(configurationGeneration = configurationGeneration)+ val content = root[CONTENT_KEY] ?: return StalkerContentCapabilities(+ configurationGeneration = configurationGeneration+ )+ val decoded = runCatching {+ json.decodeFromJsonElement<StalkerContentCapabilities>(content)+ }.getOrNull() ?: return StalkerContentCapabilities(configurationGeneration = configurationGeneration)+ return decoded.takeIf { it.validFor(configurationGeneration) }+ ?: StalkerContentCapabilities(configurationGeneration = configurationGeneration)+ }++ /** Keeps the legacy flat LIVE/VOD/SERIES keys intact for diagnostics and older builds. */+ fun encode(existingRaw: String?, capabilities: StalkerContentCapabilities): String {+ val existing = existingRaw+ ?.takeIf(String::isNotBlank)+ ?.let { runCatching { json.parseToJsonElement(it).jsonObject }.getOrNull() }+ ?: JsonObject(emptyMap())+ return buildJsonObject {+ existing.forEach { (key, value) -> if (key != CONTENT_KEY) put(key, value) }+ put(CONTENT_KEY, json.encodeToJsonElement(capabilities))+ }.toString()+ }+}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.ktindex d4c4c166..ab50be99 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt@@ -107,6 +107,35 @@ class StalkerPortalStateStore @Inject constructor(StalkerTelemetry.capabilityChanged(providerId, "METADATA_CONCURRENCY", "DOWNGRADED")}+ suspend fun recordRateLimitCooldown(+ providerId: Long,+ cooldownUntil: Long,+ now: Long = System.currentTimeMillis()+ ) = update(providerId) { state ->+ val health = decodeEndpointHealth(state.endpointHealthJson)+ .filterValues { expiry -> expiry > now }+ .toMutableMap()+ health[rateLimitKey()] = maxOf(health[rateLimitKey()] ?: 0L, cooldownUntil.coerceAtLeast(now))+ state.copy(+ endpointHealthJson = encodeBoundedHealth(health),+ validatedAt = state.validatedAt.takeIf { it > 0L } ?: now+ )+ }.also {+ StalkerTelemetry.capabilityChanged(providerId, "PROVIDER_RATE_LIMIT", "COOLDOWN")+ }++ suspend fun clearRateLimitCooldown(providerId: Long) {+ val state = dao.get(providerId) ?: return+ val health = decodeEndpointHealth(state.endpointHealthJson).toMutableMap()+ if (health.remove(rateLimitKey()) != null) {+ dao.upsert(state.copy(endpointHealthJson = json.encodeToString(health)))+ StalkerTelemetry.capabilityChanged(providerId, "PROVIDER_RATE_LIMIT", "RESTORED")+ }+ }++ fun rateLimitCooldownUntil(state: StalkerPortalStateEntity): Long =+ decodeEndpointHealth(state.endpointHealthJson)[rateLimitKey()] ?: 0L+suspend fun recordHealthyMetadataProbe(providerId: Long,now: Long = System.currentTimeMillis()@@ -130,8 +159,7 @@ class StalkerPortalStateStore @Inject constructor(.filterValues { expiry -> expiry > now }.toMutableMap()health[endpointKey(endpoint)] = until- val bounded = health.entries.sortedByDescending { it.value }.take(MAX_ENDPOINT_HEALTH_ENTRIES)- .associate { it.key to it.value }+ val bounded = decodeEndpointHealth(encodeBoundedHealth(health))state.copy(endpointHealthJson = json.encodeToString(bounded),endpointFailedUntil = bounded.values.maxOrNull() ?: 0L@@ -159,10 +187,7 @@ class StalkerPortalStateStore @Inject constructor(.toMutableMap()health[recipeKey(recipe)] = untilstate.copy(- endpointHealthJson = json.encodeToString(- health.entries.sortedByDescending { it.value }.take(MAX_ENDPOINT_HEALTH_ENTRIES)- .associate { it.key to it.value }- )+ endpointHealthJson = encodeBoundedHealth(health))}StalkerTelemetry.capabilityChanged(providerId, "AUTH_RECIPE", "COOLDOWN")@@ -216,6 +241,18 @@ class StalkerPortalStateStore @Inject constructor(return json.encodeToString(health)}+ private fun encodeBoundedHealth(health: Map<String, Long>): String {+ val rateKey = rateLimitKey()+ val rateEntry = health[rateKey]?.let { mapOf(rateKey to it) }.orEmpty()+ val ordinary = health.entries+ .asSequence()+ .filter { it.key != rateKey }+ .sortedByDescending { it.value }+ .take(MAX_ENDPOINT_HEALTH_ENTRIES - rateEntry.size)+ .associate { it.key to it.value }+ return json.encodeToString(rateEntry + ordinary)+ }+private fun decodeEndpointHealth(value: String?): Map<String, Long> = runCatching {json.decodeFromString<Map<String, Long>>(value.orEmpty().ifBlank { "{}" })}.getOrDefault(emptyMap())@@ -224,6 +261,8 @@ class StalkerPortalStateStore @Inject constructor(private fun recipeKey(recipe: String): String = healthKey("recipe", recipe.uppercase())+ private fun rateLimitKey(): String = healthKey("provider", "rate_limit")+private fun healthKey(kind: String, value: String): String = MessageDigest.getInstance("SHA-256").digest("$kind:$value".toByteArray(Charsets.UTF_8)).take(12)diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.ktindex 95f5ef09..ee2038a2 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt@@ -4,6 +4,7 @@ import android.util.Logimport com.streamvault.data.util.AdultContentClassifierimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.Category+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Episode@@ -17,6 +18,8 @@ import com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Seasonimport com.streamvault.domain.model.Series+import com.streamvault.domain.model.SeriesCatalogOrigin+import com.streamvault.domain.model.VodCatalogItemimport com.streamvault.domain.model.StalkerAuthModeimport com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerCookieMode@@ -72,6 +75,11 @@ data class StalkerPagedResult<T>(val isComplete: Boolean get() = !isTruncated && page >= totalPages}+data class StalkerVodCatalogItem(+ val rawItemId: String,+ val item: VodCatalogItem+)+class StalkerProvider(override val providerId: Long,private val api: StalkerApiService,@@ -103,6 +111,8 @@ class StalkerProvider(private val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,private val learnedProfileId: String = "",private val requireCatalogValidation: Boolean = true,+ private val catalogLayoutHint: CatalogLayout = CatalogLayout.UNKNOWN,+ private val catalogLayoutDetectionVersionHint: Int = 0,private val identityResolver: StalkerRemoteIdentityResolver? = null,private val portalStateStore: StalkerPortalStateStore? = null,private val discoveryCoordinator: StalkerDiscoveryCoordinator =@@ -116,11 +126,18 @@ internal companion object {private const val RESOLVED_URL_CACHE_SOFT_TTL_MILLIS = 60_000Lprivate const val RESOLVED_URL_CACHE_MIN_TTL_MILLIS = 5_000Lprivate const val RESOLVED_URL_CACHE_MAX_TTL_MILLIS = 300_000L+ private const val AUTH_FAILURE_COOLDOWN_MILLIS = 2_000L+ const val CATALOG_LAYOUT_DETECTION_VERSION = 1private val sharedAuthCache = ConcurrentHashMap<String, CachedAuth>()+ private val sharedAuthFailureCache = ConcurrentHashMap<String, CachedAuthFailure>()+ private val sharedAuthMutexes = ConcurrentHashMap<String, Mutex>()private val resolvedStreamUrlCache = ConcurrentHashMap<String, CachedResolvedUrl>()+ private val missingVodClassificationLogged = ConcurrentHashMap.newKeySet<Long>()fun clearSharedAuthCacheForTests() {sharedAuthCache.clear()+ sharedAuthFailureCache.clear()+ sharedAuthMutexes.clear()}fun clearResolvedStreamUrlCacheForTests() {@@ -131,6 +148,12 @@ internal companion object {private data class CachedAuth(val session: StalkerSession,val profile: StalkerProviderProfile+)++ private data class CachedAuthFailure(+ val expiresAt: Long,+ val message: String,+ val exception: Throwable?)private data class CachedResolvedUrl(@@ -144,9 +167,10 @@ internal companion object {val name: String)- private val authMutex = Mutex()+ private val authMutex = sharedAuthMutexes.computeIfAbsent(authCacheKey()) { Mutex() }private var sessionCache: StalkerSession? = nullprivate var accountProfileCache: StalkerProviderProfile? = null+ private var authFailureCache: CachedAuthFailure? = nullprivate val categoryCache = mutableMapOf<ContentType, List<CategorySeed>>()private val remoteIdentityCache = ConcurrentHashMap<Pair<ContentType, String>, Long>()@@ -154,8 +178,10 @@ internal companion object {authMutex.withLock {sessionCache = nullaccountProfileCache = null+ authFailureCache = nullcategoryCache.clear()sharedAuthCache.remove(authCacheKey())+ sharedAuthFailureCache.remove(authCacheKey())clearResolvedStreamUrlCache()}}@@ -192,6 +218,8 @@ internal companion object {return when (val authResult = ensureAuthenticated()) {is Result.Success -> {val profile = authResult.data.second+ val catalogDetection = detectCatalogLayout(authResult.data.first, profile)+ val catalogLayout = catalogDetection.layoutval learnedDeviceProfile = buildLearnedDeviceProfile(profile)val hostLabel = portalUrl.substringAfter("://").substringBefore('/').ifBlank { "portal" }val providerName = profile.accountName?.takeUnless { it.isBlank() || it == "0" }@@ -239,6 +267,12 @@ internal companion object {maxConnections = profile.maxConnections ?: 1,expirationDate = profile.expirationDate,apiVersion = "Stalker/MAG Portal",+ catalogLayout = catalogLayout,+ catalogLayoutDetectionVersion = if (catalogDetection.conclusive) {+ CATALOG_LAYOUT_DETECTION_VERSION+ } else {+ catalogLayoutDetectionVersionHint+ },status = resolveProviderStatus(profile)))@@ -248,6 +282,63 @@ internal companion object {}}+ private data class CatalogLayoutDetection(+ val layout: CatalogLayout,+ val conclusive: Boolean+ )++ private suspend fun detectCatalogLayout(+ session: StalkerSession,+ profile: StalkerProviderProfile+ ): CatalogLayoutDetection {+ if (+ catalogLayoutDetectionVersionHint >= CATALOG_LAYOUT_DETECTION_VERSION &&+ catalogLayoutHint != CatalogLayout.UNKNOWN+ ) {+ return CatalogLayoutDetection(catalogLayoutHint, conclusive = false)+ }++ val device = buildLearnedDeviceProfile(profile)+ val seriesResult = api.getSeriesCategories(session, device)+ if (seriesResult is Result.Success && seriesResult.data.isNotEmpty()) {+ StalkerTelemetry.catalogLayoutDetected(+ providerId,+ CatalogLayout.SPLIT.name,+ seriesResult.data.size,+ 0,+ "native_series_categories"+ )+ return CatalogLayoutDetection(CatalogLayout.SPLIT, conclusive = true)+ }+ val seriesEndpointIsDefinitivelyEmpty = seriesResult is Result.Success ||+ (seriesResult as? Result.Error)?.isEmptyHttpBodyResponse() == true+ if (!seriesEndpointIsDefinitivelyEmpty) {+ return CatalogLayoutDetection(catalogLayoutHint, conclusive = false)+ }++ return when (val vodResult = api.getVodCategories(session, device)) {+ is Result.Success -> if (vodResult.data.isNotEmpty()) {+ StalkerTelemetry.catalogLayoutDetected(+ providerId,+ CatalogLayout.UNIFIED_VOD.name,+ 0,+ vodResult.data.size,+ "series_empty_vod_present"+ )+ CatalogLayoutDetection(CatalogLayout.UNIFIED_VOD, conclusive = true)+ } else {+ CatalogLayoutDetection(catalogLayoutHint, conclusive = false)+ }+ is Result.Error,+ is Result.Loading -> CatalogLayoutDetection(catalogLayoutHint, conclusive = false)+ }+ }++ private fun Result.Error.isEmptyHttpBodyResponse(): Boolean {+ return generateSequence(exception) { it.cause }+ .any { it is StalkerApiError.EmptyBody }+ }+suspend fun getAccountProfile(): Result<StalkerProviderProfile> {return when (val authResult = ensureAuthenticated()) {is Result.Success -> Result.success(authResult.data.second)@@ -308,6 +399,11 @@ internal companion object {api.getVodCategories(session, profile)}+ suspend fun getUnifiedVodCategories(): Result<List<Category>> =+ mapCategories(ContentType.VOD) { session, profile ->+ api.getVodCategories(session, profile)+ }+override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> {val result = mapItems(ContentType.MOVIE, categoryId) { session, profile, rawCategoryId ->api.getVodStreams(session, profile, rawCategoryId)@@ -331,6 +427,102 @@ internal companion object {toMovie(item, requestedCategoryId = null)} }+ suspend fun getUnifiedVodPage(categoryId: Long, page: Int): Result<StalkerPagedResult<StalkerVodCatalogItem>> =+ getClassifiedVodPage(ContentType.VOD, categoryId, page)++ suspend fun getSplitVodPage(+ categoryId: Long,+ seriesCategoryId: Long,+ page: Int+ ): Result<StalkerPagedResult<StalkerVodCatalogItem>> =+ getClassifiedVodPage(ContentType.MOVIE, categoryId, page, seriesCategoryId)++ suspend fun projectVodCategoryToSeries(categoryId: Long): Long? {+ val rawId = resolveRawCategoryId(ContentType.MOVIE, categoryId) ?: return null+ val name = categoryCache[ContentType.MOVIE]+ ?.firstOrNull { it.id == categoryId || it.rawId == rawId }+ ?.name+ ?: "Category $categoryId"+ val projectedId = identityResolver?.resolveCategories(+ providerId,+ ContentType.SERIES,+ listOf(rawId to name)+ )?.get(rawId) ?: legacyStableId(ContentType.SERIES, rawId)+ categoryCache[ContentType.SERIES] = categoryCache[ContentType.SERIES]+ .orEmpty()+ .filterNot { it.rawId == rawId } + CategorySeed(projectedId, rawId, name)+ remoteIdentityCache[ContentType.SERIES to rawId] = projectedId+ return projectedId+ }++ suspend fun projectSeriesCategoryToVod(categoryId: Long): Long? {+ val rawId = resolveRawCategoryId(ContentType.SERIES, categoryId) ?: return null+ val name = categoryCache[ContentType.SERIES]+ ?.firstOrNull { it.id == categoryId || it.rawId == rawId }+ ?.name+ ?: "Category $categoryId"+ val projectedId = identityResolver?.resolveCategories(+ providerId,+ ContentType.MOVIE,+ listOf(rawId to name)+ )?.get(rawId) ?: legacyStableId(ContentType.MOVIE, rawId)+ categoryCache[ContentType.MOVIE] = categoryCache[ContentType.MOVIE]+ .orEmpty()+ .filterNot { it.rawId == rawId } + CategorySeed(projectedId, rawId, name)+ remoteIdentityCache[ContentType.MOVIE to rawId] = projectedId+ return projectedId+ }++ private suspend fun getClassifiedVodPage(+ categoryType: ContentType,+ categoryId: Long,+ page: Int,+ seriesCategoryId: Long = categoryId+ ): Result<StalkerPagedResult<StalkerVodCatalogItem>> {+ val rawResult = mapPagedItems(categoryType, categoryId) { session, profile, rawCategoryId ->+ api.getVodStreamsPage(session, profile, rawCategoryId, page)+ }+ return when (rawResult) {+ is Result.Success -> {+ val raw = rawResult.data+ val movieRecords = raw.items.filterNot(StalkerItemRecord::isSeries)+ val seriesRecords = raw.items.filter(StalkerItemRecord::isSeries)+ bindRemoteIds(ContentType.MOVIE, movieRecords.map(StalkerItemRecord::id))+ bindRemoteIds(ContentType.SERIES, seriesRecords.map(StalkerItemRecord::id))+ val items = raw.items.mapNotNull { record ->+ if (record.isSeries) {+ toSeries(+ item = record,+ requestedCategoryId = seriesCategoryId,+ categoryType = if (categoryType == ContentType.VOD) ContentType.VOD else ContentType.SERIES,+ origin = SeriesCatalogOrigin.VOD_DERIVED+ )?.let { StalkerVodCatalogItem(record.id, VodCatalogItem.SeriesItem(it)) }+ } else {+ toMovie(+ item = record,+ requestedCategoryId = categoryId,+ categoryType = categoryType+ )?.let { StalkerVodCatalogItem(record.id, VodCatalogItem.MovieItem(it)) }+ }+ }+ Result.success(+ StalkerPagedResult(+ items = items,+ page = raw.page,+ totalPages = raw.totalPages,+ pageSize = raw.pageSize,+ advertisedTotalItems = raw.advertisedTotalItems,+ advertisedTotalPages = raw.advertisedTotalPages,+ isTruncated = raw.isTruncated,+ terminationReason = raw.terminationReason+ )+ )+ }+ is Result.Error -> Result.error(rawResult.message, rawResult.exception)+ is Result.Loading -> Result.error("Unexpected loading state")+ }+ }+override suspend fun getVodInfo(vodId: Long): Result<Movie> {return when (val moviesResult = getVodStreamsPage(categoryId = null, page = 1)) {is Result.Success -> moviesResult.data.items@@ -350,7 +542,7 @@ internal companion object {// Many Ministra portals serve series inside VOD (is_series=1) with the separate// type=series endpoint returning false/empty. Fall back to VOD categories so the// Series tab is populated — adds no overhead for portals that do use type=series.- if (primary is Result.Success && primary.data.size <= 1) {+ if (primary is Result.Success && primary.data.isEmpty()) {return mapCategories(ContentType.SERIES) { session, profile ->api.getVodCategories(session, profile)}@@ -378,11 +570,7 @@ internal companion object {}suspend fun getSeriesListPage(categoryId: Long?, page: Int): Result<StalkerPagedResult<Series>> {- val primary = mapPagedItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->- api.getSeriesPage(session, profile, rawCategoryId, page)- }.let { result -> mapResolvedPage(ContentType.SERIES, result) { item ->- toSeries(item, requestedCategoryId = categoryId)- } }+ val primary = getNativeSeriesListPage(categoryId, page)// Fall back to VOD items with is_series=1 when the type=series endpoint returns// empty (providers that serve series inside VOD). Only triggers when the primary// path produces zero items, so portals using type=series are unaffected.@@ -397,6 +585,13 @@ internal companion object {return primary}+ suspend fun getNativeSeriesListPage(categoryId: Long?, page: Int): Result<StalkerPagedResult<Series>> =+ mapPagedItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->+ api.getSeriesPage(session, profile, rawCategoryId, page)+ }.let { result -> mapResolvedPage(ContentType.SERIES, result) { item ->+ toSeries(item, requestedCategoryId = categoryId)+ } }+suspend fun isWildcardCategory(type: ContentType, categoryId: Long): Boolean {val normalizedType = when (type) {ContentType.SERIES_EPISODE -> ContentType.SERIES@@ -409,9 +604,35 @@ internal companion object {override suspend fun getSeriesInfo(seriesId: Long): Result<Series> =getSeriesInfo(identityResolver?.reverse(providerId, ContentType.SERIES, seriesId) ?: seriesId.toString())- suspend fun getSeriesInfo(providerSeriesId: String): Result<Series> {+ suspend fun getSeriesInfo(+ providerSeriesId: String,+ catalogOrigin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE,+ episodePlaybackTemplateUrl: String? = null,+ learnedDialect: StalkerSeriesDetailDialect = StalkerSeriesDetailDialect.UNKNOWN+ ): Result<Series> {return runWithAuthorizedSession { session, _ ->- when (val detailsResult = api.getSeriesDetails(session, currentDeviceProfile(), providerSeriesId)) {+ val profile = currentDeviceProfile()+ var usedVodDialect = if (+ catalogOrigin == SeriesCatalogOrigin.VOD_DERIVED ||+ learnedDialect == StalkerSeriesDetailDialect.VOD_SEASON_SHELLS+ ) true else false+ val primary = if (usedVodDialect) {+ api.getVodSeriesDetails(session, profile, providerSeriesId)+ } else {+ api.getSeriesDetails(session, profile, providerSeriesId)+ }+ val detailsResult = if (+ primary is Result.Success &&+ primary.data.seasons.isEmpty() &&+ catalogOrigin == SeriesCatalogOrigin.NATIVE &&+ learnedDialect == StalkerSeriesDetailDialect.UNKNOWN+ ) {+ usedVodDialect = true+ api.getVodSeriesDetails(session, profile, providerSeriesId)+ } else {+ primary+ }+ when (detailsResult) {is Result.Success -> {val details = detailsResult.databindRemoteIds(ContentType.SERIES, listOf(details.series.id))@@ -419,7 +640,19 @@ internal companion object {ContentType.SERIES_EPISODE,details.seasons.flatMap { season -> season.episodes.map(StalkerEpisodeRecord::id) })- Result.success(details.toSeries())+ Result.success(+ details.toSeries(+ // VOD_DERIVED is also an internal signal to the repository when+ // a native row needed the bounded semantic VOD fallback. The+ // repository's native-wins merge keeps the persisted origin native.+ catalogOrigin = if (usedVodDialect) {+ SeriesCatalogOrigin.VOD_DERIVED+ } else {+ catalogOrigin+ },+ episodePlaybackTemplateUrl = episodePlaybackTemplateUrl+ )+ )}is Result.Error -> Result.error(detailsResult.message, detailsResult.exception)is Result.Loading -> Result.error("Unexpected loading state")@@ -651,7 +884,31 @@ is Result.Success -> {))}- is Result.Error -> lastError = linkResult+ is Result.Error -> {+ lastError = linkResult+ if (generateSequence(linkResult.exception) { it.cause }+ .any { it is StalkerApiError.ContentUnavailable }+ ) {+ val message = linkResult.message.takeIf(String::isNotBlank)+ ?: "The provider reported that this item is currently unavailable."+ return Result.error(+ message,+ StalkerPlaybackResolutionException(+ message = message,+ cause = linkResult.exception,+ streamKind = kind,+ portalFingerprint = accountProfile.portalFingerprint,+ magPreset = accountProfile.magPreset,+ bootstrapRecipe = accountProfile.bootstrapRecipe,+ endpointPreference = accountProfile.fingerprintEvidence.endpointPreference,+ cookieMode = accountProfile.fingerprintEvidence.cookieMode,+ playbackBackendHint = accountProfile.fingerprintEvidence.playbackBackendHint,+ fallbackRecipeUsed = accountProfile.fallbackRecipeUsed,+ rediscoveryAttempted = accountProfile.rediscoveryAttempted+ )+ )+ }+ }is Result.Loading -> {lastError = Result.error("Unexpected loading state")}@@ -689,6 +946,15 @@ is Result.Success -> {}val message = when {+ generateSequence(lastError?.exception) { it.cause }+ .any { it is StalkerApiError.ContentUnavailable } ->+ "The provider reported that this item is currently unavailable."++ generateSequence(lastError?.exception) { it.cause }+ .any { it is StalkerApiError } ->+ lastError?.message?.takeIf { it.isNotBlank() }+ ?: "The provider could not resolve this item for playback."+accountProfile.strictFingerprintRequired && lastError?.message.isNullOrBlank() ->"Portal requires stricter MAG emulation."@@ -718,6 +984,7 @@ is Result.Success -> {"recipe=${accountProfile.bootstrapRecipe.name} endpoint=${accountProfile.fingerprintEvidence.endpointPreference.name} " +"cookie=${accountProfile.fingerprintEvidence.cookieMode.name} backend=${accountProfile.fingerprintEvidence.playbackBackendHint.name} " +"fallback=${accountProfile.fallbackRecipeUsed} rediscovery=${accountProfile.rediscoveryAttempted} " ++ "errorType=${lastError?.exception?.javaClass?.simpleName ?: "none"} " +"reason=$message")Result.error(@@ -875,7 +1142,7 @@ is Result.Success -> {private suspend fun <T> mapResolvedItems(type: ContentType,- result: Result<List<StalkerItemRecord>>,+ result: Result<List<StalkerItemRecord>>?,mapper: (StalkerItemRecord) -> T?): Result<List<T>> = when (result) {is Result.Success -> {@@ -884,11 +1151,12 @@ is Result.Success -> {}is Result.Error -> Result.error(result.message, result.exception)is Result.Loading -> Result.error("Unexpected loading state")+ null -> Result.error("Portal returned no item response")}private suspend fun <T> mapResolvedPage(type: ContentType,- result: Result<StalkerPagedItems>,+ result: Result<StalkerPagedItems>?,mapper: (StalkerItemRecord) -> T?): Result<StalkerPagedResult<T>> = when (result) {is Result.Success -> {@@ -909,6 +1177,7 @@ is Result.Success -> {}is Result.Error -> Result.error(result.message, result.exception)is Result.Loading -> Result.error("Unexpected loading state")+ null -> Result.error("Portal returned no page response")}private suspend fun bindRemoteIds(type: ContentType, rawIds: Iterable<String>) {@@ -969,6 +1238,13 @@ is Result.Success -> {if (cachedSession != null && cachedProfile != null) {return@withLock Result.success(cachedSession to cachedProfile)}+ (authFailureCache ?: sharedAuthFailureCache[authCacheKey()])?.let { failure ->+ if (failure.expiresAt > System.currentTimeMillis()) {+ return@withLock Result.error(failure.message, failure.exception)+ }+ authFailureCache = null+ sharedAuthFailureCache.remove(authCacheKey(), failure)+ }sharedAuthCache[authCacheKey()]?.let { cachedAuth ->sessionCache = cachedAuth.sessionaccountProfileCache = cachedAuth.profile@@ -976,6 +1252,9 @@ is Result.Success -> {}val persistedState = portalStateStore?.getValidated(providerId)+ val hasPersistedAuthentication = persistedState?.let { state ->+ !state.workingEndpoint.isNullOrBlank() || !state.bootstrapRecipe.isNullOrBlank()+ } == trueval rawPersistedRecipe = persistedState?.bootstrapRecipe?.let { value -> runCatching { StalkerBootstrapRecipe.valueOf(value) }.getOrNull() }val persistedRecipe = rawPersistedRecipe?.takeIf { recipe ->@@ -1034,28 +1313,45 @@ is Result.Success -> {onProgress = onProgress).copy(providerId = providerId)val initialAuthResult = discoveryCoordinator.authenticate(profile)- val finalAuthResult = if (- initialAuthResult is Result.Error &&- persistedEndpointUrl != null- ) {- portalStateStore?.markEndpointUnhealthy(providerId, persistedEndpointUrl)- StalkerTelemetry.strategySelected(providerId, "AUTH_ENDPOINT_AUTO", "CACHED_ENDPOINT_FAILED")- discoveryCoordinator.authenticate(- profile.copy(- portalUrl = portalUrl,- endpointPreference = StalkerEndpointPreference.AUTO,- // Endpoint repair must retain the learned identity. Broad profile rotation- // is reserved for an explicit foreground Repair connection action.- allowCompatibilityDiscovery = false+ val finalAuthResult = when {+ initialAuthResult !is Result.Error -> initialAuthResult+ persistedEndpointUrl != null -> {+ portalStateStore?.markEndpointUnhealthy(providerId, persistedEndpointUrl)+ StalkerTelemetry.strategySelected(providerId, "AUTH_ENDPOINT_AUTO", "CACHED_ENDPOINT_FAILED")+ discoveryCoordinator.authenticate(+ profile.copy(+ portalUrl = portalUrl,+ endpointPreference = StalkerEndpointPreference.AUTO,+ // Endpoint repair retains the learned identity. Broad profile rotation+ // remains reserved for an explicit foreground Repair connection action.+ allowCompatibilityDiscovery = false+ ))- )- } else {- initialAuthResult+ }+ hasPersistedAuthentication -> {+ // If the persisted endpoint/recipe is already cooling down, the old path+ // rebuilt the same generic profile with discovery disabled. That made a+ // recoverable provider fail every catalog request until the cooldown expired.+ // Give one bounded recovery attempt the original portal base and the normal+ // compatibility candidate set, then persist whichever recipe succeeds.+ StalkerTelemetry.strategySelected(providerId, "AUTH_RECIPE_DISCOVERY", "CACHED_AUTH_RECOVERY")+ discoveryCoordinator.authenticate(+ profile.copy(+ portalUrl = portalUrl,+ bootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,+ endpointPreference = StalkerEndpointPreference.AUTO,+ allowCompatibilityDiscovery = true+ )+ )+ }+ else -> initialAuthResult}when (val authResult = finalAuthResult) {is Result.Success -> {sessionCache = authResult.data.firstaccountProfileCache = authResult.data.second+ authFailureCache = null+ sharedAuthFailureCache.remove(authCacheKey())sharedAuthCache[authCacheKey()] = CachedAuth(session = authResult.data.first,profile = authResult.data.second@@ -1071,6 +1367,12 @@ is Result.Success -> {rawPersistedRecipe?.let { failedRecipe ->portalStateStore?.markRecipeUnhealthy(providerId, failedRecipe.name)}+ authFailureCache = CachedAuthFailure(+ expiresAt = System.currentTimeMillis() + AUTH_FAILURE_COOLDOWN_MILLIS,+ message = authResult.message,+ exception = authResult.exception+ )+ sharedAuthFailureCache[authCacheKey()] = authFailureCache!!Result.error(authResult.message, authResult.exception)}is Result.Loading -> Result.error("Unexpected loading state")@@ -1237,7 +1539,8 @@ is Result.Success -> {StalkerTransportMode.USER_ACCEPTED_HTTP ->PlaybackTransportPolicy(mode = PlaybackTransportMode.USER_ACCEPTED_HTTP,- origin = grant.origin+ origin = grant.origin,+ allowCrossOriginHttpRedirects = true)StalkerTransportMode.AUTO_STRICT,StalkerTransportMode.VERIFIED_HTTPS -> null@@ -1601,6 +1904,7 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChallengidentityResolver?.reverse(providerId, normalizedType, targetId)?.let { return it }when (val categoriesResult = when (normalizedType) {ContentType.LIVE -> getLiveCategories()+ ContentType.VOD -> getVodCategories()ContentType.MOVIE -> getVodCategories()ContentType.SERIES -> getSeriesCategories()ContentType.SERIES_EPISODE -> Result.success(emptyList())@@ -1672,14 +1976,22 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChalleng)}- private fun toMovie(item: StalkerItemRecord, requestedCategoryId: Long? = null): Movie? {+ private fun toMovie(+ item: StalkerItemRecord,+ requestedCategoryId: Long? = null,+ categoryType: ContentType = ContentType.MOVIE+ ): Movie? {+ if (item.isSeries) return null+ if (!item.hasSeriesMarker && missingVodClassificationLogged.add(providerId)) {+ StalkerTelemetry.missingVodClassification(providerId)+ }val numericId = stableItemId(ContentType.MOVIE, item.id)val category = requestedCategorySeed(- type = ContentType.MOVIE,+ type = categoryType,categoryId = requestedCategoryId,fallbackName = item.categoryName)- ?: resolveCategory(ContentType.MOVIE, item.categoryId, item.categoryName)+ ?: resolveCategory(categoryType, item.categoryId, item.categoryName)val directStreamUrl = item.streamUrl?.substringAfter(' ', missingDelimiterValue = item.streamUrl)?.trim()@@ -1739,13 +2051,18 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChalleng)}- private fun toSeries(item: StalkerItemRecord, requestedCategoryId: Long? = null): Series? {+ private fun toSeries(+ item: StalkerItemRecord,+ requestedCategoryId: Long? = null,+ categoryType: ContentType = ContentType.SERIES,+ origin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE+ ): Series? {val numericId = stableItemId(ContentType.SERIES, item.id)val category = requestedCategorySeed(- type = ContentType.SERIES,+ type = categoryType,categoryId = requestedCategoryId,fallbackName = item.categoryName- ) ?: resolveCategory(ContentType.SERIES, item.categoryId, item.categoryName)+ ) ?: resolveCategory(categoryType, item.categoryId, item.categoryName)return Series(id = 0L,name = item.name.ifBlank { "Series $numericId" },@@ -1766,31 +2083,61 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChallengisUserProtected = false,lastModified = item.addedAt,seriesId = item.id.toLongOrNull() ?: numericId,- providerSeriesId = item.id+ providerSeriesId = item.id,+ catalogOrigin = origin,+ episodePlaybackTemplateUrl = buildEpisodePlaybackTemplate(item, numericId)+ )+ }++ private fun buildEpisodePlaybackTemplate(item: StalkerItemRecord, numericId: Long): String? {+ val command = item.cmd?.takeIf(String::isNotBlank)+ ?: item.streamUrl?.takeIf(String::isNotBlank)+ ?: return null+ return StalkerUrlFactory.buildInternalStreamUrl(+ providerId = providerId,+ kind = StalkerStreamKind.EPISODE,+ itemId = numericId,+ cmd = command,+ containerExtension = item.containerExtension,+ playbackDescriptor = item.playbackDescriptor+ ?: buildStalkerPlaybackDescriptor(+ primaryCmd = command,+ alternateCommands = item.commandVariants.map { it.sourceKey to it.cmd },+ capabilities = item.portalCapabilities+ ))}- private fun StalkerSeriesDetails.toSeries(): Series {- val mappedSeries = toSeries(series)+ private fun StalkerSeriesDetails.toSeries(+ catalogOrigin: SeriesCatalogOrigin,+ episodePlaybackTemplateUrl: String?+ ): Series {+ val mappedSeries = toSeries(series, origin = catalogOrigin)val baseSeries = if (mappedSeries != null) {- mappedSeries.copy(name = series.name)+ mappedSeries.copy(+ name = series.name,+ episodePlaybackTemplateUrl = mappedSeries.episodePlaybackTemplateUrl+ ?: episodePlaybackTemplateUrl+ )} else {Series(id = 0L,name = series.name,providerId = providerId,seriesId = series.id.toLongOrNull() ?: stableItemId(ContentType.SERIES, series.id),- providerSeriesId = series.id+ providerSeriesId = series.id,+ catalogOrigin = catalogOrigin,+ episodePlaybackTemplateUrl = episodePlaybackTemplateUrl)}- val mappedSeasons = seasons- .sortedBy { it.seasonNumber }- .map { season ->+ val mappedSeasons = seasons.map { season ->val episodes = season.episodes.mapIndexed { index, episode ->episode.toEpisode(fallbackSeriesId = baseSeries.seriesId,fallbackSeasonNumber = season.seasonNumber,- fallbackEpisodeNumber = index + 1+ fallbackEpisodeNumber = index + 1,+ seasonCmd = season.cmd,+ parentTemplateUrl = baseSeries.episodePlaybackTemplateUrl)}Season(@@ -1807,27 +2154,44 @@ private fun playbackTransportChallengeFor(url: String): StalkerTransportChallengprivate fun StalkerEpisodeRecord.toEpisode(fallbackSeriesId: Long,fallbackSeasonNumber: Int,- fallbackEpisodeNumber: Int+ fallbackEpisodeNumber: Int,+ seasonCmd: String?,+ parentTemplateUrl: String?): Episode {val numericId = stableItemId(ContentType.SERIES_EPISODE, id)- val directStreamUrl = cmd- ?.substringAfter(' ', missingDelimiterValue = cmd)+ val effectiveCmd = cmd?.takeIf(String::isNotBlank) ?: seasonCmd?.takeIf(String::isNotBlank)+ val directStreamUrl = effectiveCmd+ ?.substringAfter(' ', missingDelimiterValue = effectiveCmd)?.trim()?.takeIf(UrlSecurityPolicy::isAllowedStreamEntryUrl)- val resolvedStreamUrl = cmd?.takeIf { it.isNotBlank() }?.let { resolvedCmd ->+ val resolvedStreamUrl = effectiveCmd?.let { resolvedCmd ->StalkerUrlFactory.buildInternalStreamUrl(providerId = providerId,kind = StalkerStreamKind.EPISODE,itemId = numericId,cmd = resolvedCmd,containerExtension = containerExtension,- seriesNumber = seasonShellEpisodeSelector(resolvedCmd, episodeNumber),+ seriesNumber = playbackSelector+ ?: seasonShellEpisodeSelector(resolvedCmd, episodeNumber),playbackDescriptor = buildStalkerPlaybackDescriptor(primaryCmd = resolvedCmd,capabilities = StalkerPortalCapabilities()))- } ?: directStreamUrl.orEmpty()+ } ?: parentTemplateUrl+ ?.let(StalkerUrlFactory::parseInternalStreamUrl)+ ?.let { template ->+ StalkerUrlFactory.buildInternalStreamUrl(+ providerId = providerId,+ kind = StalkerStreamKind.EPISODE,+ itemId = numericId,+ cmd = template.cmd,+ containerExtension = containerExtension ?: template.containerExtension,+ seriesNumber = playbackSelector ?: episodeNumber.takeIf { it > 0 },+ playbackDescriptor = template.playbackDescriptor+ )+ }+ ?: directStreamUrl.orEmpty()return Episode(id = numericId,title = title.ifBlank { "Episode $fallbackEpisodeNumber" },diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.ktindex 3db32856..32f55da5 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt@@ -1,6 +1,7 @@package com.streamvault.data.remote.stalkerimport com.streamvault.domain.model.StalkerRequestPriority+import com.streamvault.domain.model.Resultimport java.net.SocketTimeoutExceptionimport java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.atomic.AtomicLong@@ -9,8 +10,11 @@ import javax.inject.Singletonimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.delay+import kotlinx.coroutines.withContextimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLock+import kotlin.coroutines.AbstractCoroutineContextElement+import kotlin.coroutines.CoroutineContextdata class StalkerRequestSnapshot(val active: Int,@@ -19,6 +23,20 @@ data class StalkerRequestSnapshot(val stressCooldownUntil: Long)+class StalkerNetworkPermit internal constructor(+ internal val providerId: Long,+ internal val halfOpenProbe: Boolean,+ internal val priority: StalkerNetworkPriority+)++enum class StalkerNetworkPriority { INTERACTIVE, FOREGROUND, PREFETCH, BACKGROUND }++internal class StalkerRequestPriorityContext(+ val priority: StalkerRequestPriority+) : AbstractCoroutineContextElement(Key) {+ companion object Key : CoroutineContext.Key<StalkerRequestPriorityContext>+}+data class StalkerRequestDescriptor(val contentType: String,val action: String,@@ -65,6 +83,14 @@ class StalkerRequestCoordinator @Inject constructor(var activeBackground = 0var safeMetadataConcurrency = NORMAL_METADATA_CONCURRENCYvar stressCooldownUntil = 0L+ var rateLimitCooldownUntil = 0L+ var rateLimitStrikes = 0+ var halfOpenProbeInFlight = false+ var networkTokens = NETWORK_TOKEN_CAPACITY+ var lastNetworkRefillAt = System.currentTimeMillis()+ var nextBackgroundRequestAt = 0L+ var interactiveWaiters = 0+ var interactiveInFlight = 0var persistedStateLoaded = false}@@ -122,7 +148,13 @@ class StalkerRequestCoordinator @Inject constructor(}if (!acquired) delay(ADMISSION_POLL_MILLIS)}- val result = block()+ val result = withContext(StalkerRequestPriorityContext(priority)) { block() }+ if (result is Result.Error) {+ // Catalog loaders return domain Result values rather than throwing. Keep the+ // coordinator telemetry honest so an authentication/catalog failure cannot look+ // like a successful page with zero items.+ outcome = "error_${result.exception?.telemetryOutcome() ?: "unknown"}"+ }responseMetrics = metricsOf(result)val probeNow = System.currentTimeMillis()val restored = state.mutex.withLock {@@ -143,7 +175,9 @@ class StalkerRequestCoordinator @Inject constructor(throw cancelled} catch (error: Throwable) {outcome = error.telemetryOutcome()- if (error.isProviderStressSignal()) {+ if (error.findRateLimit() != null) {+ recordRateLimit(providerId, error.findRateLimit()?.retryAfterMillis)+ } else if (error.isProviderStressSignal()) {val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLISstate.mutex.withLock {state.safeMetadataConcurrency = 1@@ -190,7 +224,12 @@ class StalkerRequestCoordinator @Inject constructor(}suspend fun recordFailure(providerId: Long, error: Throwable?) {- if (providerId <= 0L || error?.isProviderStressSignal() != true) return+ if (providerId <= 0L) return+ error?.findRateLimit()?.let { rateLimit ->+ recordRateLimit(providerId, rateLimit.retryAfterMillis)+ return+ }+ if (error?.isProviderStressSignal() != true) returnval state = states.computeIfAbsent(providerId) { ProviderState() }hydratePersistedState(providerId, state)val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLIS@@ -201,6 +240,149 @@ class StalkerRequestCoordinator @Inject constructor(portalStateStore?.recordStressCooldown(providerId, cooldownUntil)}+ /**+ * Gates every Stalker HTTP call, including authentication and playback. After a 429,+ * calls fail locally until the provider-wide cooldown expires. Exactly one half-open+ * request is then allowed to verify recovery.+ */+ suspend fun acquireNetworkPermit(+ providerId: Long,+ priority: StalkerNetworkPriority = StalkerNetworkPriority.FOREGROUND+ ): StalkerNetworkPermit {+ if (providerId <= 0L) return StalkerNetworkPermit(providerId, halfOpenProbe = false, priority)+ val state = states.computeIfAbsent(providerId) { ProviderState() }+ hydratePersistedState(providerId, state)+ val interactive = priority == StalkerNetworkPriority.INTERACTIVE+ if (interactive) state.mutex.withLock { state.interactiveWaiters += 1 }+ try {+ while (true) {+ var waitMillis = NETWORK_ADMISSION_POLL_MILLIS+ val permit = state.mutex.withLock {+ val now = System.currentTimeMillis()+ if (state.rateLimitCooldownUntil > now) {+ throw StalkerApiError.RateLimited(+ retryAfterMillis = state.rateLimitCooldownUntil - now+ )+ }+ if (state.rateLimitCooldownUntil > 0L && state.halfOpenProbeInFlight) {+ throw StalkerApiError.RateLimited(retryAfterMillis = HALF_OPEN_POLL_MILLIS)+ }++ state.refillNetworkTokens(now)+ val lowPriority = priority == StalkerNetworkPriority.PREFETCH ||+ priority == StalkerNetworkPriority.BACKGROUND+ val backgroundBlocked = lowPriority &&+ (state.interactiveWaiters > 0 || state.interactiveInFlight > 0)+ val backgroundWait = if (lowPriority) {+ (state.nextBackgroundRequestAt - now).coerceAtLeast(0L)+ } else {+ 0L+ }+ val canBorrow = interactive && state.networkTokens > INTERACTIVE_TOKEN_FLOOR+ val tokenWait = if (state.networkTokens >= 1.0 || canBorrow) {+ 0L+ } else {+ (((1.0 - state.networkTokens) * NETWORK_TOKEN_REFILL_MILLIS).toLong())+ .coerceAtLeast(1L)+ }+ waitMillis = maxOf(+ NETWORK_ADMISSION_POLL_MILLIS.takeIf { backgroundBlocked } ?: 0L,+ backgroundWait,+ tokenWait+ )+ if (waitMillis > 0L) return@withLock null++ state.networkTokens -= 1.0+ if (lowPriority) {+ val interval = if (priority == StalkerNetworkPriority.BACKGROUND) {+ BACKGROUND_REQUEST_INTERVAL_MILLIS+ } else {+ PREFETCH_REQUEST_INTERVAL_MILLIS+ }+ state.nextBackgroundRequestAt = now + interval+ }+ val halfOpen = state.rateLimitCooldownUntil > 0L+ if (halfOpen) state.halfOpenProbeInFlight = true+ if (interactive) state.interactiveInFlight += 1+ StalkerNetworkPermit(providerId, halfOpen, priority)+ }+ if (permit != null) return permit+ delay(waitMillis.coerceAtMost(MAX_NETWORK_ADMISSION_SLEEP_MILLIS))+ }+ } finally {+ if (interactive) {+ state.mutex.withLock {+ state.interactiveWaiters = (state.interactiveWaiters - 1).coerceAtLeast(0)+ }+ }+ }+ }++ suspend fun releaseNetworkPermit(permit: StalkerNetworkPermit) {+ if (permit.providerId <= 0L || permit.priority != StalkerNetworkPriority.INTERACTIVE) return+ val state = states[permit.providerId] ?: return+ state.mutex.withLock {+ state.interactiveInFlight = (state.interactiveInFlight - 1).coerceAtLeast(0)+ }+ }++ suspend fun recordNetworkSuccess(permit: StalkerNetworkPermit) {+ if (permit.providerId <= 0L || !permit.halfOpenProbe) return+ val state = states[permit.providerId] ?: return+ state.mutex.withLock {+ state.rateLimitCooldownUntil = 0L+ state.rateLimitStrikes = 0+ state.halfOpenProbeInFlight = false+ }+ portalStateStore?.clearRateLimitCooldown(permit.providerId)+ }++ suspend fun recordNetworkFailure(permit: StalkerNetworkPermit, error: Throwable) {+ if (permit.providerId <= 0L) return+ val rateLimit = error.findRateLimit()+ if (rateLimit != null) {+ recordRateLimit(permit.providerId, rateLimit.retryAfterMillis)+ return+ }+ if (!permit.halfOpenProbe) return+ val state = states[permit.providerId] ?: return+ val retryAt = System.currentTimeMillis() + HALF_OPEN_FAILURE_COOLDOWN_MILLIS+ state.mutex.withLock {+ state.rateLimitCooldownUntil = retryAt+ state.halfOpenProbeInFlight = false+ }+ portalStateStore?.recordRateLimitCooldown(permit.providerId, retryAt)+ }++ private suspend fun recordRateLimit(providerId: Long, retryAfterMillis: Long?) {+ if (providerId <= 0L) return+ val state = states.computeIfAbsent(providerId) { ProviderState() }+ hydratePersistedState(providerId, state)+ val now = System.currentTimeMillis()+ val cooldownUntil = state.mutex.withLock {+ if (state.rateLimitCooldownUntil > now) {+ val explicitUntil = retryAfterMillis+ ?.takeIf { it > 0L }+ ?.let { now + it.coerceAtMost(MAX_RATE_LIMIT_COOLDOWN_MILLIS) }+ ?: state.rateLimitCooldownUntil+ state.rateLimitCooldownUntil = maxOf(state.rateLimitCooldownUntil, explicitUntil)+ state.halfOpenProbeInFlight = false+ return@withLock state.rateLimitCooldownUntil+ }+ state.rateLimitStrikes = (state.rateLimitStrikes + 1).coerceAtMost(MAX_RATE_LIMIT_STRIKES)+ val exponential = DEFAULT_RATE_LIMIT_COOLDOWN_MILLIS shl (state.rateLimitStrikes - 1)+ val requested = retryAfterMillis?.takeIf { it > 0L } ?: exponential+ val until = now + requested.coerceIn(+ MIN_RATE_LIMIT_COOLDOWN_MILLIS,+ MAX_RATE_LIMIT_COOLDOWN_MILLIS+ )+ state.rateLimitCooldownUntil = maxOf(state.rateLimitCooldownUntil, until)+ state.halfOpenProbeInFlight = false+ state.rateLimitCooldownUntil+ }+ portalStateStore?.recordRateLimitCooldown(providerId, cooldownUntil, now)+ }+private suspend fun hydratePersistedState(providerId: Long, state: ProviderState) {if (state.mutex.withLock { state.persistedStateLoaded }) returnval persisted = portalStateStore?.get(providerId)@@ -210,6 +392,9 @@ class StalkerRequestCoordinator @Inject constructor(?.coerceIn(1, NORMAL_METADATA_CONCURRENCY)?: NORMAL_METADATA_CONCURRENCYstate.stressCooldownUntil = persisted?.stressCooldownUntil ?: 0L+ state.rateLimitCooldownUntil = persisted+ ?.let { portalStateStore?.rateLimitCooldownUntil(it) }+ ?: 0Lstate.persistedStateLoaded = true}}@@ -218,6 +403,16 @@ class StalkerRequestCoordinator @Inject constructor(private fun ProviderState.currentLimit(now: Long): Int =if (safeMetadataConcurrency <= 1 || stressCooldownUntil > now) 1 else NORMAL_METADATA_CONCURRENCY+ private fun ProviderState.refillNetworkTokens(now: Long) {+ val elapsed = (now - lastNetworkRefillAt).coerceAtLeast(0L)+ if (elapsed <= 0L) return+ networkTokens = minOf(+ NETWORK_TOKEN_CAPACITY,+ networkTokens + elapsed.toDouble() / NETWORK_TOKEN_REFILL_MILLIS.toDouble()+ )+ lastNetworkRefillAt = now+ }+private fun Throwable.isProviderStressSignal(): Boolean = when (this) {is StalkerApiError.RateLimited -> trueis StalkerApiError.Server -> httpStatus == 503@@ -228,13 +423,24 @@ class StalkerRequestCoordinator @Inject constructor(else -> cause?.isProviderStressSignal() == true}+ private fun Throwable.findRateLimit(): StalkerApiError.RateLimited? =+ generateSequence(this) { it.cause }+ .filterIsInstance<StalkerApiError.RateLimited>()+ .firstOrNull()+private fun Throwable.telemetryOutcome(): String = when (this) {is StalkerApiError.Authorization -> "authorization"is StalkerApiError.RateLimited -> "rate_limited"is StalkerApiError.Server -> "server"is StalkerApiError.Transport -> "transport"+ is StalkerApiError.TransportConsentRequired -> "transport_consent"is StalkerApiError.Malformed -> "malformed"+ is StalkerApiError.EmptyBody -> "empty_body"is StalkerApiError.ResponseTooLarge -> "oversized"+ is StalkerApiError.ContentUnavailable -> "unavailable"+ is StalkerApiError.UnsupportedProtocol -> "unsupported"+ is StalkerApiError.CatalogTruncated -> "truncated"+ is StalkerApiError.DiscoveryBudgetExceeded -> "budget"is StalkerApiError.BlockedOrConfiguration -> "blocked_configuration"else -> "failed"}@@ -243,5 +449,18 @@ class StalkerRequestCoordinator @Inject constructor(const val NORMAL_METADATA_CONCURRENCY = 2const val ADMISSION_POLL_MILLIS = 20Lconst val STRESS_COOLDOWN_MILLIS = 5L * 60L * 1000L+ const val DEFAULT_RATE_LIMIT_COOLDOWN_MILLIS = 15L * 60L * 1000L+ const val MIN_RATE_LIMIT_COOLDOWN_MILLIS = 60L * 1000L+ const val MAX_RATE_LIMIT_COOLDOWN_MILLIS = 2L * 60L * 60L * 1000L+ const val HALF_OPEN_FAILURE_COOLDOWN_MILLIS = 5L * 60L * 1000L+ const val HALF_OPEN_POLL_MILLIS = 1_000L+ const val MAX_RATE_LIMIT_STRIKES = 4+ const val NETWORK_TOKEN_CAPACITY = 8.0+ const val NETWORK_TOKEN_REFILL_MILLIS = 1_000L+ const val INTERACTIVE_TOKEN_FLOOR = -2.0+ const val BACKGROUND_REQUEST_INTERVAL_MILLIS = 5_000L+ const val PREFETCH_REQUEST_INTERVAL_MILLIS = 500L+ const val NETWORK_ADMISSION_POLL_MILLIS = 100L+ const val MAX_NETWORK_ADMISSION_SLEEP_MILLIS = 1_000L}}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.ktindex e4b27278..bcb2bbf6 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt@@ -7,6 +7,29 @@ import java.security.MessageDigest/** Sanitized structured diagnostics. Values accepted here must never contain portal secrets or URLs. */internal object StalkerTelemetry {+ fun catalogLayoutDetected(+ providerId: Long,+ layout: String,+ seriesCategoryCount: Int,+ vodCategoryCount: Int,+ evidence: String+ ) {+ val event = buildString {+ append("event=catalog_layout_detected")+ append(" provider=").append(providerHash(providerId))+ append(" layout=").append(safeLabel(layout))+ append(" series_categories=").append(seriesCategoryCount.coerceAtLeast(0))+ append(" vod_categories=").append(vodCategoryCount.coerceAtLeast(0))+ append(" evidence=").append(safeLabel(evidence))+ }+ runCatching { Log.i(TAG, event) }+ }++ fun missingVodClassification(providerId: Long) {+ val event = "event=vod_classification_missing provider=${providerHash(providerId)} fallback=MOVIE"+ runCatching { Log.w(TAG, event) }+ }+fun capabilityChanged(providerId: Long, capability: String, outcome: String) {val event = buildString {append("event=capability_state")diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransportGrantFactory.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransportGrantFactory.ktnew file mode 100644index 00000000..5b39fb94--- /dev/null+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransportGrantFactory.kt@@ -0,0 +1,42 @@+package com.streamvault.data.remote.stalker++import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.StalkerTransportGrant+import com.streamvault.domain.model.StalkerTransportMode+import com.streamvault.domain.model.StalkerTransportOrigin+import java.net.URI++/** Rebuilds the persisted user-approved transport policy for lazy Stalker requests. */+internal fun ProviderEntity.stalkerTransportGrantOrNull(): StalkerTransportGrant? {+ if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&+ stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&+ stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPS+ ) {+ return null+ }+ val origin = stalkerTransportOrigin.toStalkerTransportOrigin()+ ?: serverUrl.toStalkerTransportOrigin()+ ?: return null+ val pin = stalkerTlsSpkiSha256.takeIf(String::isNotBlank)+ if (stalkerTransportMode == StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS && pin == null) {+ return null+ }+ return StalkerTransportGrant(+ mode = stalkerTransportMode,+ origin = origin,+ spkiSha256 = pin,+ consentedAt = stalkerTransportConsentAt+ )+}++private fun String.toStalkerTransportOrigin(): StalkerTransportOrigin? {+ val uri = runCatching { URI(trim()) }.getOrNull() ?: return null+ val scheme = uri.scheme?.lowercase()?.takeIf { it == "http" || it == "https" } ?: return null+ val host = uri.host?.lowercase()?.takeIf(String::isNotBlank) ?: return null+ val port = when {+ uri.port != -1 -> uri.port+ scheme == "https" -> 443+ else -> 80+ }+ return StalkerTransportOrigin(scheme, host, port)+}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.ktindex c88a2bf4..47b2c2e9 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@@ -675,6 +675,10 @@ class XtreamProvider(XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories"),requestProfile)+ ContentType.VOD -> api.getVodCategories(+ XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_vod_categories"),+ requestProfile+ )ContentType.SERIES -> api.getSeriesCategories(XtreamUrlFactory.buildPlayerApiUrl(serverUrl, username, password, action = "get_series_categories"),requestProfilediff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamUrlFactory.ktindex 5617362d..542adccb 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@@ -306,6 +306,7 @@ object XtreamUrlFactory {fun kindForContentType(contentType: ContentType): XtreamStreamKind? = when (contentType) {ContentType.LIVE -> XtreamStreamKind.LIVE+ ContentType.VOD -> nullContentType.MOVIE -> XtreamStreamKind.MOVIEContentType.SERIES_EPISODE -> XtreamStreamKind.SERIESContentType.SERIES -> nulldiff --git a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.ktindex 3e77d8a0..74ddd9b4 100644--- a/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/CategoryRepositoryImpl.kt@@ -26,9 +26,10 @@ class CategoryRepositoryImpl @Inject constructor(combine(categoryDao.getByProviderAndType(providerId, ContentType.LIVE.name),categoryDao.getByProviderAndType(providerId, ContentType.MOVIE.name),- categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name)- ) { live, movies, series ->- (live + movies + series)+ categoryDao.getByProviderAndType(providerId, ContentType.SERIES.name),+ categoryDao.getByProviderAndType(providerId, ContentType.VOD.name)+ ) { live, movies, series, vod ->+ (live + movies + series + vod).map { it.toDomain() }.sortedWith(compareBy<Category>({ it.type.ordinal }, { it.name.lowercase() }))}@@ -45,6 +46,10 @@ class CategoryRepositoryImpl @Inject constructor(ContentType.LIVE -> channelDao.updateProtectionStatus(providerId, categoryId, isProtected)ContentType.MOVIE -> movieDao.updateProtectionStatus(providerId, categoryId, isProtected)ContentType.SERIES -> seriesDao.updateProtectionStatus(providerId, categoryId, isProtected)+ ContentType.VOD -> {+ movieDao.updateProtectionStatus(providerId, categoryId, isProtected)+ seriesDao.updateProtectionStatus(providerId, categoryId, isProtected)+ }ContentType.SERIES_EPISODE -> Unit}}diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.ktindex 06a83afd..5663bb6f 100644--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt@@ -28,6 +28,7 @@ import com.streamvault.data.remote.stalker.StalkerRequestDescriptorimport com.streamvault.data.remote.stalker.StalkerResponseMetricsimport com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerTrafficCoordinator+import com.streamvault.data.remote.stalker.stalkerTransportGrantOrNullimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolverimport com.streamvault.data.remote.xtream.XtreamProvider@@ -39,6 +40,7 @@ import com.streamvault.data.util.buildPresentedMoviesimport com.streamvault.data.util.rankSearchResultsimport com.streamvault.data.util.toFtsPrefixQueryimport com.streamvault.domain.model.Category+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.LibraryFilterTypeimport com.streamvault.domain.model.LibraryBrowseQuery@@ -56,6 +58,9 @@ import com.streamvault.domain.model.StalkerRequestPriorityimport com.streamvault.domain.model.VodDuplicateConfidenceimport com.streamvault.domain.model.VodDuplicateHandlingModeimport com.streamvault.domain.model.VodMovieVariant+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.repository.MovieRepositoryimport com.streamvault.domain.repository.PlaybackHistoryRepositoryimport com.streamvault.domain.repository.SyncMetadataRepository@@ -399,20 +404,117 @@ class MovieRepositoryImpl @Inject constructor(override fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>> {return flow {val normalizedSearch = query.searchQuery.trim()+ val requiresCompleteCategory = normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH ||+ query.filterBy.type != LibraryFilterType.ALL ||+ query.sortBy != LibrarySortBy.LIBRARY ||+ preferencesRepository.vodDuplicateHandlingMode.first() != VodDuplicateHandlingMode.SHOW_ALL+ if (requiresCompleteCategory) {+ query.categoryId?.let {+ requestCategoryHydration(query.providerId, it, VodCategoryHydrationRequest.COMPLETE)+ }+ }query.categoryId?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }?.let {- ensureXtreamCategoryLoaded(- query.providerId,- it,- fetchIfMissing = true,- refreshStaleInBackground = true,- requiredCount = browseFetchLimit(query),- loadStalkerCategoryCompletely = true- )+ val provider = providerDao.getById(query.providerId)+ if (provider?.type == ProviderType.XTREAM_CODES) {+ ensureXtreamCategoryLoaded(+ query.providerId,+ it,+ fetchIfMissing = true,+ refreshStaleInBackground = true,+ requiredCount = browseFetchLimit(query)+ )+ }}emit(fetchMovieBrowseResult(query))}.flowOn(Dispatchers.IO)}+ override fun observeCategoryHydration(+ providerId: Long,+ categoryId: Long+ ): Flow<VodCategoryHydration?> = movieCategoryHydrationDao.observe(providerId, categoryId).map { entity ->+ entity?.let {+ VodCategoryHydration(+ lastSuccessfulPage = it.lastSuccessfulPage,+ totalPages = it.totalPages,+ itemCount = it.itemCount,+ isComplete = it.isComplete,+ hasMovies = it.itemCount > 0,+ isLoading = it.lastStatus == "RUNNING",+ error = it.lastError+ )+ }+ }++ override suspend fun requestCategoryHydration(+ providerId: Long,+ categoryId: Long,+ request: VodCategoryHydrationRequest+ ): Result<Unit> {+ val provider = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ if (provider.type != ProviderType.STALKER_PORTAL) return Result.success(Unit)+ val loadMode = preferencesRepository.vodCategoryLoadMode.first()+ val effectiveRequest = if (+ request == VodCategoryHydrationRequest.OPEN && loadMode == VodCategoryLoadMode.COMPLETE_ON_OPEN+ ) VodCategoryHydrationRequest.COMPLETE else request+ val current = movieCategoryHydrationDao.get(providerId, categoryId)+ val requestedPage = if (effectiveRequest == VodCategoryHydrationRequest.NEXT_PAGE) {+ ((current?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ } else null+ if (effectiveRequest == VodCategoryHydrationRequest.OPEN && (current?.lastSuccessfulPage ?: 0) > 0) {+ scheduleMoviePrefetch(providerId, categoryId, loadMode)+ return Result.success(Unit)+ }+ val result = if (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {+ syncManager.hydrateSplitVodCategory(providerId, categoryId, effectiveRequest, ContentType.MOVIE)+ } else {+ val count = movieDao.getCountByCategory(providerId, categoryId).first()+ hydrateStalkerMovieCategoryToCount(+ providerId = providerId,+ categoryId = categoryId,+ provider = provider,+ requiredCount = if (effectiveRequest == VodCategoryHydrationRequest.COMPLETE) Int.MAX_VALUE else count + 1,+ localCount = count,+ hydration = current,+ loadCompletely = effectiveRequest == VodCategoryHydrationRequest.COMPLETE,+ requestedPage = requestedPage+ )+ Result.success(Unit)+ }+ if (result is Result.Success && request == VodCategoryHydrationRequest.OPEN) {+ scheduleMoviePrefetch(providerId, categoryId, loadMode)+ }+ return result+ }++ private fun scheduleMoviePrefetch(providerId: Long, categoryId: Long, loadMode: VodCategoryLoadMode) {+ if (loadMode != VodCategoryLoadMode.PAGED) return+ repositoryScope.launch {+ val provider = providerDao.getById(providerId) ?: return@launch+ val current = movieCategoryHydrationDao.get(providerId, categoryId)+ if (current?.isComplete == true) return@launch+ if (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {+ syncManager.hydrateSplitVodCategory(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.NEXT_PAGE,+ ContentType.MOVIE+ )+ } else {+ val count = movieDao.getCountByCategory(providerId, categoryId).first()+ hydrateStalkerMovieCategoryToCount(+ providerId,+ categoryId,+ provider,+ requiredCount = count + 1,+ localCount = count,+ hydration = current,+ requestedPage = ((current?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ )+ }+ }+ }+override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->if (ftsQuery.isNullOrBlank()) {@@ -1491,6 +1593,18 @@ class MovieRepositoryImpl @Inject constructor() {return}+ if (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {+ syncManager.hydrateSplitVodCategory(+ providerId = providerId,+ movieCategoryId = categoryId,+ request = if (loadStalkerCategoryCompletely) {+ VodCategoryHydrationRequest.COMPLETE+ } else {+ VodCategoryHydrationRequest.OPEN+ }+ )+ return+ }hydrateStalkerMovieCategoryToCount(providerId = providerId,categoryId = categoryId,@@ -1530,6 +1644,14 @@ class MovieRepositoryImpl @Inject constructor(if (!shouldUseStalkerLazyFallback(hydration, localCount, requiredCount)) {return@launch}+ if (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {+ syncManager.hydrateSplitVodCategory(+ providerId = providerId,+ movieCategoryId = categoryId,+ request = VodCategoryHydrationRequest.NEXT_PAGE+ )+ return@launch+ }hydrateStalkerMovieCategoryToCount(providerId = providerId,categoryId = categoryId,@@ -1574,15 +1696,18 @@ class MovieRepositoryImpl @Inject constructor(localCount: Int? = null,hydration: MovieCategoryHydrationEntity? = null,allowWildcard: Boolean = true,- loadCompletely: Boolean = false+ loadCompletely: Boolean = false,+ requestedPage: Int? = null) {val key = "$providerId:$categoryId"val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }lock.withLock {+ val persistedHydration = movieCategoryHydrationDao.get(providerId, categoryId)+ if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) returnval stalkerProvider = createStalkerProvider(providerId, provider)if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) returnvar currentCount = localCount ?: movieDao.getCountByCategory(providerId, categoryId).first()- var currentHydration = hydration ?: movieCategoryHydrationDao.get(providerId, categoryId)+ var currentHydration = persistedHydration ?: hydrationif ((currentHydration?.isComplete == true && currentCount > 0) ||(!loadCompletely && currentCount >= requiredCount)) return@@ -1623,6 +1748,13 @@ class MovieRepositoryImpl @Inject constructor(if (!firstIteration && totalPages > 0 && nextPage > totalPages) breakfirstIteration = falseremotePagesRequested += 1+ movieCategoryHydrationDao.upsert(+ (currentHydration ?: MovieCategoryHydrationEntity(providerId, categoryId)).copy(+ lastAttemptedPage = nextPage,+ lastStatus = "RUNNING",+ lastError = null+ )+ )val requestPriority = if (isPreviewLoad) {StalkerRequestPriority.VISIBLE_PREVIEW} else {@@ -1654,7 +1786,7 @@ class MovieRepositoryImpl @Inject constructor(when (val result = coordinatedResult) {is Success -> {val entities = result.data.items.map { movie -> movie.toEntity() }- val pageComplete = result.data.isComplete || entities.isEmpty()+ val pageComplete = result.data.isCompletetransactionRunner.inTransaction {movieDao.upsertCategoryPage(providerId, entities)val updatedCount = movieDao.getCountByCategory(providerId, categoryId).first()@@ -1675,7 +1807,8 @@ class MovieRepositoryImpl @Inject constructor(retryAfterMs = 0L,failureCount = 0,retryBudgetRemaining = 3,- lastPageFingerprint = null+ lastPageFingerprint = result.data.items.joinToString("|") { it.streamId.toString() }+ .takeIf(String::isNotEmpty))movieCategoryHydrationDao.upsert(currentHydration!!)}@@ -1818,6 +1951,7 @@ class MovieRepositoryImpl @Inject constructor(signature = provider.stalkerSignature,stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,protocolPreference = provider.stalkerProtocolPreference,+ transportGrant = provider.stalkerTransportGrantOrNull(),requestedProfileId = provider.stalkerRequestedProfileId,learnedProfileId = provider.stalkerLearnedProfileId,identityResolver = stalkerRemoteIdentityResolver,diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.ktindex 4c7c5871..d9376337 100644--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt@@ -112,7 +112,8 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(?.toDomain()} else null}- ContentType.LIVE -> null+ ContentType.LIVE,+ ContentType.VOD -> null}}diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex 67d2200d..66a78000 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -745,6 +745,9 @@ class ProviderRepositoryImpl @Inject constructor(transportGrant = effectiveTransportGrant,requestedProfileId = requestedProfileId,requireCatalogValidation = requireLiveReadiness,+ catalogLayoutHint = existingProvider?.catalogLayout+ ?: com.streamvault.domain.model.CatalogLayout.UNKNOWN,+ catalogLayoutDetectionVersionHint = 0,onProgress = onProgress)@@ -1053,6 +1056,7 @@ class ProviderRepositoryImpl @Inject constructor(): Result<Unit> {if (force && providerDao.getById(providerId)?.type == ProviderType.STALKER_PORTAL) {stalkerPortalStateStore.invalidateCapabilities(providerId)+ providerDao.invalidateCatalogLayoutDetection(providerId)}return when (val syncResult = syncManager.sync(@@ -1318,6 +1322,8 @@ class ProviderRepositoryImpl @Inject constructor(requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,learnedProfileId: String = "",requireCatalogValidation: Boolean = true,+ catalogLayoutHint: com.streamvault.domain.model.CatalogLayout = com.streamvault.domain.model.CatalogLayout.UNKNOWN,+ catalogLayoutDetectionVersionHint: Int = 0,onProgress: ((String) -> Unit)? = null): StalkerProvider {return StalkerProvider(@@ -1351,6 +1357,8 @@ class ProviderRepositoryImpl @Inject constructor(requestedProfileId = requestedProfileId,learnedProfileId = learnedProfileId,requireCatalogValidation = requireCatalogValidation,+ catalogLayoutHint = catalogLayoutHint,+ catalogLayoutDetectionVersionHint = catalogLayoutDetectionVersionHint,identityResolver = stalkerRemoteIdentityResolver,portalStateStore = stalkerPortalStateStore,onProgress = onProgress@@ -1391,7 +1399,9 @@ class ProviderRepositoryImpl @Inject constructor(protocolPreference = entity.stalkerProtocolPreference,transportGrant = entity.toStalkerTransportGrant(),requestedProfileId = entity.stalkerRequestedProfileId,- learnedProfileId = entity.stalkerLearnedProfileId+ learnedProfileId = entity.stalkerLearnedProfileId,+ catalogLayoutHint = entity.catalogLayout,+ catalogLayoutDetectionVersionHint = entity.catalogLayoutDetectionVersion)}diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.ktindex 5e6185c6..93bdd7af 100644--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt@@ -8,6 +8,8 @@ import com.streamvault.data.mapper.*import com.streamvault.data.remote.jellyfin.JellyfinProviderimport com.streamvault.data.remote.http.toGenericRequestProfileimport com.streamvault.data.remote.stalker.StalkerApiService+import com.streamvault.data.remote.stalker.StalkerContentCapabilitiesCodec+import com.streamvault.data.remote.stalker.StalkerEpisodeSelectorDialectimport com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerProviderimport com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver@@ -16,6 +18,10 @@ import com.streamvault.data.remote.stalker.StalkerRequestDescriptorimport com.streamvault.data.remote.stalker.StalkerResponseMetricsimport com.streamvault.data.remote.stalker.StalkerPortalStateStoreimport com.streamvault.data.remote.stalker.StalkerTrafficCoordinator+import com.streamvault.data.remote.stalker.StalkerSeriesDetailDialect+import com.streamvault.data.remote.stalker.StalkerUrlFactory+import com.streamvault.data.remote.stalker.StalkerVodPlaybackDialect+import com.streamvault.data.remote.stalker.stalkerTransportGrantOrNullimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProviderimport com.streamvault.data.remote.xtream.XtreamStreamUrlResolver@@ -335,20 +341,98 @@ class SeriesRepositoryImpl @Inject constructor(override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> {return flow {val normalizedSearch = query.searchQuery.trim()+ val requiresCompleteCategory = normalizedSearch.length >= MIN_SEARCH_QUERY_LENGTH ||+ query.filterBy.type != LibraryFilterType.ALL ||+ query.sortBy != LibrarySortBy.LIBRARY ||+ preferencesRepository.vodDuplicateHandlingMode.first() != VodDuplicateHandlingMode.SHOW_ALL+ if (requiresCompleteCategory) {+ query.categoryId?.let {+ requestCategoryHydration(query.providerId, it, VodCategoryHydrationRequest.COMPLETE)+ }+ }query.categoryId?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }?.let {- ensureXtreamCategoryLoaded(- providerId = query.providerId,- categoryId = it,- requiredCount = browseFetchLimit(query),- loadStalkerCategoryCompletely = true- )+ val provider = providerDao.getById(query.providerId)+ if (provider?.type == ProviderType.XTREAM_CODES) {+ ensureXtreamCategoryLoaded(+ providerId = query.providerId,+ categoryId = it,+ requiredCount = browseFetchLimit(query)+ )+ }}emit(fetchSeriesBrowseResult(query))}.flowOn(Dispatchers.IO)}+ override fun observeCategoryHydration(+ providerId: Long,+ categoryId: Long+ ): Flow<VodCategoryHydration?> = seriesCategoryHydrationDao.observe(providerId, categoryId).map { entity ->+ entity?.let {+ VodCategoryHydration(+ lastSuccessfulPage = it.lastSuccessfulPage,+ totalPages = it.totalPages,+ itemCount = it.itemCount,+ isComplete = it.isComplete,+ hasSeries = it.itemCount > 0,+ isLoading = it.lastStatus == "RUNNING",+ error = it.lastError+ )+ }+ }++ override suspend fun requestCategoryHydration(+ providerId: Long,+ categoryId: Long,+ request: VodCategoryHydrationRequest+ ): Result<Unit> {+ val provider = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ if (provider.type != ProviderType.STALKER_PORTAL) return Result.success(Unit)+ val mode = preferencesRepository.vodCategoryLoadMode.first()+ val effectiveRequest = if (+ request == VodCategoryHydrationRequest.OPEN && mode == VodCategoryLoadMode.COMPLETE_ON_OPEN+ ) VodCategoryHydrationRequest.COMPLETE else request+ val current = seriesCategoryHydrationDao.get(providerId, categoryId)+ val requestedPage = if (effectiveRequest == VodCategoryHydrationRequest.NEXT_PAGE) {+ ((current?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ } else null+ val hasDerived = seriesDao.countByCategoryAndOrigin(+ providerId,+ categoryId,+ SeriesCatalogOrigin.VOD_DERIVED+ ) > 0+ if (!hasDerived && !(effectiveRequest == VodCategoryHydrationRequest.OPEN && (current?.lastSuccessfulPage ?: 0) > 0)) {+ val count = seriesDao.getCountByCategory(providerId, categoryId).first()+ hydrateStalkerSeriesCategoryToCount(+ providerId = providerId,+ categoryId = categoryId,+ provider = provider,+ requiredCount = if (effectiveRequest == VodCategoryHydrationRequest.COMPLETE) Int.MAX_VALUE else count + 1,+ localCount = count,+ hydration = current,+ loadCompletely = effectiveRequest == VodCategoryHydrationRequest.COMPLETE,+ requestedPage = requestedPage+ )+ }+ val derivedResult = if (+ hasDerived && provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0+ ) {+ syncManager.hydrateSplitVodSeriesCategory(providerId, categoryId, effectiveRequest)+ } else {+ Result.success(Unit)+ }+ if (derivedResult is Result.Success && request == VodCategoryHydrationRequest.OPEN &&+ mode == VodCategoryLoadMode.PAGED+ ) {+ repositoryScope.launch {+ requestCategoryHydration(providerId, categoryId, VodCategoryHydrationRequest.NEXT_PAGE)+ }+ }+ return derivedResult+ }+override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =query.trim().takeIf { it.length >= MIN_SEARCH_QUERY_LENGTH }?.toFtsPrefixQuery().let { ftsQuery ->if (ftsQuery.isNullOrBlank()) {@@ -404,6 +488,18 @@ class SeriesRepositoryImpl @Inject constructor(if (provider.type == ProviderType.XTREAM_CODES && seriesEntity.hasFreshXtreamDetails()) {return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))}+ if (provider.type == ProviderType.STALKER_PORTAL && seriesEntity.hasFreshStalkerDetails()) {+ val localSeries = buildSeriesWithPersistedEpisodes(seriesEntity)+ // Older catalog-page REPLACE writes could cascade-delete the episodes+ // while leaving the parent marked as freshly hydrated. A VOD-derived+ // series with that impossible state must self-repair on the next open.+ if (+ seriesEntity.catalogOrigin != SeriesCatalogOrigin.VOD_DERIVED ||+ localSeries.seasons.any { season -> season.episodes.isNotEmpty() }+ ) {+ return Result.success(attachSeriesPresentation(localSeries, knownPresentation))+ }+ }val remoteResult = try {when (provider.type) {@@ -419,7 +515,14 @@ class SeriesRepositoryImpl @Inject constructor(return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))}ProviderType.STALKER_PORTAL -> createStalkerProvider(providerId, provider).getSeriesInfo(- seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.seriesId.toString()+ providerSeriesId = seriesEntity.providerSeriesId?.takeIf { it.isNotBlank() }+ ?: seriesEntity.seriesId.toString(),+ catalogOrigin = seriesEntity.catalogOrigin,+ episodePlaybackTemplateUrl = seriesEntity.episodePlaybackTemplateUrl,+ learnedDialect = StalkerContentCapabilitiesCodec.decode(+ provider.stalkerCapabilitiesJson,+ provider.contentCapabilityGeneration()+ ).seriesDetailDialect)ProviderType.M3U -> return Result.success(attachSeriesPresentation(buildSeriesWithPersistedEpisodes(seriesEntity), knownPresentation))ProviderType.JELLYFIN -> {@@ -466,6 +569,8 @@ class SeriesRepositoryImpl @Inject constructor(return when (remoteResult) {is Result.Success -> {val remoteSeries = remoteResult.data+ val hasRemoteEpisodes = remoteSeries.seasons.any { season -> season.episodes.isNotEmpty() }+ val hasPersistedEpisodes = episodeDao.getBySeriesSync(seriesEntity.id).isNotEmpty()val updatedSeries = seriesEntity.copy(name = remoteSeries.name.ifBlank { seriesEntity.name },@@ -484,10 +589,67 @@ class SeriesRepositoryImpl @Inject constructor(episodeRunTime = remoteSeries.episodeRunTime ?: seriesEntity.episodeRunTime,lastModified = if (remoteSeries.lastModified > 0) remoteSeries.lastModified else seriesEntity.lastModified,providerSeriesId = remoteSeries.providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesEntity.providerSeriesId,- cacheState = CACHE_STATE_DETAIL_HYDRATED,- detailHydratedAt = System.currentTimeMillis()+ catalogOrigin = if (seriesEntity.catalogOrigin == SeriesCatalogOrigin.NATIVE) {+ SeriesCatalogOrigin.NATIVE+ } else {+ remoteSeries.catalogOrigin+ },+ episodePlaybackTemplateUrl = remoteSeries.episodePlaybackTemplateUrl+ ?: seriesEntity.episodePlaybackTemplateUrl,+ cacheState = if (hasRemoteEpisodes || hasPersistedEpisodes) {+ CACHE_STATE_DETAIL_HYDRATED+ } else {+ "SUMMARY_ONLY"+ },+ detailHydratedAt = if (hasRemoteEpisodes || hasPersistedEpisodes) {+ System.currentTimeMillis()+ } else {+ 0L+ })seriesDao.update(updatedSeries)+ if (provider.type == ProviderType.STALKER_PORTAL && remoteSeries.seasons.any { it.episodes.isNotEmpty() }) {+ val currentCapabilities = StalkerContentCapabilitiesCodec.decode(+ provider.stalkerCapabilitiesJson,+ provider.contentCapabilityGeneration()+ )+ val learnedCapabilities = currentCapabilities.copy(+ seriesDetailDialect = when (remoteSeries.catalogOrigin) {+ SeriesCatalogOrigin.VOD_DERIVED -> StalkerSeriesDetailDialect.VOD_SEASON_SHELLS+ SeriesCatalogOrigin.NATIVE -> StalkerSeriesDetailDialect.NATIVE_SERIES+ },+ episodeSelectorDialect = if (+ remoteSeries.seasons.flatMap(Season::episodes).any { episode ->+ StalkerUrlFactory.parseInternalStreamUrl(episode.streamUrl)?.seriesNumber != null+ }+ ) {+ StalkerEpisodeSelectorDialect.PARENT_COMMAND_WITH_SERIES_NUMBER+ } else {+ StalkerEpisodeSelectorDialect.EPISODE_COMMAND+ },+ vodPlaybackDialect = updatedSeries.episodePlaybackTemplateUrl+ ?.let(StalkerUrlFactory::parseInternalStreamUrl)+ ?.let { token ->+ if (token.cmd.trim().startsWith("http", ignoreCase = true)) {+ StalkerVodPlaybackDialect.DIRECT+ } else {+ StalkerVodPlaybackDialect.CREATE_LINK+ }+ } ?: currentCapabilities.vodPlaybackDialect,+ validationEvidence = (+ currentCapabilities.validationEvidence ++ "series_details_non_empty:${seriesEntity.catalogOrigin.name.lowercase()}"+ ).distinct().takeLast(8)+ )+ providerDao.update(+ provider.copy(+ stalkerCapabilitiesJson = StalkerContentCapabilitiesCodec.encode(+ provider.stalkerCapabilitiesJson,+ learnedCapabilities+ )+ )+ )+ }if (provider.type == ProviderType.XTREAM_CODES) {xtreamContentIndexDao.markDetailHydrated(providerId = providerId,@@ -1555,15 +1717,18 @@ class SeriesRepositoryImpl @Inject constructor(localCount: Int? = null,hydration: SeriesCategoryHydrationEntity? = null,allowWildcard: Boolean = true,- loadCompletely: Boolean = false+ loadCompletely: Boolean = false,+ requestedPage: Int? = null) {val key = "$providerId:$categoryId"val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }lock.withLock {+ val persistedHydration = seriesCategoryHydrationDao.get(providerId, categoryId)+ if (requestedPage != null && (persistedHydration?.lastSuccessfulPage ?: 0) >= requestedPage) returnval stalkerProvider = createStalkerProvider(providerId, provider)if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) returnvar currentCount = localCount ?: seriesDao.getCountByCategory(providerId, categoryId).first()- var currentHydration = hydration ?: seriesCategoryHydrationDao.get(providerId, categoryId)+ var currentHydration = persistedHydration ?: hydrationif ((currentHydration?.isComplete == true && currentCount > 0) ||(!loadCompletely && currentCount >= requiredCount)) return@@ -1604,6 +1769,13 @@ class SeriesRepositoryImpl @Inject constructor(if (!firstIteration && totalPages > 0 && nextPage > totalPages) breakfirstIteration = falseremotePagesRequested += 1+ seriesCategoryHydrationDao.upsert(+ (currentHydration ?: SeriesCategoryHydrationEntity(providerId, categoryId)).copy(+ lastAttemptedPage = nextPage,+ lastStatus = "RUNNING",+ lastError = null+ )+ )val requestPriority = if (isPreviewLoad) {StalkerRequestPriority.VISIBLE_PREVIEW} else {@@ -1628,14 +1800,20 @@ class SeriesRepositoryImpl @Inject constructor(terminationReason = page?.terminationReason)}- ) { stalkerProvider.getSeriesListPage(categoryId, nextPage) }+ ) {+ if (provider.catalogLayout == CatalogLayout.SPLIT && provider.catalogLayoutDetectionVersion > 0) {+ stalkerProvider.getNativeSeriesListPage(categoryId, nextPage)+ } else {+ stalkerProvider.getSeriesListPage(categoryId, nextPage)+ }+ }if (coordinatedResult is Result.Error) {stalkerRequestCoordinator.recordFailure(providerId, coordinatedResult.exception)}when (val result = coordinatedResult) {is Success -> {val entities = result.data.items.map { series -> series.toEntity() }- val pageComplete = result.data.isComplete || entities.isEmpty()+ val pageComplete = result.data.isCompleteseriesDao.upsertCategoryPage(providerId, entities)currentCount = seriesDao.getCountByCategory(providerId, categoryId).first()currentHydration = SeriesCategoryHydrationEntity(@@ -1654,7 +1832,8 @@ class SeriesRepositoryImpl @Inject constructor(retryAfterMs = 0L,failureCount = 0,retryBudgetRemaining = 3,- lastPageFingerprint = null+ lastPageFingerprint = result.data.items.joinToString("|") { it.seriesId.toString() }+ .takeIf(String::isNotEmpty))seriesCategoryHydrationDao.upsert(currentHydration!!)if (pageComplete) break@@ -1791,10 +1970,29 @@ class SeriesRepositoryImpl @Inject constructor(signature = provider.stalkerSignature,stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,protocolPreference = provider.stalkerProtocolPreference,+ transportGrant = provider.stalkerTransportGrantOrNull(),requestedProfileId = provider.stalkerRequestedProfileId,learnedProfileId = provider.stalkerLearnedProfileId,identityResolver = stalkerRemoteIdentityResolver,portalStateStore = stalkerPortalStateStore)}++ private fun SeriesEntity.hasFreshStalkerDetails(now: Long = System.currentTimeMillis()): Boolean {+ if (cacheState != CACHE_STATE_DETAIL_HYDRATED) return false+ if (detailHydratedAt <= 0L) return false+ if (remoteStaleAt > 0L) return false+ return !ContentCachePolicy.shouldRefresh(detailHydratedAt, DETAIL_REFRESH_TTL_MILLIS, now)+ }++ private fun ProviderEntity.contentCapabilityGeneration(): Int = listOf(+ serverUrl,+ stalkerMacAddress,+ stalkerAuthMode.name,+ stalkerRequestedProfileId,+ stalkerLearnedProfileId,+ stalkerAdvancedOptionsJson,+ catalogLayout.name,+ catalogLayoutDetectionVersion.toString()+ ).joinToString("\u0000").hashCode()}diff --git a/data/src/main/java/com/streamvault/data/repository/VodRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/VodRepositoryImpl.ktnew file mode 100644index 00000000..0dc36b55--- /dev/null+++ b/data/src/main/java/com/streamvault/data/repository/VodRepositoryImpl.kt@@ -0,0 +1,158 @@+package com.streamvault.data.repository++import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.VodCatalogEntryDao+import com.streamvault.data.local.dao.VodCategoryHydrationDao+import com.streamvault.data.mapper.toDomain+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.sync.SyncManager+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.VodCatalogItem+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.model.VodCategoryLoadMode+import com.streamvault.domain.repository.VodRepository+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.emitAll+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.ExperimentalCoroutinesApi++@Singleton+@OptIn(ExperimentalCoroutinesApi::class)+class VodRepositoryImpl @Inject constructor(+ private val movieDao: MovieDao,+ private val seriesDao: SeriesDao,+ private val vodCategoryHydrationDao: VodCategoryHydrationDao,+ private val vodCatalogEntryDao: VodCatalogEntryDao,+ private val categoryDao: CategoryDao,+ private val preferencesRepository: PreferencesRepository,+ private val syncManager: SyncManager+) : VodRepository {+ private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ override fun getCategories(providerId: Long): Flow<List<Category>> = combine(+ categoryDao.getByProviderAndType(providerId, ContentType.VOD.name),+ preferencesRepository.parentalControlLevel,+ preferencesRepository.getHiddenCategoryIds(providerId, ContentType.VOD)+ ) { entities, parentalLevel, hiddenIds ->+ entities.asSequence()+ .filterNot { it.categoryId in hiddenIds }+ .filter { parentalLevel < 3 || (!it.isAdult && !it.isUserProtected) }+ .map { it.toDomain() }+ .toList()+ }++ override fun getCategoryPreview(+ providerId: Long,+ categoryId: Long,+ limit: Int+ ): Flow<List<VodCatalogItem>> = flow {+ ensurePreview(providerId, categoryId)+ emitAll(observeOrderedItems(providerId, categoryId, limit))+ }++ override fun getCategoryItems(+ providerId: Long,+ categoryId: Long+ ): Flow<List<VodCatalogItem>> = observeOrderedItems(providerId, categoryId, Int.MAX_VALUE)++ override fun observeHydration(+ providerId: Long,+ categoryId: Long+ ): Flow<VodCategoryHydration?> = vodCategoryHydrationDao.observe(providerId, categoryId).map { entity ->+ entity?.let {+ VodCategoryHydration(+ lastSuccessfulPage = it.lastSuccessfulPage,+ totalPages = it.totalPages,+ pageSize = it.pageSize,+ itemCount = it.itemCount,+ isComplete = it.isComplete,+ hasMovies = it.hasMovies,+ hasSeries = it.hasSeries,+ isLoading = it.lastStatus == "RUNNING",+ error = it.lastError+ )+ }+ }++ override suspend fun ensurePreview(+ providerId: Long,+ categoryId: Long+ ): Result<Unit> = syncManager.hydrateUnifiedVodCategory(+ providerId = providerId,+ categoryId = categoryId,+ request = VodCategoryHydrationRequest.OPEN+ )++ override suspend fun requestCategoryHydration(+ providerId: Long,+ categoryId: Long,+ request: VodCategoryHydrationRequest+ ): Result<Unit> {+ val loadMode = preferencesRepository.vodCategoryLoadMode.first()+ val effectiveRequest = if (+ request == VodCategoryHydrationRequest.OPEN && loadMode == VodCategoryLoadMode.COMPLETE_ON_OPEN+ ) VodCategoryHydrationRequest.COMPLETE else request+ val result = syncManager.hydrateUnifiedVodCategory(providerId, categoryId, effectiveRequest)+ if (result is Result.Success && request == VodCategoryHydrationRequest.OPEN &&+ loadMode == VodCategoryLoadMode.PAGED+ ) {+ repositoryScope.launch {+ syncManager.hydrateUnifiedVodCategory(+ providerId,+ categoryId,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ }+ }+ return result+ }++ override suspend fun hydrateCompletely(providerId: Long, categoryId: Long): Result<Unit> =+ syncManager.hydrateUnifiedVodCategory(+ providerId = providerId,+ categoryId = categoryId,+ request = VodCategoryHydrationRequest.COMPLETE+ )++ private fun observeOrderedItems(+ providerId: Long,+ categoryId: Long,+ limit: Int+ ): Flow<List<VodCatalogItem>> = vodCatalogEntryDao+ .observeByCategory(providerId, categoryId)+ .flatMapLatest { entries ->+ if (entries.isEmpty()) return@flatMapLatest flowOf(emptyList())+ val movieIds = entries.filter { it.itemType == ContentType.MOVIE }.map { it.targetId }.distinct()+ val seriesIds = entries.filter { it.itemType == ContentType.SERIES }.map { it.targetId }.distinct()+ combine(+ if (movieIds.isEmpty()) flowOf(emptyList()) else movieDao.observeByStreamIds(providerId, movieIds),+ if (seriesIds.isEmpty()) flowOf(emptyList()) else seriesDao.observeBySeriesIds(providerId, seriesIds)+ ) { movies, series ->+ val moviesById = movies.associateBy { it.streamId }+ val seriesById = series.associateBy { it.seriesId }+ entries.asSequence().mapNotNull { entry ->+ when (entry.itemType) {+ ContentType.MOVIE -> moviesById[entry.targetId]?.toDomain()?.let(VodCatalogItem::MovieItem)+ ContentType.SERIES -> seriesById[entry.targetId]?.toDomain()?.let(VodCatalogItem::SeriesItem)+ else -> null+ }+ }.take(limit).toList()+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.ktindex b0855616..114c88fa 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncCatalogStore.kt@@ -351,6 +351,7 @@ internal class SyncCatalogStore(name = category.name,parentId = category.parentId,type = category.type,+ providerOrder = category.providerOrder,isAdult = category.isAdult,syncFingerprint = categoryFingerprint(category))@@ -405,6 +406,7 @@ internal class SyncCatalogStore(parentId = stage.parentId,type = ContentType.LIVE,providerId = providerId,+ providerOrder = stage.providerOrder,isAdult = stage.isAdult)}@@ -450,6 +452,7 @@ internal class SyncCatalogStore(name = stage.name,parentId = stage.parentId,isAdult = stage.isAdult,+ providerOrder = stage.providerOrder,isUserProtected = current.isUserProtected,syncFingerprint = stage.syncFingerprint)@@ -919,6 +922,7 @@ internal class SyncCatalogStore(normalizeText(category.name),category.parentId?.toString().orEmpty(),category.type.name,+ category.providerOrder.toString(),category.isAdult.toString())}diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 3853f0f5..a70a021b 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -15,6 +15,8 @@ import com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.StalkerIndexJobDaoimport com.streamvault.data.local.dao.TmdbIdentityDao+import com.streamvault.data.local.dao.VodCategoryHydrationDao+import com.streamvault.data.local.dao.VodCatalogEntryDaoimport com.streamvault.data.local.dao.XtreamContentIndexDaoimport com.streamvault.data.local.dao.XtreamIndexJobDaoimport com.streamvault.data.local.dao.XtreamLiveOnboardingDao@@ -24,6 +26,8 @@ import com.streamvault.data.local.entity.ChannelGuideSyncEntityimport com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.SeriesEntityimport com.streamvault.data.local.entity.StalkerIndexJobEntity+import com.streamvault.data.local.entity.VodCatalogEntryEntity+import com.streamvault.data.local.entity.VodCategoryHydrationEntityimport com.streamvault.data.local.entity.XtreamContentIndexEntityimport com.streamvault.data.local.entity.XtreamIndexJobEntityimport com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntity@@ -36,6 +40,7 @@ import com.streamvault.data.remote.stalker.StalkerApiServiceimport com.streamvault.data.remote.stalker.StalkerApiErrorimport com.streamvault.data.remote.stalker.StalkerPlaybackModeimport com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.data.remote.stalker.StalkerVodCatalogItemimport com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolverimport com.streamvault.data.remote.stalker.StalkerRequestCoordinatorimport com.streamvault.data.remote.stalker.StalkerRequestDescriptor@@ -61,6 +66,7 @@ import com.streamvault.data.security.CredentialCryptoimport com.streamvault.data.util.AdultContentClassifierimport com.streamvault.data.util.UrlSecurityPolicyimport com.streamvault.domain.model.Channel+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.GuideSourcePolicyimport com.streamvault.domain.model.ContentTypeimport com.streamvault.domain.model.Movie@@ -69,6 +75,7 @@ import com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Series+import com.streamvault.domain.model.VodCatalogItemimport com.streamvault.domain.model.StalkerCatalogModeimport com.streamvault.domain.model.StalkerIndexStateimport com.streamvault.domain.model.StalkerRequestPriority@@ -97,7 +104,6 @@ import kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport kotlinx.coroutines.withContext-import kotlinx.coroutines.withTimeoutOrNullimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.serialization.json.Json@@ -127,13 +133,10 @@ private const val STALKER_CATEGORY_RETRY_COOLDOWN_MILLIS = 5 * 60 * 1000Lprivate const val STALKER_RUNNING_JOB_STALE_MILLIS = 15 * 60 * 1000Lprivate const val STALKER_MIN_HEALTHY_EPG_PROGRAMS = 3// Bulk live is an optimization. Large portals stream tens of MB over a single-// response and can spend 8s+ generating it before the first byte, so a fixed-// wall-clock cap kills healthy transfers on slow links. Instead cancel only-// when the stream stalls (no items for the stall window) and keep a generous-// overall cap so a response that never completes cannot block the-// per-category recovery path forever.+// response and can spend 8s+ generating it before the first byte. Cancel only+// when the stream stalls (no items for the stall window); an absolute wall-clock+// cap would kill healthy transfers that continue making progress.private const val STALKER_BULK_LIVE_STALL_TIMEOUT_MILLIS = 30_000L-private const val STALKER_BULK_LIVE_OVERALL_TIMEOUT_MILLIS = 5 * 60 * 1000Lprivate const val STALKER_BULK_LIVE_STALL_CHECK_INTERVAL_MILLIS = 1_000L// A negative bulk-live verdict expires far sooner than the 7-day validated// portal state: re-probing costs one fast request, while a stale false verdict@@ -163,6 +166,8 @@ private const val XTREAM_ONBOARDING_PHASE_FAILED = "FAILED"* 6h period; 5 000 leaves ample headroom while still catching multi-megabyte payloads.*/private const val STALKER_PER_CHANNEL_RECORD_SANITY_CAP = 5_000+private const val STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN = 48+private const val MILLIS_PER_DAY = 24L * 60L * 60L * 1000L/*** Sentinel exception raised inside the streamed per-channel EPG callback when we detect@@ -209,6 +214,8 @@ class SyncManager @Inject constructor(private val categoryDao: CategoryDao,private val movieCategoryHydrationDao: MovieCategoryHydrationDao,private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao,+ private val vodCategoryHydrationDao: VodCategoryHydrationDao,+ private val vodCatalogEntryDao: VodCatalogEntryDao,private val catalogSyncDao: CatalogSyncDao,private val tmdbIdentityDao: TmdbIdentityDao,private val xtreamContentIndexDao: XtreamContentIndexDao,@@ -267,8 +274,347 @@ class SyncManager @Inject constructor(private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()private val providerStalkerSummaryMutexes = ConcurrentHashMap<Long, Mutex>()private val providerStalkerIndexSectionMutexes = ConcurrentHashMap<String, Mutex>()+ private val providerVodCategoryMutexes = ConcurrentHashMap<String, Mutex>()private val providerEpgMutexes = ConcurrentHashMap<Long, Mutex>()private val syncAdmissionMutex = Mutex()++ suspend fun hydrateUnifiedVodCategory(+ providerId: Long,+ categoryId: Long,+ request: com.streamvault.domain.model.VodCategoryHydrationRequest+ ): Result<Unit> {+ val requestedPage = if (request == com.streamvault.domain.model.VodCategoryHydrationRequest.NEXT_PAGE) {+ ((vodCategoryHydrationDao.get(providerId, categoryId)?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ } else {+ null+ }+ val lock = providerVodCategoryMutexes.computeIfAbsent("$providerId:$categoryId") { Mutex() }+ return lock.withLock {+ val providerEntity = providerDao.getById(providerId)+ ?: return@withLock Result.error("Provider not found")+ if (providerEntity.type != ProviderType.STALKER_PORTAL) {+ return@withLock Result.success(Unit)+ }+ val current = vodCategoryHydrationDao.get(providerId, categoryId)+ if (current?.isComplete == true ||+ (requestedPage != null && current != null && current.lastSuccessfulPage >= requestedPage) ||+ (request == com.streamvault.domain.model.VodCategoryHydrationRequest.OPEN &&+ (current?.lastSuccessfulPage ?: 0) > 0)+ ) {+ return@withLock Result.success(Unit)+ }++ val api = createStalkerSyncProvider(providerEntity.toDomain())+ var hydration = current+ var nextPage = ((current?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ while (true) {+ val attemptAt = System.currentTimeMillis()+ vodCategoryHydrationDao.upsert(+ (hydration ?: VodCategoryHydrationEntity(providerId, categoryId)).copy(+ lastAttemptedPage = nextPage,+ lastStatus = "RUNNING",+ lastError = null+ )+ )+ when (val pageResult = api.getUnifiedVodPage(categoryId, nextPage)) {+ is Result.Success -> {+ val page = pageResult.data+ val category = categoryDao.getByProviderAndTypeSync(providerId, ContentType.VOD.name)+ .firstOrNull { it.categoryId == categoryId }+ val protected = category?.isUserProtected == true+ val movies = page.items.mapNotNull { entry ->+ (entry.item as? VodCatalogItem.MovieItem)?.movie+ ?.copy(isUserProtected = protected)+ ?.toEntity()+ }+ val series = page.items.mapNotNull { entry ->+ (entry.item as? VodCatalogItem.SeriesItem)?.series+ ?.copy(isUserProtected = protected)+ ?.toEntity()+ }+ val entries = page.items.mapIndexed { rawIndex, entry ->+ when (val item = entry.item) {+ is VodCatalogItem.MovieItem -> VodCatalogEntryEntity(+ providerId = providerId,+ categoryId = categoryId,+ rawItemId = entry.rawItemId,+ itemType = ContentType.MOVIE,+ targetId = item.movie.streamId,+ rawPage = page.page,+ rawIndex = rawIndex+ )+ is VodCatalogItem.SeriesItem -> VodCatalogEntryEntity(+ providerId = providerId,+ categoryId = categoryId,+ rawItemId = entry.rawItemId,+ itemType = ContentType.SERIES,+ targetId = item.series.seriesId,+ rawPage = page.page,+ rawIndex = rawIndex+ )+ }+ }+ transactionRunner.inTransaction {+ movieDao.upsertCategoryPage(providerId, movies)+ seriesDao.upsertCategoryPage(providerId, series)+ vodCatalogEntryDao.replacePage(providerId, categoryId, page.page, entries)+ val persistedCount = vodCatalogEntryDao.countByCategory(providerId, categoryId)+ hydration = VodCategoryHydrationEntity(+ providerId = providerId,+ categoryId = categoryId,+ lastLoadedPage = page.page,+ lastAttemptedPage = page.page,+ lastSuccessfulPage = page.page,+ totalPages = page.totalPages,+ pageSize = page.pageSize,+ itemCount = persistedCount,+ isComplete = page.isComplete,+ hasMovies = (hydration?.hasMovies == true) || movies.isNotEmpty(),+ hasSeries = (hydration?.hasSeries == true) || series.isNotEmpty(),+ lastHydratedAt = attemptAt,+ lastStatus = if (page.isTruncated) "TRUNCATED" else "SUCCESS",+ lastError = page.terminationReason,+ retryAfterMs = 0L,+ failureCount = 0,+ retryBudgetRemaining = STALKER_CATEGORY_RETRY_BUDGET,+ lastPageFingerprint = entries.joinToString("|") { it.rawItemId }.takeIf(String::isNotEmpty)+ )+ vodCategoryHydrationDao.upsert(hydration!!)+ }+ if (page.isTruncated) return@withLock Result.error(page.terminationReason ?: "VOD response was truncated")+ if (page.isComplete) return@withLock Result.success(Unit)+ if (request != com.streamvault.domain.model.VodCategoryHydrationRequest.COMPLETE) {+ return@withLock Result.success(Unit)+ }+ nextPage = page.page + 1+ }+ is Result.Error -> {+ val prior = hydration ?: VodCategoryHydrationEntity(providerId, categoryId)+ hydration = prior.copy(+ lastAttemptedPage = nextPage,+ lastStatus = "FAILED_RETRYABLE",+ lastError = pageResult.message,+ failureCount = prior.failureCount + 1,+ retryBudgetRemaining = (prior.retryBudgetRemaining - 1).coerceAtLeast(0)+ )+ vodCategoryHydrationDao.upsert(hydration!!)+ return@withLock Result.error(pageResult.message, pageResult.exception)+ }+ Result.Loading -> return@withLock Result.error("VOD hydration did not complete")+ }+ }+ @Suppress("UNREACHABLE_CODE")+ Result.success(Unit)+ }+ }++ suspend fun hydrateSplitVodCategory(+ providerId: Long,+ movieCategoryId: Long,+ request: com.streamvault.domain.model.VodCategoryHydrationRequest,+ requestedProjection: ContentType = ContentType.MOVIE+ ): Result<Unit> {+ val requestedPage = if (request == com.streamvault.domain.model.VodCategoryHydrationRequest.NEXT_PAGE) {+ ((movieCategoryHydrationDao.get(providerId, movieCategoryId)?.lastSuccessfulPage ?: 0) + 1)+ .coerceAtLeast(1)+ } else {+ null+ }+ val lock = providerVodCategoryMutexes.computeIfAbsent("split:$providerId:$movieCategoryId") { Mutex() }+ return lock.withLock {+ val providerEntity = providerDao.getById(providerId)+ ?: return@withLock Result.error("Provider not found")+ if (providerEntity.type != ProviderType.STALKER_PORTAL || providerEntity.catalogLayout != CatalogLayout.SPLIT) {+ return@withLock Result.success(Unit)+ }+ var hydration = movieCategoryHydrationDao.get(providerId, movieCategoryId)+ var movieCount = movieDao.getCountByCategory(providerId, movieCategoryId).first()+ if (hydration?.isComplete == true ||+ (requestedPage != null && hydration != null && hydration.lastSuccessfulPage >= requestedPage) ||+ (request == com.streamvault.domain.model.VodCategoryHydrationRequest.OPEN &&+ (hydration?.lastSuccessfulPage ?: 0) > 0)+ ) {+ return@withLock Result.success(Unit)+ }+ val api = createStalkerSyncProvider(providerEntity.toDomain())+ val movieCategory = categoryDao.getByProviderAndTypeSync(providerId, ContentType.MOVIE.name)+ .firstOrNull { it.categoryId == movieCategoryId }+ ?: return@withLock Result.error("Movie category not found")+ // Populate the provider's category identity cache before translating it to Series.+ api.getVodCategories()+ val seriesCategoryId = api.projectVodCategoryToSeries(movieCategoryId)+ ?: return@withLock Result.error("Unable to resolve VOD-derived Series category")+ val initialProjectionCount = when (requestedProjection) {+ ContentType.SERIES -> seriesDao.getCountByCategory(providerId, seriesCategoryId).first()+ else -> movieCount+ }+ var nextPage = ((hydration?.lastSuccessfulPage ?: 0) + 1).coerceAtLeast(1)+ while (true) {+ val attemptAt = System.currentTimeMillis()+ movieCategoryHydrationDao.upsert(+ (hydration ?: com.streamvault.data.local.entity.MovieCategoryHydrationEntity(+ providerId,+ movieCategoryId+ )).copy(+ lastAttemptedPage = nextPage,+ lastStatus = "RUNNING",+ lastError = null+ )+ )+ seriesCategoryHydrationDao.get(providerId, seriesCategoryId)?.let { seriesHydration ->+ seriesCategoryHydrationDao.upsert(+ seriesHydration.copy(+ lastAttemptedPage = nextPage,+ lastStatus = "RUNNING",+ lastError = null+ )+ )+ }+ when (val pageResult = api.getSplitVodPage(movieCategoryId, seriesCategoryId, nextPage)) {+ is Result.Success -> {+ val page = pageResult.data+ val movies = page.items.mapNotNull { (it.item as? VodCatalogItem.MovieItem)?.movie?.toEntity() }+ val incomingSeries = page.items.mapNotNull {+ (it.item as? VodCatalogItem.SeriesItem)?.series+ ?.copy(isUserProtected = movieCategory.isUserProtected)+ ?.toEntity()+ }+ val now = attemptAt+ val existingSeriesHydration = seriesCategoryHydrationDao.get(providerId, seriesCategoryId)+ transactionRunner.inTransaction {+ movieDao.upsertCategoryPage(providerId, movies)+ if (incomingSeries.isNotEmpty()) {+ categoryDao.insertAll(+ listOf(+ CategoryEntity(+ providerId = providerId,+ categoryId = seriesCategoryId,+ name = movieCategory.name,+ parentId = movieCategory.parentId,+ type = ContentType.SERIES,+ providerOrder = movieCategory.providerOrder,+ isAdult = movieCategory.isAdult,+ isUserProtected = movieCategory.isUserProtected+ )+ )+ )+ }+ // Check inside the same transaction as the write so a concurrent+ // native-Series refresh can never be replaced by derived VOD data.+ val existingSeries = seriesDao.getBySeriesIds(+ providerId,+ incomingSeries.map { it.seriesId }+ ).associateBy { it.seriesId }+ val derivedSeries = incomingSeries.filter { incoming ->+ existingSeries[incoming.seriesId]?.catalogOrigin !=+ com.streamvault.domain.model.SeriesCatalogOrigin.NATIVE+ }+ seriesDao.upsertCategoryPage(providerId, derivedSeries)+ movieCount = movieDao.getCountByCategory(providerId, movieCategoryId).first()+ val seriesCount = seriesDao.getCountByCategory(providerId, seriesCategoryId).first()+ hydration = com.streamvault.data.local.entity.MovieCategoryHydrationEntity(+ providerId = providerId,+ categoryId = movieCategoryId,+ lastHydratedAt = now,+ itemCount = movieCount,+ lastStatus = if (page.isTruncated) "TRUNCATED" else "SUCCESS",+ lastError = page.terminationReason,+ lastLoadedPage = page.page,+ lastAttemptedPage = page.page,+ lastSuccessfulPage = page.page,+ totalPages = page.totalPages,+ isComplete = page.isComplete,+ pageSize = page.pageSize,+ retryBudgetRemaining = STALKER_CATEGORY_RETRY_BUDGET,+ lastPageFingerprint = page.items.joinToString("|") { it.rawItemId }+ .takeIf(String::isNotEmpty)+ )+ movieCategoryHydrationDao.upsert(hydration!!)+ if (incomingSeries.isNotEmpty() || existingSeriesHydration != null) {+ seriesCategoryHydrationDao.upsert(+ com.streamvault.data.local.entity.SeriesCategoryHydrationEntity(+ providerId = providerId,+ categoryId = seriesCategoryId,+ lastHydratedAt = now,+ itemCount = seriesCount,+ lastStatus = if (page.isTruncated) "TRUNCATED" else "SUCCESS",+ lastError = page.terminationReason,+ lastLoadedPage = page.page,+ lastAttemptedPage = page.page,+ lastSuccessfulPage = page.page,+ totalPages = page.totalPages,+ isComplete = page.isComplete,+ pageSize = page.pageSize,+ retryBudgetRemaining = STALKER_CATEGORY_RETRY_BUDGET,+ lastPageFingerprint = page.items.joinToString("|") { it.rawItemId }+ .takeIf(String::isNotEmpty)+ )+ )+ }+ }+ if (page.isTruncated) return@withLock Result.error(page.terminationReason ?: "VOD response was truncated")+ val projectionCount = when (requestedProjection) {+ ContentType.SERIES -> seriesDao.getCountByCategory(providerId, seriesCategoryId).first()+ else -> movieCount+ }+ if (page.isComplete ||+ (request != com.streamvault.domain.model.VodCategoryHydrationRequest.COMPLETE &&+ projectionCount > initialProjectionCount)+ ) {+ return@withLock Result.success(Unit)+ }+ nextPage = page.page + 1+ }+ is Result.Error -> {+ val prior = hydration ?: com.streamvault.data.local.entity.MovieCategoryHydrationEntity(+ providerId,+ movieCategoryId+ )+ movieCategoryHydrationDao.upsert(+ prior.copy(+ lastAttemptedPage = nextPage,+ lastStatus = "FAILED_RETRYABLE",+ lastError = pageResult.message,+ failureCount = prior.failureCount + 1,+ retryBudgetRemaining = (prior.retryBudgetRemaining - 1).coerceAtLeast(0)+ )+ )+ seriesCategoryHydrationDao.get(providerId, seriesCategoryId)?.let { seriesHydration ->+ seriesCategoryHydrationDao.upsert(+ seriesHydration.copy(+ lastAttemptedPage = nextPage,+ lastStatus = "FAILED_RETRYABLE",+ lastError = pageResult.message,+ failureCount = seriesHydration.failureCount + 1,+ retryBudgetRemaining = (seriesHydration.retryBudgetRemaining - 1).coerceAtLeast(0)+ )+ )+ }+ return@withLock Result.error(pageResult.message, pageResult.exception)+ }+ Result.Loading -> return@withLock Result.error("Split VOD hydration did not complete")+ }+ }+ @Suppress("UNREACHABLE_CODE")+ Result.success(Unit)+ }+ }++ suspend fun hydrateSplitVodSeriesCategory(+ providerId: Long,+ seriesCategoryId: Long,+ request: com.streamvault.domain.model.VodCategoryHydrationRequest+ ): Result<Unit> {+ val providerEntity = providerDao.getById(providerId) ?: return Result.error("Provider not found")+ if (providerEntity.type != ProviderType.STALKER_PORTAL || providerEntity.catalogLayout != CatalogLayout.SPLIT) {+ return Result.success(Unit)+ }+ val api = createStalkerSyncProvider(providerEntity.toDomain())+ api.getSeriesCategories()+ val movieCategoryId = api.projectSeriesCategoryToVod(seriesCategoryId)+ ?: return Result.error("Unable to resolve VOD category for derived Series")+ return hydrateSplitVodCategory(providerId, movieCategoryId, request, ContentType.SERIES)+ }private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {OkHttpXtreamApiService(client = okHttpClient,@@ -1498,6 +1844,7 @@ class SyncManager @Inject constructor(ContentType.MOVIE -> listOf(ContentType.MOVIE)ContentType.SERIES -> listOf(ContentType.SERIES)ContentType.LIVE -> listOf(ContentType.LIVE)+ ContentType.VOD -> emptyList()ContentType.SERIES_EPISODE -> emptyList()null -> listOf(ContentType.LIVE, ContentType.MOVIE, ContentType.SERIES)}@@ -1515,6 +1862,7 @@ class SyncManager @Inject constructor(ContentType.LIVE -> processXtreamLiveIndexBackfillSection(providerId, onProgress)ContentType.MOVIE,ContentType.SERIES -> processXtreamSummaryIndexSection(provider, api, contentType, maxCategoriesPerSection, onProgress)+ ContentType.VOD,ContentType.SERIES_EPISODE -> Unit}}.exceptionOrNull()@@ -1725,9 +2073,15 @@ class SyncManager @Inject constructor()}if (movie.runnable && series.runnable) {- val selected = listOf(movie, series).minWith(- compareBy<StalkerCatalogSectionState>({ it.updatedAt }, { it.contentType.ordinal })- )+ // In split mode, finish/prune the native Series projection before VOD-derived+ // supplementation. That lets a disappeared native row fall back to VOD safely.+ val selected = if (provider.catalogLayout == CatalogLayout.SPLIT) {+ series+ } else {+ listOf(movie, series).minWith(+ compareBy<StalkerCatalogSectionState>({ it.updatedAt }, { it.contentType.ordinal })+ )+ }return StalkerCatalogDecision(selected.contentType,reason = "oldest pending section is ${selected.contentType.name.lowercase()} (${selected.jobState ?: "no job"})"@@ -2096,7 +2450,8 @@ class SyncManager @Inject constructor(api = api,contentType = contentType,categoryId = attempt.category.categoryId,- page = attempt.nextPage+ page = attempt.nextPage,+ splitVod = provider.catalogLayout == CatalogLayout.SPLIT)})@@ -2211,12 +2566,23 @@ class SyncManager @Inject constructor(if (successfulPages.isNotEmpty()) {val indexedAt = System.currentTimeMillis()when (contentType) {- ContentType.MOVIE -> upsertXtreamMovieSummaryBatch(- provider.id,- successfulPages.flatMap { page -> page.items.filterIsInstance<Movie>() },- indexedAt,- restoreWatchProgress = false- )+ ContentType.MOVIE -> {+ val rawItems = successfulPages.flatMap { page -> page.items }+ val classified = rawItems.filterIsInstance<StalkerVodCatalogItem>()+ val movies = if (classified.isEmpty()) {+ rawItems.filterIsInstance<Movie>()+ } else {+ classified.mapNotNull { (it.item as? VodCatalogItem.MovieItem)?.movie }+ }+ upsertXtreamMovieSummaryBatch(provider.id, movies, indexedAt, restoreWatchProgress = false)+ if (classified.isNotEmpty()) {+ upsertVodDerivedSeriesSummaryBatch(+ provider.id,+ classified.mapNotNull { (it.item as? VodCatalogItem.SeriesItem)?.series },+ indexedAt+ )+ }+ }ContentType.SERIES -> upsertXtreamSeriesSummaryBatch(provider.id,successfulPages.flatMap { page -> page.items.filterIsInstance<Series>() },@@ -2865,16 +3231,25 @@ class SyncManager @Inject constructor(api: StalkerProvider,contentType: ContentType,categoryId: Long,- page: Int+ page: Int,+ splitVod: Boolean = false): Result<com.streamvault.data.remote.stalker.StalkerPagedResult<out Any>> {- val initial = fetchStalkerSummaryPage(api, contentType, categoryId, page)+ suspend fun fetch(): Result<com.streamvault.data.remote.stalker.StalkerPagedResult<out Any>> {+ if (splitVod && contentType == ContentType.MOVIE) {+ val seriesCategoryId = api.projectVodCategoryToSeries(categoryId)+ ?: return Result.error("Unable to resolve VOD-derived Series category")+ return api.getSplitVodPage(categoryId, seriesCategoryId, page)+ }+ return fetchStalkerSummaryPage(api, contentType, categoryId, page)+ }+ val initial = fetch()val recovered = if (initial is Result.Error && isLikelyStalkerAuthFailure(initial.message, initial.exception)) {Log.w(TAG,"Retrying Stalker ${contentType.name} page $page after auth refresh for category $categoryId")api.invalidateAuthentication()- fetchStalkerSummaryPage(api, contentType, categoryId, page)+ fetch()} else {initial}@@ -2978,9 +3353,6 @@ class SyncManager @Inject constructor(return "Portal repeated the same page payload for page $requestedPage."}}- if (pagedResult.items.isEmpty() && pagedResult.totalPages > requestedPage) {- return "Portal returned an empty mid-catalog page for page $requestedPage."- }return null}@@ -2989,6 +3361,9 @@ class SyncManager @Inject constructor(contentType: ContentType): String? {if (items.isEmpty()) return "empty"+ val classifiedSeeds = items.filterIsInstance<StalkerVodCatalogItem>()+ .map { entry -> "${entry.rawItemId}:${entry.item.stableId}" }+ if (classifiedSeeds.isNotEmpty()) return sha1Hex(classifiedSeeds.joinToString("|"))val seeds = when (contentType) {ContentType.MOVIE -> items.filterIsInstance<Movie>().map { movie ->"${movie.streamId}:${movie.categoryId}:${movie.addedAt}"@@ -3005,10 +3380,14 @@ class SyncManager @Inject constructor(private fun dedupeStalkerPageItems(items: List<out Any>,contentType: ContentType- ): List<out Any> = when (contentType) {- ContentType.MOVIE -> items.filterIsInstance<Movie>().distinctBy(Movie::streamId)- ContentType.SERIES -> items.filterIsInstance<Series>().distinctBy { it.providerSeriesId ?: it.seriesId.toString() }- else -> items+ ): List<out Any> {+ val classified = items.filterIsInstance<StalkerVodCatalogItem>()+ if (classified.isNotEmpty()) return classified.distinctBy(StalkerVodCatalogItem::rawItemId)+ return when (contentType) {+ ContentType.MOVIE -> items.filterIsInstance<Movie>().distinctBy(Movie::streamId)+ ContentType.SERIES -> items.filterIsInstance<Series>().distinctBy { it.providerSeriesId ?: it.seriesId.toString() }+ else -> items+ }}private fun filterStalkerItemsToCategories(@@ -3557,6 +3936,58 @@ class SyncManager @Inject constructor(return merged.size}+ private suspend fun upsertVodDerivedSeriesSummaryBatch(+ providerId: Long,+ series: List<Series>,+ indexedAt: Long+ ): Int {+ if (series.isEmpty()) return 0+ val incoming = series.map { item ->+ item.toEntity().copy(+ catalogOrigin = com.streamvault.domain.model.SeriesCatalogOrigin.VOD_DERIVED,+ cacheState = "SUMMARY_ONLY",+ detailHydratedAt = 0L,+ remoteStaleAt = 0L+ )+ }+ var accepted = emptyList<SeriesEntity>()+ transactionRunner.inTransaction {+ val existing = seriesDao.getBySeriesIds(providerId, incoming.map { it.seriesId })+ .associateBy { it.seriesId }+ accepted = incoming.mapNotNull { summary ->+ val current = existing[summary.seriesId]+ if (current?.catalogOrigin == com.streamvault.domain.model.SeriesCatalogOrigin.NATIVE) {+ null+ } else {+ mergeSeriesSummary(current, summary)+ }+ }+ val projectedCategories = accepted.mapNotNull { item ->+ val categoryId = item.categoryId ?: return@mapNotNull null+ CategoryEntity(+ providerId = providerId,+ categoryId = categoryId,+ name = item.categoryName ?: "Category $categoryId",+ type = ContentType.SERIES,+ isAdult = item.isAdult,+ isUserProtected = item.isUserProtected+ )+ }.distinctBy { it.categoryId }+ if (projectedCategories.isNotEmpty()) categoryDao.insertAll(projectedCategories)+ if (accepted.isNotEmpty()) {+ seriesDao.insertAll(accepted)+ val persisted = seriesDao.getBySeriesIds(providerId, accepted.map { it.seriesId })+ .associateBy { it.seriesId }+ xtreamContentIndexDao.upsertAll(+ accepted.map { item ->+ item.toXtreamIndexRow(providerId, persisted[item.seriesId]?.id ?: item.id, indexedAt)+ }+ )+ }+ }+ return accepted.size+ }+private suspend fun loadMoviesByStreamIds(providerId: Long,streamIds: List<Long>@@ -3720,6 +4151,7 @@ class SyncManager @Inject constructor(ContentType.MOVIE -> "Movies"ContentType.SERIES -> "Series"ContentType.LIVE -> "Live TV"+ ContentType.VOD -> "VOD"ContentType.SERIES_EPISODE -> "Episodes"}@@ -4004,7 +4436,36 @@ class SyncManager @Inject constructor(emitCatalogSyncProgress(section = Section.LIVE)progress(provider.id, onProgress, "Connecting to portal...")val api = createStalkerSyncProvider(provider)- requireResult(api.authenticate(), "Failed to authenticate with portal")+ val authenticatedProvider = requireResult(api.authenticate(), "Failed to authenticate with portal")+ val effectiveCatalogLayout = authenticatedProvider.catalogLayout+ .takeUnless { it == com.streamvault.domain.model.CatalogLayout.UNKNOWN }+ ?: provider.catalogLayout+ val catalogLayoutChanged =+ authenticatedProvider.catalogLayout != com.streamvault.domain.model.CatalogLayout.UNKNOWN &&+ authenticatedProvider.catalogLayout != provider.catalogLayout+ if (+ catalogLayoutChanged ||+ authenticatedProvider.catalogLayoutDetectionVersion != provider.catalogLayoutDetectionVersion+ ) {+ transactionRunner.inTransaction {+ if (authenticatedProvider.catalogLayout != com.streamvault.domain.model.CatalogLayout.UNKNOWN) {+ providerDao.updateCatalogLayout(+ provider.id,+ authenticatedProvider.catalogLayout,+ authenticatedProvider.catalogLayoutDetectionVersion+ )+ }+ if (catalogLayoutChanged) {+ categoryDao.deleteByProviderAndType(provider.id, ContentType.MOVIE.name)+ categoryDao.deleteByProviderAndType(provider.id, ContentType.SERIES.name)+ categoryDao.deleteByProviderAndType(provider.id, ContentType.VOD.name)+ movieCategoryHydrationDao.deleteByProvider(provider.id)+ seriesCategoryHydrationDao.deleteByProvider(provider.id)+ vodCategoryHydrationDao.deleteByProvider(provider.id)+ vodCatalogEntryDao.deleteByProvider(provider.id)+ }+ }+ }stalkerReadinessTracker.authenticated(provider.id)var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)@@ -4036,9 +4497,13 @@ class SyncManager @Inject constructor(// committed or the previously committed live cache was accepted as fresh.stalkerReadinessTracker.liveReady(provider.id)- if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (force || catalogLayoutChanged || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Preparing Movies...")- val categories = when (val categoriesResult = api.getVodCategories()) {+ val categories = when (val categoriesResult = if (effectiveCatalogLayout == CatalogLayout.UNIFIED_VOD) {+ api.getUnifiedVodCategories()+ } else {+ api.getVodCategories()+ }) {is com.streamvault.domain.model.Result.Success -> categoriesResult.datais com.streamvault.domain.model.Result.Error -> {val missingCatalogDiagnostic = if (@@ -4070,22 +4535,33 @@ class SyncManager @Inject constructor(// front. Using replaceMovieCatalog with an empty sequence would run full stale// deletion and destroy any movies already hydrated via on-demand category loads.// replaceCategories updates/inserts category rows without touching movie rows.+ val storedCategoryType = if (effectiveCatalogLayout == CatalogLayout.UNIFIED_VOD) ContentType.VOD else ContentType.MOVIEsyncCatalogStore.replaceCategories(providerId = provider.id,- type = "MOVIE",- categories = categories.map { category ->+ type = storedCategoryType.name,+ categories = categories.mapIndexed { index, category ->CategoryEntity(providerId = provider.id,categoryId = category.id,name = category.name,parentId = category.parentId,- type = ContentType.MOVIE,+ type = storedCategoryType,+ providerOrder = index,isAdult = category.isAdult)})+ if (effectiveCatalogLayout == CatalogLayout.SPLIT) {+ // Raw VOD pages must be scanned again after a category refresh so derived+ // Series can be restored after native-Series pruning.+ movieCategoryHydrationDao.deleteByProvider(provider.id)+ }+ categoryDao.deleteByProviderAndType(+ provider.id,+ if (storedCategoryType == ContentType.VOD) ContentType.MOVIE.name else ContentType.VOD.name+ )movieCategoryCount = categories.size- if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {+ if (effectiveCatalogLayout != CatalogLayout.UNIFIED_VOD && provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {queueStalkerIndexSection(providerId = provider.id,contentType = ContentType.MOVIE,@@ -4105,7 +4581,10 @@ class SyncManager @Inject constructor(queuedMovieIndex = provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX}- if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {+ if (effectiveCatalogLayout == CatalogLayout.UNIFIED_VOD) {+ categoryDao.deleteByProviderAndType(provider.id, ContentType.SERIES.name)+ seriesCategoryHydrationDao.deleteByProvider(provider.id)+ } else if (force || catalogLayoutChanged || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {progress(provider.id, onProgress, "Preparing Series...")val categories = when (val categoriesResult = api.getSeriesCategories()) {is com.streamvault.domain.model.Result.Success -> categoriesResult.data@@ -4140,13 +4619,14 @@ class SyncManager @Inject constructor(syncCatalogStore.replaceCategories(providerId = provider.id,type = "SERIES",- categories = categories.map { category ->+ categories = categories.mapIndexed { index, category ->CategoryEntity(providerId = provider.id,categoryId = category.id,name = category.name,parentId = category.parentId,type = ContentType.SERIES,+ providerOrder = index,isAdult = category.isAdult)}@@ -4259,7 +4739,7 @@ class SyncManager @Inject constructor(val remoteId = seriesEntity.providerSeriesIdif (!remoteId.isNullOrBlank()) {transactionRunner.inTransaction {- seriesDao.insertAll(listOf(seriesEntity))+ seriesDao.upsertCategoryPage(provider.id, listOf(seriesEntity))}}}@@ -4638,6 +5118,7 @@ class SyncManager @Inject constructor(val replacedChannelKeys = linkedSetOf<String>()val bulkCoveredChannelKeys = linkedSetOf<String>()var importedProgramCount = 0+ var providerRateLimited = falsesuspend fun flushPrograms() {if (insertBuffer.isEmpty()) return@@ -4689,10 +5170,24 @@ class SyncManager @Inject constructor(}}}.onFailure { error ->+ providerRateLimited = error.hasStalkerRateLimit()Log.d(TAG, "Bulk Stalker portal EPG fetch unavailable for provider ${provider.id}", error)}- val fallbackGuideRequests = guideRequests.filterNot { request -> request.channelKey in bulkCoveredChannelKeys }+ val uncoveredGuideRequests = guideRequests.filterNot { request -> request.channelKey in bulkCoveredChannelKeys }+ val perChannelGuideWindowed = uncoveredGuideRequests.size > STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN+ val fallbackGuideRequests = if (providerRateLimited) {+ emptyList()+ } else if (perChannelGuideWindowed) {+ val windowCount = (uncoveredGuideRequests.size + STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN - 1) /+ STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN+ val windowIndex = ((now / MILLIS_PER_DAY) % windowCount).toInt()+ uncoveredGuideRequests+ .drop(windowIndex * STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN)+ .take(STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN)+ } else {+ uncoveredGuideRequests+ }// Some portals ignore `ch_id` and return the entire bulk EPG for every per-channel// request. After the first per-channel call we sample the response shape; if it@@ -4740,7 +5235,14 @@ class SyncManager @Inject constructor(throw streamResult.exception ?: IllegalStateException(streamResult.message)}}.onFailure { error ->- if (error is StalkerBrokenPerChannelEpgException) {+ if (error.hasStalkerRateLimit()) {+ providerRateLimited = true+ ignorePerChannelGuide = true+ Log.w(+ TAG,+ "Stalker provider ${provider.id} entered rate-limit cooldown; cancelling remaining per-channel EPG requests."+ )+ } else if (error is StalkerBrokenPerChannelEpgException) {ignorePerChannelGuide = trueLog.w(TAG,@@ -4782,6 +5284,15 @@ class SyncManager @Inject constructor()val warnings = mutableListOf<String>()+ if (providerRateLimited) {+ warnings.add("Stalker portal rate limit reached; remaining guide requests were cancelled.")+ }+ if (perChannelGuideWindowed) {+ warnings.add(+ "Portal EPG fallback was limited to $STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUN channels this run; " ++ "later background runs rotate through the remaining channels."+ )+ }if (epgCount == 0) {warnings.add("Stalker portal guide import returned zero programs.")}@@ -5278,6 +5789,10 @@ class SyncManager @Inject constructor(}}+ private fun Throwable.hasStalkerRateLimit(): Boolean =+ generateSequence(this as Throwable?) { it.cause }+ .any { it is StalkerApiError.RateLimited }+private fun shouldRememberSequentialPreference(error: Throwable): Boolean {return xtreamAdaptiveSyncPolicy.isProviderStress(error) ||error is XtreamAuthenticationException ||@@ -5660,6 +6175,8 @@ class SyncManager @Inject constructor(transportGrant = provider.toStalkerTransportGrant(),requestedProfileId = provider.stalkerRequestedProfileId,learnedProfileId = provider.stalkerLearnedProfileId,+ catalogLayoutHint = provider.catalogLayout,+ catalogLayoutDetectionVersionHint = provider.catalogLayoutDetectionVersion,identityResolver = stalkerRemoteIdentityResolver,portalStateStore = stalkerPortalStateStore)@@ -5997,11 +6514,10 @@ class SyncManager @Inject constructor(/*** Runs the bulk live stream with a stall watchdog instead of a fixed wall-clock* cap. Large portals stream tens of MB in one response, so the attempt is- * cancelled only when no items arrive for [STALKER_BULK_LIVE_STALL_TIMEOUT_MILLIS];- * [STALKER_BULK_LIVE_OVERALL_TIMEOUT_MILLIS] remains as a final bound so a response- * that never completes cannot block the per-category recovery path forever.- * Returns null when the attempt ended by stall/overall timeout, mirroring the- * previous withTimeoutOrNull contract.+ * cancelled only when no items arrive for [STALKER_BULK_LIVE_STALL_TIMEOUT_MILLIS].+ * There is intentionally no absolute wall-clock timeout: a large catalog may take+ * longer than five minutes while still making healthy progress. Returns null when+ * the attempt ended by a stall, while propagating cancellation of the worker itself.*/private suspend fun <T> withStalkerBulkLiveStallTimeout(block: suspend (markProgress: () -> Unit) -> T@@ -6021,15 +6537,13 @@ class SyncManager @Inject constructor(}}try {- withTimeoutOrNull(STALKER_BULK_LIVE_OVERALL_TIMEOUT_MILLIS) {- try {- streamDeferred.await()- } catch (cancelled: CancellationException) {- // Propagate cancellation of the outer scope (worker stopped or the- // overall timeout fired); only the watchdog's stall-cancel maps to null.- if (!isActive) throw cancelled- null- }+ try {+ streamDeferred.await()+ } catch (cancelled: CancellationException) {+ // Propagate cancellation of the outer scope (worker stopped); only the+ // watchdog's stall-cancel maps to null.+ if (!isActive) throw cancelled+ null}} finally {watchdog.cancel()diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.ktindex 55c5d76d..eaee7d66 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt@@ -1128,6 +1128,52 @@ class OkHttpStalkerApiServiceTest {assertThat(success.data).isEqualTo("http://cdn.example.com/live/stream.ts")}+ @Test+ fun requestJson_retries_empty_body_with_mac_query_and_remembers_portal_requirement() = runTest {+ val requestedMacQueries = mutableListOf<String?>()+ val service = OkHttpStalkerApiService(+ okHttpClient = OkHttpClient.Builder()+ .addInterceptor { chain ->+ val request = chain.request()+ requestedMacQueries += request.url.queryParameter("mac")+ val body = if (request.url.queryParameter("mac").isNullOrBlank()) {+ ""+ } else {+ """{"js":{"cmd":"ffmpeg http://cdn.example.com/live/stream.ts"}}"""+ }+ Response.Builder()+ .request(request)+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(body.toResponseBody("application/json".toMediaType()))+ .build()+ }+ .build(),+ json = Json { ignoreUnknownKeys = true }+ )+ val session = stalkerSession()+ val profile = stalkerProfile()++ val first = service.createLink(+ session = session,+ profile = profile,+ kind = StalkerStreamKind.LIVE,+ cmd = "ffmpeg http://placeholder"+ )+ val second = service.createLink(+ session = session,+ profile = profile,+ kind = StalkerStreamKind.LIVE,+ cmd = "ffmpeg http://placeholder-2"+ )++ assertThat(first).isInstanceOf(Result.Success::class.java)+ assertThat(second).isInstanceOf(Result.Success::class.java)+ assertThat(requestedMacQueries).containsExactly(null, "00:1A:79:12:34:56", "00:1A:79:12:34:56")+ .inOrder()+ }+@Testfun createLink_uses_mag_live_storage_selector_without_changing_vod() = runTest {val requested = mutableListOf<Pair<String, String>>()@@ -1807,6 +1853,36 @@ class OkHttpStalkerApiServiceTest {assertThat(requestCount).isEqualTo(200)}+ @Test+ fun getVodStreamsPage_parses_supported_isSeries_representations_and_tracks_missing_markers() = runTest {+ val service = OkHttpStalkerApiService(+ okHttpClient = fakeClient(+ "get_ordered_list" to """+ {"js":{"total_items":"8","max_page_items":"20","data":[+ {"id":"1","name":"Numeric series","category_id":"42","is_series":1},+ {"id":"2","name":"String series","category_id":"42","is_series":"1"},+ {"id":"3","name":"Boolean series","category_id":"42","is_series":true},+ {"id":"4","name":"Numeric movie","category_id":"42","is_series":0},+ {"id":"5","name":"String movie","category_id":"42","is_series":"0"},+ {"id":"6","name":"Boolean movie","category_id":"42","is_series":false},+ {"id":"7","name":"Missing marker","category_id":"42"},+ {"id":"8","name":"Invalid marker","category_id":"42","is_series":"maybe"}+ ]}}+ """.trimIndent()+ ),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.getVodStreamsPage(stalkerSession(), stalkerProfile(), "42", page = 1)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val items = (result as Result.Success).data.items+ assertThat(items.take(3).map { it.isSeries }).containsExactly(true, true, true).inOrder()+ assertThat(items.drop(3).map { it.isSeries }).containsExactly(false, false, false, false, false).inOrder()+ assertThat(items.take(6).map { it.hasSeriesMarker }).containsExactly(true, true, true, true, true, true).inOrder()+ assertThat(items.drop(6).map { it.hasSeriesMarker }).containsExactly(false, false).inOrder()+ }+@Testfun getLiveCategories_stays_on_selected_endpoint_after_authentication() = runTest {val requestedUrls = mutableListOf<String>()@@ -2456,6 +2532,223 @@ class OkHttpStalkerApiServiceTest {assertThat(success.data.seasons[1].episodes.map { it.episodeNumber }).containsExactly(1, 2, 3).inOrder()}+ @Test+ fun getVodSeriesDetails_uses_shell_id_and_retains_all_episode_pages_in_provider_order() = runTest {+ val requestedSeasonIds = mutableListOf<String>()+ val requestedPages = mutableListOf<Int>()+ val service = OkHttpStalkerApiService(+ okHttpClient = OkHttpClient.Builder()+ .addInterceptor { chain ->+ val request = chain.request()+ assertThat(request.url.queryParameter("type")).isEqualTo("vod")+ val seasonId = request.url.queryParameter("season_id").orEmpty()+ val page = request.url.queryParameter("p")?.toIntOrNull() ?: 1+ val body = if (seasonId == "0") {+ """{"js":{"total_items":1,"max_page_items":14,"data":[{"id":"season-shell-77","video_id":"55000","name":"Season 1","season_number":"1","is_season":"1"}]}}"""+ } else {+ requestedSeasonIds += seasonId+ requestedPages += page+ val start = (page - 1) * 14 + 1+ val end = minOf(page * 14, 39)+ val entries = (start..end).joinToString(",") { episode ->+ """{"id":"episode-$episode","name":"Episode $episode","series_number":"$episode","season_id":"season-shell-77","is_episode":true,"series":[1,2,3,4,5,6,7,8]}"""+ }+ """{"js":{"total_items":39,"max_page_items":14,"data":[$entries]}}"""+ }+ Response.Builder()+ .request(request)+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(body.toResponseBody("application/json".toMediaType()))+ .build()+ }+ .build(),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.getVodSeriesDetails(+ session = stalkerSession(),+ profile = stalkerProfile(),+ seriesId = "55000"+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val details = (result as Result.Success).data+ assertThat(requestedSeasonIds).containsExactly(+ "season-shell-77", "season-shell-77", "season-shell-77"+ ).inOrder()+ assertThat(requestedSeasonIds).doesNotContain("55000")+ assertThat(requestedPages).containsExactly(1, 2, 3).inOrder()+ assertThat(details.seasons.single().episodes).hasSize(39)+ assertThat(details.seasons.single().episodes.map { it.episodeNumber })+ .containsExactlyElementsIn((1..39).toList()).inOrder()+ assertThat(details.paginationEvidence.single().successfulPages).isEqualTo(3)+ }++ @Test+ fun createLink_maps_nothing_to_play_to_content_unavailable() = runTest {+ val service = OkHttpStalkerApiService(+ okHttpClient = fakeClient(+ "create_link" to """{"js":{"error":"nothing_to_play","cmd":""}}"""+ ),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.createLink(+ session = stalkerSession(),+ profile = stalkerProfile(),+ kind = StalkerStreamKind.MOVIE,+ cmd = "ffmpeg http://provider.invalid/movie"+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ val error = result as Result.Error+ assertThat(error.exception).isInstanceOf(StalkerApiError.ContentUnavailable::class.java)+ assertThat(error.message).contains("currently unavailable")+ }++ @Test+ fun createLink_readsPortalErrorBeforeOversizedDiagnosticText() = runTest {+ val oversizedDiagnostic = "storage timeout ".repeat(8_000)+ val service = OkHttpStalkerApiService(+ okHttpClient = fakeClient(+ "create_link" to+ """{"js":{"id":0,"cmd":"","error":"nothing_to_play"},"text":"$oversizedDiagnostic"}"""+ ),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.createLink(+ session = stalkerSession(),+ profile = stalkerProfile(),+ kind = StalkerStreamKind.MOVIE,+ cmd = "/media/331155.mpg"+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ val error = result as Result.Error+ assertThat(error.exception).isInstanceOf(StalkerApiError.ContentUnavailable::class.java)+ assertThat(error.exception).isNotInstanceOf(StalkerApiError.ResponseTooLarge::class.java)+ }++ @Test+ fun createLink_readsPlayableCommandBeforeOversizedDiagnosticText() = runTest {+ val oversizedDiagnostic = "ignored backend diagnostics ".repeat(8_000)+ val service = OkHttpStalkerApiService(+ okHttpClient = fakeClient(+ "create_link" to+ """{"js":{"id":42,"cmd":"ffmpeg https://cdn.example.com/movie.m3u8","error":""},"text":"$oversizedDiagnostic"}"""+ ),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.createLink(+ session = stalkerSession(),+ profile = stalkerProfile(),+ kind = StalkerStreamKind.MOVIE,+ cmd = "/media/42.mpg"+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data).isEqualTo("https://cdn.example.com/movie.m3u8")+ }++ @Test+ fun createLink_maps_scalar_nothing_to_play_to_content_unavailable() = runTest {+ val service = OkHttpStalkerApiService(+ okHttpClient = fakeClient(+ "create_link" to """{"js":"nothing_to_play"}"""+ ),+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.createLink(+ session = stalkerSession(),+ profile = stalkerProfile(),+ kind = StalkerStreamKind.MOVIE,+ cmd = "/media/123.mpg"+ )++ assertThat(result).isInstanceOf(Result.Error::class.java)+ val error = result as Result.Error+ assertThat(error.exception).isInstanceOf(StalkerApiError.ContentUnavailable::class.java)+ assertThat(error.message).contains("currently unavailable")+ }++ @Test+ fun createLink_429_opensProviderCircuitAndSuppressesSecondHttpRequest() = runTest {+ val requestCount = java.util.concurrent.atomic.AtomicInteger()+ val client = OkHttpClient.Builder()+ .addInterceptor { chain ->+ requestCount.incrementAndGet()+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(429)+ .message("Too Many Requests")+ .header("Retry-After", "120")+ .body("{}".toResponseBody("application/json".toMediaType()))+ .build()+ }+ .build()+ val coordinator = StalkerRequestCoordinator()+ val service = OkHttpStalkerApiService(+ okHttpClient = client,+ json = Json { ignoreUnknownKeys = true },+ requestCoordinator = coordinator+ )+ val profile = stalkerProfile().copy(providerId = 91L)++ val first = service.createLink(+ stalkerSession(), profile, StalkerStreamKind.MOVIE, "/media/1.mpg"+ )+ val second = service.createLink(+ stalkerSession(), profile, StalkerStreamKind.MOVIE, "/media/2.mpg"+ )++ assertThat(first).isInstanceOf(Result.Error::class.java)+ assertThat(second).isInstanceOf(Result.Error::class.java)+ assertThat((second as Result.Error).exception)+ .isInstanceOf(StalkerApiError.RateLimited::class.java)+ assertThat(requestCount.get()).isEqualTo(1)+ }++ @Test+ fun createLink_returnsAuthenticatedEndpointWhenPortalStreamsMediaInsteadOfJson() = runTest {+ val media = ByteArray(70 * 1024)+ media[0] = 0x47+ media[188] = 0x47+ val client = OkHttpClient.Builder()+ .addInterceptor { chain ->+ Response.Builder()+ .request(chain.request())+ .protocol(Protocol.HTTP_1_1)+ .code(200)+ .message("OK")+ .body(media.toResponseBody("video/mpeg".toMediaType()))+ .build()+ }+ .build()+ val service = OkHttpStalkerApiService(+ okHttpClient = client,+ json = Json { ignoreUnknownKeys = true }+ )++ val result = service.createLink(+ stalkerSession(),+ stalkerProfile(),+ StalkerStreamKind.EPISODE,+ "/media/123.mpg",+ seriesNumber = 2+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val endpoint = (result as Result.Success).data+ assertThat(endpoint).contains("action=create_link")+ assertThat(endpoint).contains("series=2")+ }+@Testfun authenticate_classifies_device_conflict_envelope_as_terminal_device_conflict() = runTest {val requestedActions = mutableListOf<String>()diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerContentCapabilitiesTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerContentCapabilitiesTest.ktnew file mode 100644index 00000000..390d598e--- /dev/null+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerContentCapabilitiesTest.kt@@ -0,0 +1,40 @@+package com.streamvault.data.remote.stalker++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class StalkerContentCapabilitiesTest {+ @Test+ fun codec_preservesLegacyFlatCapabilities_andRoundTripsVersionedContentCapabilities() {+ val legacy = """{"LIVE":"SUPPORTED","VOD":"SUPPORTED","SERIES":"EMPTY"}"""+ val capabilities = StalkerContentCapabilities(+ configurationGeneration = 42,+ seriesDetailDialect = StalkerSeriesDetailDialect.VOD_SEASON_SHELLS,+ episodeSelectorDialect = StalkerEpisodeSelectorDialect.PARENT_COMMAND_WITH_SERIES_NUMBER,+ vodPlaybackDialect = StalkerVodPlaybackDialect.CREATE_LINK,+ validationEvidence = listOf("series_details_non_empty:vod_derived")+ )++ val encoded = StalkerContentCapabilitiesCodec.encode(legacy, capabilities)+ val decoded = StalkerContentCapabilitiesCodec.decode(encoded, 42)++ assertThat(encoded).contains("\"LIVE\":\"SUPPORTED\"")+ assertThat(decoded).isEqualTo(capabilities)+ }++ @Test+ fun codec_invalidatesLearnedDialects_whenConfigurationGenerationChanges() {+ val encoded = StalkerContentCapabilitiesCodec.encode(+ null,+ StalkerContentCapabilities(+ configurationGeneration = 7,+ seriesDetailDialect = StalkerSeriesDetailDialect.VOD_SEASON_SHELLS+ )+ )++ val decoded = StalkerContentCapabilitiesCodec.decode(encoded, 8)++ assertThat(decoded.configurationGeneration).isEqualTo(8)+ assertThat(decoded.seriesDetailDialect).isEqualTo(StalkerSeriesDetailDialect.UNKNOWN)+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.ktindex a22eed72..6564c31b 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt@@ -8,6 +8,20 @@ import kotlinx.coroutines.test.runTestimport org.junit.Testclass StalkerPortalStateStoreTest {+ @Test+ fun `rate limit cooldown is persisted independently and can be cleared`() = runTest {+ val dao = FakePortalStateDao()+ val store = StalkerPortalStateStore(dao)++ store.recordRateLimitCooldown(9L, cooldownUntil = 61_000L, now = 1_000L)+ val limited = requireNotNull(store.get(9L))+ assertThat(store.rateLimitCooldownUntil(limited)).isEqualTo(61_000L)+ assertThat(limited.stressCooldownUntil).isEqualTo(0L)++ store.clearRateLimitCooldown(9L)+ assertThat(store.rateLimitCooldownUntil(requireNotNull(store.get(9L)))).isEqualTo(0L)+ }+@Testfun `capabilities are validated for seven days and selectively invalidated`() = runTest {val dao = FakePortalStateDao()diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.ktindex 4d18dded..10e0ea6f 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt@@ -2,12 +2,16 @@ package com.streamvault.data.remote.stalkerimport com.google.common.truth.Truth.assertThatimport com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.StalkerPortalStateDaoimport com.streamvault.data.local.dao.StalkerRemoteIdentityDao+import com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.data.local.entity.StalkerRemoteIdentityEntityimport com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.PlaybackTransportModeimport com.streamvault.domain.model.Result+import com.streamvault.domain.model.StalkerBootstrapRecipeimport com.streamvault.domain.model.StalkerTransportGrantimport com.streamvault.domain.model.StalkerTransportModeimport com.streamvault.domain.model.StalkerTransportOrigin@@ -65,6 +69,202 @@ class StalkerProviderTest {assertThat(success.data.status).isEqualTo(ProviderStatus.PARTIAL)}+ @Test+ fun authenticate_detects_unifiedVod_when_nativeSeriesIsEmpty_andVodExists() = runTest {+ val provider = StalkerProvider(+ providerId = 7,+ api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("165", "Movies")),+ seriesCategories = emptyList()+ ),+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.authenticate() as Result.Success++ assertThat(result.data.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ assertThat(result.data.catalogLayoutDetectionVersion)+ .isEqualTo(StalkerProvider.CATALOG_LAYOUT_DETECTION_VERSION)+ }++ @Test+ fun authenticate_detects_split_when_nativeSeriesCategoriesExist() = runTest {+ val provider = StalkerProvider(+ providerId = 8,+ api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("10", "Movies")),+ seriesCategories = listOf(StalkerCategoryRecord("20", "Series"))+ ),+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:57",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.authenticate() as Result.Success++ assertThat(result.data.catalogLayout).isEqualTo(CatalogLayout.SPLIT)+ }++ @Test+ fun authenticate_retainsLastLayout_whenSeriesProbeFails() = runTest {+ val provider = StalkerProvider(+ providerId = 10,+ api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ seriesCategoriesResult = Result.error("timeout")+ ),+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:59",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en",+ catalogLayoutHint = CatalogLayout.UNIFIED_VOD,+ catalogLayoutDetectionVersionHint = 0+ )++ val result = provider.authenticate() as Result.Success++ assertThat(result.data.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ assertThat(result.data.catalogLayoutDetectionVersion).isEqualTo(0)+ }++ @Test+ fun authenticate_treatsHttp200EmptyBody_asNoNativeSeriesSupport() = runTest {+ val provider = StalkerProvider(+ providerId = 13,+ api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("10", "VOD")),+ seriesCategoriesResult = Result.error(+ "Failed to load series categories",+ StalkerApiError.EmptyBody("Portal returned an empty response for get_categories.")+ )+ ),+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:63",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val result = provider.authenticate() as Result.Success++ assertThat(result.data.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ assertThat(result.data.catalogLayoutDetectionVersion)+ .isEqualTo(StalkerProvider.CATALOG_LAYOUT_DETECTION_VERSION)+ }++ @Test+ fun authenticate_keepsProvidersIsolated_whenTheirCatalogCapabilitiesDiffer() = runTest {+ fun provider(id: Long, seriesCategories: List<StalkerCategoryRecord>) = StalkerProvider(+ providerId = id,+ api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("10", "VOD")),+ seriesCategories = seriesCategories+ ),+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:${id.toString().padStart(2, '0')}",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val unified = provider(11, emptyList()).authenticate() as Result.Success+ val split = provider(12, listOf(StalkerCategoryRecord("20", "Series"))).authenticate() as Result.Success++ assertThat(unified.data.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ assertThat(split.data.catalogLayout).isEqualTo(CatalogLayout.SPLIT)+ }++ @Test+ fun vodPaging_classifiesSeriesMarker_withoutLeakingSeriesIntoMovies() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("124", "Anime Movies/Series")),+ vodPageItems = listOf(+ StalkerItemRecord(+ id = "100",+ name = "Movie",+ streamUrl = "https://cdn.example.com/movie.mp4",+ isSeries = false+ ),+ StalkerItemRecord(+ id = "200",+ name = "Series",+ streamUrl = "https://cdn.example.com/series.mp4",+ isSeries = true+ )+ )+ )+ val provider = StalkerProvider(+ providerId = 9,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:58",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )++ val movies = provider.getVodStreamsPage(null, 1) as Result.Success+ val series = provider.getSeriesListPage(null, 1) as Result.Success++ assertThat(movies.data.items.map { it.name }).containsExactly("Movie")+ assertThat(series.data.items.map { it.name }).containsExactly("Series")+ assertThat(movies.data.totalPages).isEqualTo(1)+ assertThat(series.data.totalPages).isEqualTo(1)+ }++ @Test+ fun unifiedVodPage_keepsMixedProviderOrder_andDefaultsMissingMarkerToMovie() = runTest {+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ vodCategories = listOf(StalkerCategoryRecord("124", "Mixed")),+ vodPageItems = listOf(+ StalkerItemRecord(id = "200", name = "Series A", isSeries = true),+ StalkerItemRecord(id = "100", name = "Unmarked Movie", streamUrl = "https://cdn.example.com/movie.mp4"),+ StalkerItemRecord(id = "201", name = "Series B", isSeries = true)+ )+ )+ val provider = StalkerProvider(+ providerId = 14,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:61",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en"+ )+ val category = (provider.getUnifiedVodCategories() as Result.Success).data.single()++ val page = (provider.getUnifiedVodPage(category.id, 1) as Result.Success).data++ assertThat(page.items.map { entry ->+ when (entry.item) {+ is com.streamvault.domain.model.VodCatalogItem.MovieItem -> "movie"+ is com.streamvault.domain.model.VodCatalogItem.SeriesItem -> "series"+ }+ }).containsExactly("series", "movie", "series").inOrder()+ assertThat(page.items.map { it.rawItemId }).containsExactly("200", "100", "201").inOrder()+ assertThat(page.items.map { entry ->+ when (val item = entry.item) {+ is com.streamvault.domain.model.VodCatalogItem.MovieItem -> item.movie.categoryId+ is com.streamvault.domain.model.VodCatalogItem.SeriesItem -> item.series.categoryId+ }+ }).containsExactly(category.id, category.id, category.id)+ assertThat(page.page).isEqualTo(1)+ assertThat(page.isComplete).isTrue()+ }+@Testfun authenticate_maps_expired_date_to_expired() = runTest {val provider = StalkerProvider(@@ -130,6 +330,46 @@ class StalkerProviderTest {assertThat(checkNotNull(api.lastAuthenticateProfile).allowCompatibilityDiscovery).isFalse()}+ @Test+ fun authenticate_recovers_when_saved_endpoint_and_recipe_are_cooling_down() = runTest {+ val dao = FakePortalStateDao()+ val stateStore = StalkerPortalStateStore(dao)+ dao.upsert(+ StalkerPortalStateEntity(+ providerId = 7L,+ workingEndpoint = "https://portal.example.com/server/load.php",+ bootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE.name,+ validatedAt = System.currentTimeMillis()+ )+ )+ stateStore.markEndpointUnhealthy(+ providerId = 7L,+ endpoint = "https://portal.example.com/server/load.php"+ )+ stateStore.markRecipeUnhealthy(+ providerId = 7L,+ recipe = StalkerBootstrapRecipe.GENERIC_SAFE.name+ )+ val api = FakeStalkerApiService(+ profile = StalkerProviderProfile(accountName = "Room"),+ authenticationFailuresBeforeSuccess = 1+ )+ val provider = StalkerProvider(+ providerId = 7,+ api = api,+ portalUrl = "https://portal.example.com/c/",+ macAddress = "00:1A:79:12:34:56",+ deviceProfile = "MAG250",+ timezone = "UTC",+ locale = "en",+ portalStateStore = stateStore+ )++ assertThat(provider.authenticate()).isInstanceOf(Result.Success::class.java)+ assertThat(api.authenticateCalls).isEqualTo(2)+ assertThat(checkNotNull(api.lastAuthenticateProfile).allowCompatibilityDiscovery).isTrue()+ }+@Testfun authenticate_unsavedProvider_allowsExplicitCompatibilityDiscovery() = runTest {val api = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))@@ -878,8 +1118,13 @@ class StalkerProviderTest {private val currentCookieHeader: String = "",private val liveCategoryResults: ArrayDeque<Result<List<StalkerCategoryRecord>>> = ArrayDeque(),private val seriesDetails: StalkerSeriesDetails? = null,+ private val vodCategories: List<StalkerCategoryRecord> = emptyList(),+ private val seriesCategories: List<StalkerCategoryRecord> = emptyList(),+ private val vodCategoriesResult: Result<List<StalkerCategoryRecord>>? = null,+ private val seriesCategoriesResult: Result<List<StalkerCategoryRecord>>? = null,private val vodPageItems: List<StalkerItemRecord> = emptyList(),- private val seriesPageItems: List<StalkerItemRecord> = emptyList()+ private val seriesPageItems: List<StalkerItemRecord> = emptyList(),+ private var authenticationFailuresBeforeSuccess: Int = 0) : StalkerApiService {var createLinkCalls: Int = 0private set@@ -891,6 +1136,10 @@ class StalkerProviderTest {override suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {authenticateCalls += 1lastAuthenticateProfile = profile+ if (authenticationFailuresBeforeSuccess > 0) {+ authenticationFailuresBeforeSuccess -= 1+ return Result.error("authentication failed")+ }return Result.success(StalkerSession(loadUrl = "https://portal.example.com/server/load.php",@@ -923,7 +1172,7 @@ class StalkerProviderTest {override suspend fun getVodCategories(session: StalkerSession,profile: StalkerDeviceProfile- ) = Result.success(emptyList<StalkerCategoryRecord>())+ ) = vodCategoriesResult ?: Result.success(vodCategories)override suspend fun getVodStreams(session: StalkerSession,@@ -941,7 +1190,7 @@ class StalkerProviderTest {override suspend fun getSeriesCategories(session: StalkerSession,profile: StalkerDeviceProfile- ) = Result.success(emptyList<StalkerCategoryRecord>())+ ) = seriesCategoriesResult ?: Result.success(seriesCategories)override suspend fun getSeries(session: StalkerSession,@@ -1017,6 +1266,18 @@ class StalkerProviderTest {override fun currentCookieHeader(session: StalkerSession): String = currentCookieHeader}+ private class FakePortalStateDao : StalkerPortalStateDao {+ private val rows = mutableMapOf<Long, StalkerPortalStateEntity>()++ override suspend fun get(providerId: Long): StalkerPortalStateEntity? = rows[providerId]++ override suspend fun upsert(entity: StalkerPortalStateEntity) {+ rows[entity.providerId] = entity+ }++ override suspend fun invalidate(providerId: Long): Int = if (rows.remove(providerId) != null) 1 else 0+ }+@Testfun resolvePlaybackInfo_applies_accepted_http_only_to_the_granted_origin() = runTest {val grant = StalkerTransportGrant(diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.ktindex 229148e4..660f2f48 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt@@ -8,9 +8,48 @@ import kotlinx.coroutines.asyncimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.runCurrentimport kotlinx.coroutines.test.runTest+import org.junit.Assert.assertThrowsimport org.junit.Testclass StalkerRequestCoordinatorTest {+ @Test+ fun backgroundNetworkRequestWaitsWhileInteractivePlaybackIsActive() = runTest {+ val coordinator = StalkerRequestCoordinator()+ val playback = coordinator.acquireNetworkPermit(+ 21L,+ StalkerNetworkPriority.INTERACTIVE+ )+ val background = async {+ coordinator.acquireNetworkPermit(21L, StalkerNetworkPriority.BACKGROUND)+ }++ runCurrent()+ assertThat(background.isCompleted).isFalse()++ coordinator.releaseNetworkPermit(playback)+ advanceUntilIdle()+ assertThat(background.await().priority).isEqualTo(StalkerNetworkPriority.BACKGROUND)+ }++ @Test+ fun rateLimitBlocksAllProviderNetworkPermitsWithoutAnotherRequest() = runTest {+ val coordinator = StalkerRequestCoordinator()++ coordinator.recordFailure(+ providerId = 11L,+ error = StalkerApiError.RateLimited(retryAfterMillis = 60_000L)+ )++ val error = assertThrows(StalkerApiError.RateLimited::class.java) {+ kotlinx.coroutines.runBlocking { coordinator.acquireNetworkPermit(11L) }+ }+ assertThat(error.retryAfterMillis).isAtLeast(59_000L)++ // A different provider remains isolated and healthy.+ val otherProviderPermit = coordinator.acquireNetworkPermit(12L)+ assertThat(otherProviderPermit.providerId).isEqualTo(12L)+ }+@Testfun duplicateRequestsShareOneExecution() = runTest {val coordinator = StalkerRequestCoordinator()diff --git a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.ktindex 99627ca0..e0c64156 100644--- a/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolverTest.kt@@ -703,6 +703,12 @@ class XtreamStreamUrlResolverTest {override suspend fun activate(id: Long) = Unitoverride suspend fun updateSyncTime(id: Long, timestamp: Long) = Unitoverride suspend fun updateEpgUrl(id: Long, epgUrl: String) = Unit+ override suspend fun invalidateCatalogLayoutDetection(id: Long) = Unit+ override suspend fun updateCatalogLayout(+ id: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ version: Int+ ) = Unit}private class FakeStalkerApiService : StalkerApiService {diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.ktindex bba912e2..573a006a 100644--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt@@ -45,6 +45,8 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.SyncMetadataimport com.streamvault.domain.model.VodDuplicateConfidenceimport com.streamvault.domain.model.VodDuplicateHandlingMode+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.model.VodCategoryLoadModeimport com.streamvault.domain.model.VodMovieVariantimport com.streamvault.domain.model.VodSyncModeimport com.streamvault.domain.model.VodVariantObservation@@ -673,8 +675,9 @@ class MovieRepositoryImplTest {}@Test- fun `browsing stalker movie category hydrates every advertised page before returning`() = runTest {+ fun `complete request hydrates every advertised stalker movie page before returning`() = runTest {whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))+ whenever(preferencesRepository.vodCategoryLoadMode).thenReturn(flowOf(VodCategoryLoadMode.PAGED))whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0),flowOf(14),@@ -695,9 +698,11 @@ class MovieRepositoryImplTest {whenever(movieDao.getFreshByCategoryCursorPage(7L, 42L, 40)).thenReturn(emptyList())whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))- createRepository().browseMovies(- LibraryBrowseQuery(providerId = 7L, categoryId = 42L, limit = 60)- ).first()+ createRepository().requestCategoryHydration(+ 7L,+ 42L,+ VodCategoryHydrationRequest.COMPLETE+ )(1..3).forEach { page ->verify(stalkerApiService).getVodStreamsPage(any(), any(), anyOrNull(), eq(page))diff --git a/data/src/test/java/com/streamvault/data/repository/VodRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/VodRepositoryImplTest.ktnew file mode 100644index 00000000..18478a2e--- /dev/null+++ b/data/src/test/java/com/streamvault/data/repository/VodRepositoryImplTest.kt@@ -0,0 +1,152 @@+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.MovieDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.dao.VodCatalogEntryDao+import com.streamvault.data.local.dao.VodCategoryHydrationDao+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.SeriesEntity+import com.streamvault.data.local.entity.VodCatalogEntryEntity+import com.streamvault.data.local.entity.VodCategoryHydrationEntity+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.sync.SyncManager+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Result+import com.streamvault.domain.model.VodCatalogItem+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.model.VodCategoryLoadMode+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.mock+import org.mockito.kotlin.verify+import org.mockito.kotlin.verifyNoInteractions+import org.mockito.kotlin.whenever+import org.mockito.kotlin.timeout++class VodRepositoryImplTest {+ private val movieDao = mock<MovieDao>()+ private val seriesDao = mock<SeriesDao>()+ private val hydrationDao = mock<VodCategoryHydrationDao>()+ private val entryDao = mock<VodCatalogEntryDao>()+ private val categoryDao = mock<CategoryDao>()+ private val preferences = mock<PreferencesRepository>()+ private val syncManager = mock<SyncManager>()++ private fun repository() = VodRepositoryImpl(+ movieDao,+ seriesDao,+ hydrationDao,+ entryDao,+ categoryDao,+ preferences,+ syncManager+ )++ @Test+ fun categoryItems_followPersistedProviderOrderAcrossTypes() = runTest {+ whenever(entryDao.observeByCategory(3, 100)).thenReturn(+ flowOf(+ listOf(+ VodCatalogEntryEntity(3, 100, "series-9", ContentType.SERIES, 9, 1, 0),+ VodCatalogEntryEntity(3, 100, "movie-7", ContentType.MOVIE, 7, 1, 1),+ VodCatalogEntryEntity(3, 100, "series-8", ContentType.SERIES, 8, 1, 2)+ )+ )+ )+ whenever(movieDao.observeByStreamIds(3, listOf(7L))).thenReturn(+ flowOf(listOf(MovieEntity(streamId = 7, providerId = 3, categoryId = 100, name = "Movie")))+ )+ whenever(seriesDao.observeBySeriesIds(3, listOf(9L, 8L))).thenReturn(+ flowOf(+ listOf(+ SeriesEntity(seriesId = 8, providerId = 3, categoryId = 100, name = "Second Series"),+ SeriesEntity(seriesId = 9, providerId = 3, categoryId = 100, name = "First Series")+ )+ )+ )++ val items = repository().getCategoryItems(3, 100).first()++ assertThat(items.map {+ when (it) {+ is VodCatalogItem.MovieItem -> it.movie.name+ is VodCatalogItem.SeriesItem -> it.series.name+ }+ }).containsExactly("First Series", "Movie", "Second Series").inOrder()+ verifyNoInteractions(syncManager)+ }++ @Test+ fun openInPagedMode_fetchesOnePageThenPrefetchesExactlyOnePage() = runTest {+ whenever(preferences.vodCategoryLoadMode).thenReturn(flowOf(VodCategoryLoadMode.PAGED))+ whenever(syncManager.hydrateUnifiedVodCategory(8, 201, VodCategoryHydrationRequest.OPEN))+ .thenReturn(Result.success(Unit))+ whenever(syncManager.hydrateUnifiedVodCategory(8, 201, VodCategoryHydrationRequest.NEXT_PAGE))+ .thenReturn(Result.success(Unit))++ repository().requestCategoryHydration(8, 201, VodCategoryHydrationRequest.OPEN)++ verify(syncManager).hydrateUnifiedVodCategory(8, 201, VodCategoryHydrationRequest.OPEN)+ verify(syncManager, timeout(1_000)).hydrateUnifiedVodCategory(+ 8,+ 201,+ VodCategoryHydrationRequest.NEXT_PAGE+ )+ }++ @Test+ fun hydration_exposesProviderPageSizeForAheadOfScrollPrefetch() = runTest {+ whenever(hydrationDao.observe(8, 201)).thenReturn(+ flowOf(+ VodCategoryHydrationEntity(+ providerId = 8,+ categoryId = 201,+ lastSuccessfulPage = 2,+ totalPages = 9,+ pageSize = 36,+ itemCount = 72+ )+ )+ )++ assertThat(repository().observeHydration(8, 201).first()?.pageSize).isEqualTo(36)+ }++ @Test+ fun completeOnOpenMode_usesCompleteRequestWithoutPagedOpen() = runTest {+ whenever(preferences.vodCategoryLoadMode).thenReturn(flowOf(VodCategoryLoadMode.COMPLETE_ON_OPEN))+ whenever(syncManager.hydrateUnifiedVodCategory(8, 202, VodCategoryHydrationRequest.COMPLETE))+ .thenReturn(Result.success(Unit))++ repository().requestCategoryHydration(8, 202, VodCategoryHydrationRequest.OPEN)++ verify(syncManager).hydrateUnifiedVodCategory(8, 202, VodCategoryHydrationRequest.COMPLETE)+ }++ @Test+ fun previewHydratesOneRawPage_andAppliesVodVisibility() = runTest {+ whenever(syncManager.hydrateUnifiedVodCategory(4, 101, VodCategoryHydrationRequest.OPEN))+ .thenReturn(Result.success(Unit))+ whenever(entryDao.observeByCategory(4, 101)).thenReturn(flowOf(emptyList()))+ repository().getCategoryPreview(4, 101, 10).first()+ verify(syncManager).hydrateUnifiedVodCategory(4, 101, VodCategoryHydrationRequest.OPEN)++ whenever(categoryDao.getByProviderAndType(4, ContentType.VOD.name)).thenReturn(+ flowOf(+ listOf(+ CategoryEntity(providerId = 4, categoryId = 101, name = "Visible", type = ContentType.VOD),+ CategoryEntity(providerId = 4, categoryId = 102, name = "Hidden", type = ContentType.VOD)+ )+ )+ )+ whenever(preferences.parentalControlLevel).thenReturn(flowOf(2))+ whenever(preferences.getHiddenCategoryIds(4, ContentType.VOD)).thenReturn(flowOf(setOf(102L)))++ assertThat(repository().getCategories(4).first().map { it.id }).containsExactly(101L)+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.ktindex cf6465df..262f2e21 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncCatalogStoreTest.kt@@ -72,6 +72,7 @@ class SyncCatalogStoreTest {name = "News",type = ContentType.LIVE,providerId = providerId,+ providerOrder = 4,syncFingerprint = "old-category")val currentChannel = ChannelEntity(@@ -93,6 +94,7 @@ class SyncCatalogStoreTest {categoryId = 101L,name = "World News",type = ContentType.LIVE,+ providerOrder = 9,syncFingerprint = "new-category"))@@ -109,6 +111,7 @@ class SyncCatalogStoreTest {assertThat(updatedCategories.firstValue.single()).isEqualTo(currentCategory.copy(name = "World News",+ providerOrder = 9,syncFingerprint = "new-category"))diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktindex ea69ae44..e946a55f 100644--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -19,6 +19,8 @@ import com.streamvault.data.local.dao.SeriesCategoryHydrationDaoimport com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.StalkerIndexJobDaoimport com.streamvault.data.local.dao.TmdbIdentityDao+import com.streamvault.data.local.dao.VodCategoryHydrationDao+import com.streamvault.data.local.dao.VodCatalogEntryDaoimport com.streamvault.data.local.dao.XtreamContentIndexDaoimport com.streamvault.data.local.dao.XtreamIndexJobDaoimport com.streamvault.data.local.dao.XtreamLiveOnboardingDao@@ -136,13 +138,20 @@ class SyncManagerTest {stalkerMacAddress: String): ProviderEntity? = nulloverride suspend fun updateEpgUrl(id: Long, epgUrl: String) = Unit+ override suspend fun invalidateCatalogLayoutDetection(id: Long) = Unit+ override suspend fun updateCatalogLayout(+ id: Long,+ layout: com.streamvault.domain.model.CatalogLayout,+ version: Int+ ) = Unit}companion object {fun sampleProvider(type: ProviderType = ProviderType.XTREAM_CODES) = ProviderEntity(id = 1L, name = "Test", type = type,serverUrl = "https://test.example.com:8080",- username = "demo", password = "demo"+ username = "demo", password = "demo",+ catalogLayoutDetectionVersion = com.streamvault.data.remote.stalker.StalkerProvider.CATALOG_LAYOUT_DETECTION_VERSION)fun stalkerSyntheticCategoryId(providerId: Long, type: ContentType, seed: String): Long {@@ -235,6 +244,8 @@ class SyncManagerTest {private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao = mock()private val movieCategoryHydrationDao: MovieCategoryHydrationDao = mock()private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao = mock()+ private val vodCategoryHydrationDao: VodCategoryHydrationDao = mock()+ private val vodCatalogEntryDao: VodCatalogEntryDao = mock()private val epgRepo: EpgRepository = mock()private val epgSourceRepo: EpgSourceRepository = mock()private val preferencesRepo: PreferencesRepository = mock()@@ -360,6 +371,8 @@ class SyncManagerTest {categoryDao = categoryDao,movieCategoryHydrationDao = movieCategoryHydrationDao,seriesCategoryHydrationDao = seriesCategoryHydrationDao,+ vodCategoryHydrationDao = vodCategoryHydrationDao,+ vodCatalogEntryDao = vodCatalogEntryDao,catalogSyncDao = catalogSyncDao,tmdbIdentityDao = tmdbIdentityDao,xtreamContentIndexDao = xtreamContentIndexDao,diff --git a/domain/src/main/java/com/streamvault/domain/model/Category.kt b/domain/src/main/java/com/streamvault/domain/model/Category.ktindex 0a6f005c..2dc0950d 100644--- a/domain/src/main/java/com/streamvault/domain/model/Category.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Category.kt@@ -8,6 +8,7 @@ data class Category(val type: ContentType = ContentType.LIVE,val isVirtual: Boolean = false,val count: Int = 0,+ val providerOrder: Int = 0,val isAdult: Boolean = false,val isUserProtected: Boolean = false) {diff --git a/domain/src/main/java/com/streamvault/domain/model/ContentType.kt b/domain/src/main/java/com/streamvault/domain/model/ContentType.ktindex 283a509d..229c900c 100644--- a/domain/src/main/java/com/streamvault/domain/model/ContentType.kt+++ b/domain/src/main/java/com/streamvault/domain/model/ContentType.kt@@ -2,6 +2,7 @@ package com.streamvault.domain.modelenum class ContentType {LIVE,+ VOD,MOVIE,SERIES,SERIES_EPISODEdiff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.ktindex 29e3a226..8b1800cb 100644--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt@@ -61,6 +61,8 @@ data class Provider(val xtreamFastSyncEnabled: Boolean = true,val xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,val m3uVodClassificationEnabled: Boolean = false,+ val catalogLayout: CatalogLayout = CatalogLayout.SPLIT,+ val catalogLayoutDetectionVersion: Int = 0,val status: ProviderStatus = ProviderStatus.UNKNOWN,val lastSyncedAt: Long = 0L,val createdAt: Long = System.currentTimeMillis()@@ -75,6 +77,13 @@ data class Provider("Provider(id=$id, name=$name, type=$type, status=$status, isActive=$isActive)"}+/** Provider-scoped presentation of the VOD catalog. */+enum class CatalogLayout {+ UNKNOWN,+ SPLIT,+ UNIFIED_VOD+}+enum class ProviderType {XTREAM_CODES,M3U,diff --git a/domain/src/main/java/com/streamvault/domain/model/Series.kt b/domain/src/main/java/com/streamvault/domain/model/Series.ktindex b5d3d709..d61090f6 100644--- a/domain/src/main/java/com/streamvault/domain/model/Series.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Series.kt@@ -28,7 +28,10 @@ data class Series(val selectedVariantId: Long? = null,val variants: List<VodSeriesVariant> = emptyList(),val duplicateConfidence: VodDuplicateConfidence = VodDuplicateConfidence.NONE,- val variantLabel: String? = null+ val variantLabel: String? = null,+ val catalogOrigin: SeriesCatalogOrigin = SeriesCatalogOrigin.NATIVE,+ /** Provider-neutral logical playback URL used when episode rows do not carry their own command. */+ val episodePlaybackTemplateUrl: String? = null) {init {require(rating in 0f..10f) { "rating must be between 0 and 10" }@@ -36,6 +39,11 @@ data class Series(}}+enum class SeriesCatalogOrigin {+ NATIVE,+ VOD_DERIVED+}+data class Season(val seasonNumber: Int,val name: String = "Season $seasonNumber",diff --git a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.ktindex c76f27c5..bcb73ebc 100644--- a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt+++ b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt@@ -38,7 +38,13 @@ data class PlaybackTransportPolicy(val mode: PlaybackTransportMode,val origin: StalkerTransportOrigin,/** Base64 SHA-256 of the approved SubjectPublicKeyInfo. */- val spkiSha256: String? = null+ val spkiSha256: String? = null,+ /**+ * IPTV providers often redirect an approved HTTP portal URL to a raw-IP or CDN HTTP+ * stream. The player may follow those redirects only when the user explicitly accepted+ * cleartext HTTP transport.+ */+ val allowCrossOriginHttpRedirects: Boolean = false) {init {if (mode == PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS) {@@ -46,6 +52,14 @@ data class PlaybackTransportPolicy("Accepted unverified HTTPS playback requires an SPKI fingerprint"}}+ if (allowCrossOriginHttpRedirects) {+ require(mode == PlaybackTransportMode.USER_ACCEPTED_HTTP) {+ "Cross-origin playback redirects require accepted HTTP transport"+ }+ require(origin.scheme.equals("http", ignoreCase = true)) {+ "Cross-origin playback redirects require an HTTP origin"+ }+ }}}diff --git a/domain/src/main/java/com/streamvault/domain/model/VodCatalog.kt b/domain/src/main/java/com/streamvault/domain/model/VodCatalog.ktnew file mode 100644index 00000000..fd15ba28--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/model/VodCatalog.kt@@ -0,0 +1,83 @@+package com.streamvault.domain.model++sealed interface VodCatalogItem {+ val stableId: String+ val title: String+ val categoryId: Long?+ val sortTimestamp: Long++ data class MovieItem(val movie: Movie) : VodCatalogItem {+ override val stableId: String = "movie:${movie.id}"+ override val title: String = movie.name+ override val categoryId: Long? = movie.categoryId+ override val sortTimestamp: Long = movie.addedAt+ }++ data class SeriesItem(val series: Series) : VodCatalogItem {+ override val stableId: String = "series:${series.id}"+ override val title: String = series.name+ override val categoryId: Long? = series.categoryId+ override val sortTimestamp: Long = series.lastModified+ }+}++data class VodCatalogEntry(+ val categoryId: Long,+ val rawItemId: String,+ val itemType: ContentType,+ val targetId: Long,+ val rawPage: Int,+ val rawIndex: Int+)++data class VodCategoryHydration(+ val lastSuccessfulPage: Int = 0,+ val totalPages: Int = 0,+ val pageSize: Int = 0,+ val itemCount: Int = 0,+ val isComplete: Boolean = false,+ val hasMovies: Boolean = false,+ val hasSeries: Boolean = false,+ val isLoading: Boolean = false,+ val error: String? = null+) {+ val hasMoreRemote: Boolean get() = !isComplete+ val isInitialLoading: Boolean get() = isLoading && itemCount == 0+ val isAppending: Boolean get() = isLoading && itemCount > 0+}++enum class VodCategoryLoadMode(val storageValue: String) {+ PAGED("paged"),+ COMPLETE_ON_OPEN("complete_on_open");++ companion object {+ fun fromStorage(value: String?): VodCategoryLoadMode =+ entries.firstOrNull { it.storageValue.equals(value, ignoreCase = true) } ?: PAGED+ }+}++enum class VodCategoryHydrationRequest {+ OPEN,+ NEXT_PAGE,+ COMPLETE+}++enum class VodCategoryKind {+ UNKNOWN,+ MOVIES,+ SERIES,+ MIXED;++ companion object {+ fun from(items: List<VodCatalogItem>): VodCategoryKind {+ val hasMovies = items.any { it is VodCatalogItem.MovieItem }+ val hasSeries = items.any { it is VodCatalogItem.SeriesItem }+ return when {+ hasMovies && hasSeries -> MIXED+ hasMovies -> MOVIES+ hasSeries -> SERIES+ else -> UNKNOWN+ }+ }+ }+}diff --git a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.ktindex 90072512..1a01ba33 100644--- a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt@@ -8,7 +8,10 @@ import com.streamvault.domain.model.PagedResultimport com.streamvault.domain.model.Resultimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.VodMovieVariant+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequestimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOfinterface MovieRepository {fun getMovies(providerId: Long): Flow<List<Movie>>@@ -25,6 +28,12 @@ interface MovieRepository {fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>>fun getLibraryCount(providerId: Long): Flow<Int>fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>>+ fun observeCategoryHydration(providerId: Long, categoryId: Long): Flow<VodCategoryHydration?> = flowOf(null)+ suspend fun requestCategoryHydration(+ providerId: Long,+ categoryId: Long,+ request: VodCategoryHydrationRequest+ ): Result<Unit> = Result.success(Unit)fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>suspend fun getMovie(movieId: Long): Movie?suspend fun getMovieVariants(movieId: Long): List<VodMovieVariant> = emptyList()diff --git a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.ktindex ae4aa833..e1a8d2ef 100644--- a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt+++ b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt@@ -8,7 +8,10 @@ import com.streamvault.domain.model.Resultimport com.streamvault.domain.model.Seriesimport com.streamvault.domain.model.SeriesDetailPresentationHintimport com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequestimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOfinterface SeriesRepository {fun getSeries(providerId: Long): Flow<List<Series>>@@ -23,6 +26,12 @@ interface SeriesRepository {fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>>fun getLibraryCount(providerId: Long): Flow<Int>fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>>+ fun observeCategoryHydration(providerId: Long, categoryId: Long): Flow<VodCategoryHydration?> = flowOf(null)+ suspend fun requestCategoryHydration(+ providerId: Long,+ categoryId: Long,+ request: VodCategoryHydrationRequest+ ): Result<Unit> = Result.success(Unit)fun searchSeries(providerId: Long, query: String): Flow<List<Series>>suspend fun getSeriesById(seriesId: Long): Series?suspend fun getEpisodeById(episodeId: Long): Episode?diff --git a/domain/src/main/java/com/streamvault/domain/repository/VodRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/VodRepository.ktnew file mode 100644index 00000000..4cd843c7--- /dev/null+++ b/domain/src/main/java/com/streamvault/domain/repository/VodRepository.kt@@ -0,0 +1,18 @@+package com.streamvault.domain.repository++import com.streamvault.domain.model.Category+import com.streamvault.domain.model.VodCatalogItem+import com.streamvault.domain.model.VodCategoryHydration+import com.streamvault.domain.model.VodCategoryHydrationRequest+import com.streamvault.domain.model.Result+import kotlinx.coroutines.flow.Flow++interface VodRepository {+ fun getCategories(providerId: Long): Flow<List<Category>>+ fun getCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<VodCatalogItem>>+ fun getCategoryItems(providerId: Long, categoryId: Long): Flow<List<VodCatalogItem>>+ fun observeHydration(providerId: Long, categoryId: Long): Flow<VodCategoryHydration?>+ suspend fun ensurePreview(providerId: Long, categoryId: Long): Result<Unit>+ suspend fun requestCategoryHydration(providerId: Long, categoryId: Long, request: VodCategoryHydrationRequest): Result<Unit>+ suspend fun hydrateCompletely(providerId: Long, categoryId: Long): Result<Unit>+}diff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.ktindex ade8a6da..07554aa7 100644--- a/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetContinueWatching.kt@@ -100,19 +100,22 @@ class GetContinueWatching @Inject constructor(ContentType.SERIES,ContentType.SERIES_EPISODE -> "series:${entry.seriesId?.takeIf { it > 0L } ?: entry.contentId}"ContentType.LIVE -> "live:${entry.contentId}"+ ContentType.VOD -> "vod:${entry.contentId}"}private fun PlaybackHistory.isResumeEligible(): Boolean = when (contentType) {ContentType.MOVIE,ContentType.SERIES_EPISODE -> resumePositionMs > 0LContentType.SERIES -> true- ContentType.LIVE -> false+ ContentType.LIVE,+ ContentType.VOD -> false}private fun PlaybackHistory.isCompleted(): Boolean = when (contentType) {ContentType.MOVIE,ContentType.SERIES_EPISODE -> isPlaybackComplete(resumePositionMs, totalDurationMs)ContentType.SERIES,- ContentType.LIVE -> false+ ContentType.LIVE,+ ContentType.VOD -> false}-}\ No newline at end of file+}diff --git a/domain/src/test/java/com/streamvault/domain/model/VodCatalogTest.kt b/domain/src/test/java/com/streamvault/domain/model/VodCatalogTest.ktnew file mode 100644index 00000000..f35879dc--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/model/VodCatalogTest.kt@@ -0,0 +1,33 @@+package com.streamvault.domain.model++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class VodCatalogTest {+ @Test+ fun categoryKind_isDerivedFromAllTypedItems() {+ val movie = VodCatalogItem.MovieItem(Movie(id = 1, name = "Movie", streamUrl = "movie"))+ val series = VodCatalogItem.SeriesItem(Series(id = 2, name = "Series"))++ assertThat(VodCategoryKind.from(emptyList())).isEqualTo(VodCategoryKind.UNKNOWN)+ assertThat(VodCategoryKind.from(listOf(movie))).isEqualTo(VodCategoryKind.MOVIES)+ assertThat(VodCategoryKind.from(listOf(series))).isEqualTo(VodCategoryKind.SERIES)+ assertThat(VodCategoryKind.from(listOf(movie, series))).isEqualTo(VodCategoryKind.MIXED)+ }++ @Test+ fun movieAndSeriesStableIds_doNotCollide() {+ val movie = VodCatalogItem.MovieItem(Movie(id = 7, name = "Shared", streamUrl = "movie"))+ val series = VodCatalogItem.SeriesItem(Series(id = 7, name = "Shared"))++ assertThat(movie.stableId).isNotEqualTo(series.stableId)+ }++ @Test+ fun categoryLoadMode_defaultsUnknownValuesToPaged() {+ assertThat(VodCategoryLoadMode.fromStorage(null)).isEqualTo(VodCategoryLoadMode.PAGED)+ assertThat(VodCategoryLoadMode.fromStorage("future-mode")).isEqualTo(VodCategoryLoadMode.PAGED)+ assertThat(VodCategoryLoadMode.fromStorage("complete_on_open"))+ .isEqualTo(VodCategoryLoadMode.COMPLETE_ON_OPEN)+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.ktindex 5e69a38e..e501c0ef 100644--- a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt+++ b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt@@ -23,8 +23,20 @@ object StreamTypeResolver {)private val dashMimeHints = listOf("application/dash+xml")private val smoothStreamingMimeHints = listOf("application/vnd.ms-sstr+xml", "text/xml")- private val hlsQueryHints = listOf("ext=m3u8", "output=m3u8", "format=m3u8", "type=m3u8")- private val tsQueryHints = listOf("ext=ts", "output=ts", "format=ts", "type=ts")+ private val hlsQueryHints = listOf(+ "ext=m3u8",+ "extension=m3u8",+ "output=m3u8",+ "format=m3u8",+ "type=m3u8"+ )+ private val tsQueryHints = listOf(+ "ext=ts",+ "extension=ts",+ "output=ts",+ "format=ts",+ "type=ts"+ )private val hlsLiveAliases = setOf("sd", "hd", "fhd", "uhd", "4k", "playlist", "master", "index")fun resolve(streamInfo: StreamInfo, mimeType: String? = null): ResolvedStreamType {diff --git a/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt b/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.ktindex 07bcdf1d..b2434b20 100644--- a/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt+++ b/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt@@ -2,15 +2,19 @@ package com.streamvault.player.playbackimport com.streamvault.domain.model.PlaybackTransportModeimport com.streamvault.domain.model.PlaybackTransportPolicy+import com.streamvault.domain.model.StalkerTransportOriginimport java.io.IOExceptionimport java.security.MessageDigestimport java.security.SecureRandomimport java.security.cert.CertificateExceptionimport java.security.cert.X509Certificateimport java.util.Base64+import java.util.Localeimport javax.net.ssl.HostnameVerifierimport javax.net.ssl.SSLContextimport javax.net.ssl.X509TrustManager+import okhttp3.HttpUrl+import okhttp3.Interceptorimport okhttp3.OkHttpClientfun OkHttpClient.Builder.applyUnsafeTlsBypass(): OkHttpClient.Builder {@@ -34,17 +38,9 @@ fun OkHttpClient.Builder.applyUnsafeTlsBypass(): OkHttpClient.Builder {fun OkHttpClient.Builder.applyPlaybackTransportPolicy(policy: PlaybackTransportPolicy): OkHttpClient.Builder {- addNetworkInterceptor { chain ->- val requestOrigin = chain.request().url- val expected = policy.origin- if (!requestOrigin.scheme.equals(expected.scheme, ignoreCase = true) ||- !requestOrigin.host.equals(expected.host, ignoreCase = true) ||- requestOrigin.port != expected.port- ) {- throw IOException("Playback transport approval does not cover the redirected origin.")- }- chain.proceed(chain.request())- }+ followRedirects(false)+ .followSslRedirects(false)+ .addInterceptor(PlaybackTransportRedirectInterceptor(policy))if (policy.mode != PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS) {return this}@@ -82,6 +78,104 @@ fun OkHttpClient.Builder.applyPlaybackTransportPolicy(}}+internal fun allowsPlaybackCrossOriginHttpRedirect(+ source: StalkerTransportOrigin,+ target: StalkerTransportOrigin,+ policy: PlaybackTransportPolicy+): Boolean =+ !samePlaybackOrigin(source, target) &&+ policy.allowCrossOriginHttpRedirects &&+ policy.mode == PlaybackTransportMode.USER_ACCEPTED_HTTP &&+ policy.origin.scheme.equals("http", ignoreCase = true) &&+ target.scheme.equals("http", ignoreCase = true)++private class PlaybackTransportRedirectInterceptor(+ private val policy: PlaybackTransportPolicy+) : Interceptor {+ override fun intercept(chain: Interceptor.Chain): okhttp3.Response {+ var request = chain.request()+ var crossOriginRedirectApproved = false+ repeat(MAX_REDIRECTS + 1) { hop ->+ val sourceOrigin = request.url.toPlaybackOrigin()+ if (!samePlaybackOrigin(sourceOrigin, policy.origin) &&+ !(crossOriginRedirectApproved &&+ isAllowedCrossOriginHttpPlaybackOrigin(sourceOrigin, policy))+ ) {+ throw IOException("Playback transport approval does not cover the redirected origin.")+ }++ val response = chain.proceed(request)+ if (response.code !in REDIRECT_CODES) return response+ if (hop >= MAX_REDIRECTS) {+ response.close()+ throw IOException("Playback redirect limit exceeded.")+ }+ val target = response.header("Location")+ ?.let(request.url::resolve)+ ?: return response+ val targetOrigin = target.toPlaybackOrigin()+ val sameOrigin = samePlaybackOrigin(sourceOrigin, targetOrigin)+ val redirectSourceApproved = samePlaybackOrigin(sourceOrigin, policy.origin) ||+ crossOriginRedirectApproved+ if (!sameOrigin &&+ (!redirectSourceApproved ||+ !allowsPlaybackCrossOriginHttpRedirect(sourceOrigin, targetOrigin, policy))+ ) {+ response.close()+ throw IOException("Playback transport approval does not cover the redirected origin.")+ }+ if (!sameOrigin) {+ crossOriginRedirectApproved = true+ }+ response.close()+ request = request.newBuilder()+ .url(target)+ .apply {+ if (!sameOrigin) {+ SENSITIVE_REDIRECT_HEADERS.forEach(::removeHeader)+ }+ }+ .build()+ }+ throw IOException("Playback redirect limit exceeded.")+ }++ private companion object {+ const val MAX_REDIRECTS = 5+ val REDIRECT_CODES = setOf(300, 301, 302, 303, 307, 308)+ val SENSITIVE_REDIRECT_HEADERS = listOf(+ "Authorization",+ "Cookie",+ "X-User-Agent",+ "X-Device-Id",+ "X-Signature"+ )+ }+}++private fun isAllowedCrossOriginHttpPlaybackOrigin(+ origin: StalkerTransportOrigin,+ policy: PlaybackTransportPolicy+): Boolean =+ policy.allowCrossOriginHttpRedirects &&+ policy.mode == PlaybackTransportMode.USER_ACCEPTED_HTTP &&+ origin.scheme.equals("http", ignoreCase = true)++private fun samePlaybackOrigin(+ first: StalkerTransportOrigin,+ second: StalkerTransportOrigin+): Boolean =+ first.scheme.equals(second.scheme, ignoreCase = true) &&+ first.host.equals(second.host, ignoreCase = true) &&+ first.port == second.port++private fun HttpUrl.toPlaybackOrigin(): StalkerTransportOrigin =+ StalkerTransportOrigin(+ scheme = scheme.lowercase(Locale.ROOT),+ host = host.lowercase(Locale.ROOT),+ port = port+ )+private fun X509Certificate.playbackSpkiSha256(): String ="sha256/" + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(publicKey.encoded)diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.ktindex 844b72d4..fd8c1811 100644--- a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt@@ -1,6 +1,9 @@package com.streamvault.player.playbackimport com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackTransportMode+import com.streamvault.domain.model.PlaybackTransportPolicy+import com.streamvault.domain.model.StalkerTransportOriginimport org.junit.Testclass PlayerDataSourceFactoryProviderTest {@@ -82,4 +85,38 @@ class PlayerDataSourceFactoryProviderTest {assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.PROGRESSIVE)).isFalse()assertThat(shouldWrapDataSourceReadStats(ResolvedStreamType.DASH)).isFalse()}++ @Test+ fun `accepted HTTP transport permits provider cross-origin HTTP redirect`() {+ val policy = PlaybackTransportPolicy(+ mode = PlaybackTransportMode.USER_ACCEPTED_HTTP,+ origin = StalkerTransportOrigin("http", "portal.example.com", 80),+ allowCrossOriginHttpRedirects = true+ )++ assertThat(+ allowsPlaybackCrossOriginHttpRedirect(+ source = policy.origin,+ target = StalkerTransportOrigin("http", "198.51.100.7", 80),+ policy = policy+ )+ ).isTrue()+ }++ @Test+ fun `cross-origin redirect permission does not weaken HTTPS transport`() {+ val policy = PlaybackTransportPolicy(+ mode = PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS,+ origin = StalkerTransportOrigin("https", "portal.example.com", 443),+ spkiSha256 = "sha256/test"+ )++ assertThat(+ allowsPlaybackCrossOriginHttpRedirect(+ source = policy.origin,+ target = StalkerTransportOrigin("http", "198.51.100.7", 80),+ policy = policy+ )+ ).isFalse()+ }}diff --git a/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.ktindex 3b44421a..990bfafe 100644--- a/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt@@ -47,6 +47,24 @@ class StreamTypeResolverTest {.isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)}+ @Test+ fun `stalker extension ts query resolves to MPEG TS live`() {+ assertThat(+ StreamTypeResolver.resolve(+ "http://portal.example.com/play/live.php?stream=1544246&extension=ts&play_token=token"+ )+ ).isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)+ }++ @Test+ fun `stalker extension m3u8 query resolves to HLS`() {+ assertThat(+ StreamTypeResolver.resolve(+ "http://portal.example.com/play/live.php?stream=1544246&extension=m3u8"+ )+ ).isEqualTo(ResolvedStreamType.HLS)+ }+@Testfun `mp4 resolves to progressive`() {assertThat(StreamTypeResolver.resolve("http://example.com/movie.mp4"))